diff --git a/LICENSES/vendor/gopkg.in/yaml.v2/LICENSE b/LICENSES/vendor/cel.dev/expr/LICENSE similarity index 98% rename from LICENSES/vendor/gopkg.in/yaml.v2/LICENSE rename to LICENSES/vendor/cel.dev/expr/LICENSE index 88be4ca082..73f72e4c66 100644 --- a/LICENSES/vendor/gopkg.in/yaml.v2/LICENSE +++ b/LICENSES/vendor/cel.dev/expr/LICENSE @@ -1,4 +1,5 @@ -= vendor/gopkg.in/yaml.v2 licensed under: = += vendor/cel.dev/expr licensed under: = + Apache License Version 2.0, January 2004 @@ -180,7 +181,7 @@ APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" + boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a @@ -188,7 +189,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright {yyyy} {name of copyright owner} + Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -202,4 +203,4 @@ See the License for the specific language governing permissions and limitations under the License. -= vendor/gopkg.in/yaml.v2/LICENSE e3fc50a88d0a364313df4b21ef20c29e += vendor/cel.dev/expr/LICENSE 3b83ef96387f14655fc854ddc3c6bd57 diff --git a/LICENSES/vendor/github.com/golang/groupcache/LICENSE b/LICENSES/vendor/github.com/golang/groupcache/LICENSE deleted file mode 100644 index 98ae0d6e00..0000000000 --- a/LICENSES/vendor/github.com/golang/groupcache/LICENSE +++ /dev/null @@ -1,195 +0,0 @@ -= vendor/github.com/golang/groupcache 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: - -You must give any other recipients of the Work or Derivative Works a copy of -this License; and -You must cause any modified files to carry prominent notices stating that You -changed the files; and -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 -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 - -APPENDIX: How to apply the Apache License to your work - -To apply the Apache License to your work, attach the following boilerplate -notice, with the fields enclosed by brackets "[]" replaced with your own -identifying information. (Don't include the brackets!) The text should be -enclosed in the appropriate comment syntax for the file format. We also -recommend that a file or class name and description of purpose be included on -the same "printed page" as the copyright notice for easier identification within -third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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/golang/groupcache/LICENSE 19cbd64715b51267a47bf3750cc6a8a5 diff --git a/LICENSES/vendor/github.com/Azure/go-autorest/autorest/mocks/LICENSE b/LICENSES/vendor/github.com/google/btree/LICENSE similarity index 93% rename from LICENSES/vendor/github.com/Azure/go-autorest/autorest/mocks/LICENSE rename to LICENSES/vendor/github.com/google/btree/LICENSE index 635cf4ef3d..db41454298 100644 --- a/LICENSES/vendor/github.com/Azure/go-autorest/autorest/mocks/LICENSE +++ b/LICENSES/vendor/github.com/google/btree/LICENSE @@ -1,4 +1,4 @@ -= vendor/github.com/Azure/go-autorest/autorest/mocks licensed under: = += vendor/github.com/google/btree licensed under: = Apache License @@ -178,7 +178,18 @@ END OF TERMS AND CONDITIONS - Copyright 2015 Microsoft Corporation + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -192,4 +203,4 @@ 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/google/btree/LICENSE 3b83ef96387f14655fc854ddc3c6bd57 diff --git a/LICENSES/vendor/github.com/imdario/mergo/LICENSE b/LICENSES/vendor/github.com/imdario/mergo/LICENSE deleted file mode 100644 index 591ec7bb6c..0000000000 --- a/LICENSES/vendor/github.com/imdario/mergo/LICENSE +++ /dev/null @@ -1,32 +0,0 @@ -= vendor/github.com/imdario/mergo licensed under: = - -Copyright (c) 2013 Dario Castañé. All rights reserved. -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -= vendor/github.com/imdario/mergo/LICENSE ff13e03bb57bf9c52645f2f942afa28b diff --git a/LICENSES/vendor/go.uber.org/zap/LICENSE b/LICENSES/vendor/go.uber.org/zap/LICENSE index 0c8aeedad2..9324cd1464 100644 --- a/LICENSES/vendor/go.uber.org/zap/LICENSE +++ b/LICENSES/vendor/go.uber.org/zap/LICENSE @@ -20,4 +20,4 @@ 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/go.uber.org/zap/LICENSE.txt 5e8153e456a82529ea845e0d511abb69 += vendor/go.uber.org/zap/LICENSE 5e8153e456a82529ea845e0d511abb69 diff --git a/go.mod b/go.mod index 2c51d5bb4a..ccba2c1dba 100644 --- a/go.mod +++ b/go.mod @@ -17,9 +17,6 @@ require ( github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.6.0 github.com/Azure/go-autorest/autorest v0.11.29 - github.com/Azure/go-autorest/autorest/adal v0.9.24 - github.com/Azure/go-autorest/autorest/mocks v0.4.2 - github.com/Azure/go-autorest/tracing v0.6.0 github.com/evanphx/json-patch v5.9.0+incompatible github.com/fsnotify/fsnotify v1.8.0 github.com/go-logr/logr v1.4.2 @@ -27,6 +24,7 @@ require ( github.com/onsi/ginkgo/v2 v2.22.0 github.com/onsi/gomega v1.36.0 github.com/prometheus/client_golang v1.20.5 + github.com/samber/lo v1.47.0 github.com/spf13/cobra v1.8.1 github.com/spf13/pflag v1.0.5 github.com/stretchr/testify v1.10.0 @@ -71,10 +69,12 @@ require ( github.com/Azure/azure-storage-queue-go v0.0.0-20230531184854-c06a8eff66fe // indirect github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect github.com/Azure/go-autorest v14.2.0+incompatible // indirect + github.com/Azure/go-autorest/autorest/adal v0.9.24 // indirect github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect github.com/Azure/go-autorest/autorest/to v0.4.0 // indirect github.com/Azure/go-autorest/autorest/validation v0.3.1 // indirect github.com/Azure/go-autorest/logger v0.2.1 // indirect + github.com/Azure/go-autorest/tracing v0.6.0 // indirect github.com/AzureAD/microsoft-authentication-library-for-go v1.3.1 // indirect github.com/NYTimes/gziphandler v1.1.1 // indirect github.com/antlr4-go/antlr/v4 v4.13.0 // indirect @@ -124,7 +124,6 @@ require ( github.com/prometheus/client_model v0.6.1 // indirect github.com/prometheus/common v0.60.1 // indirect github.com/prometheus/procfs v0.15.1 // indirect - github.com/samber/lo v1.38.1 // indirect github.com/shopspring/decimal v1.3.1 // indirect github.com/stoewer/go-strcase v1.3.0 // indirect github.com/x448/float16 v0.8.4 // indirect diff --git a/go.sum b/go.sum index 5d3afd4a6b..fdecfa23aa 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,6 @@ cel.dev/expr v0.18.0 h1:CJ6drgk+Hf96lkLikr4rFf19WrU0BOWEihyZnI2TAzo= cel.dev/expr v0.18.0/go.mod h1:MrpN08Q+lEBs+bGYdLxxHkZoUSsCp0nSKTs0nTymJgw= +cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= github.com/Azure/azure-kusto-go v0.16.1 h1:vCBWcQghmC1qIErUUgVNWHxGhZVStu1U/hki6iBA14k= github.com/Azure/azure-kusto-go v0.16.1/go.mod h1:9F2zvXH8B6eWzgI1S4k1ZXAIufnBZ1bv1cW1kB1n3D0= github.com/Azure/azure-pipeline-go v0.1.8/go.mod h1:XA1kFWRVhSK+KNFiOhfv83Fv8L9achrP7OxIzeTn1Yg= @@ -81,8 +82,12 @@ github.com/AzureAD/microsoft-authentication-library-for-go v1.3.1 h1:gUDtaZk8het github.com/AzureAD/microsoft-authentication-library-for-go v1.3.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I= github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= +github.com/alecthomas/kingpin/v2 v2.4.0/go.mod h1:0gyi0zQnjuFk8xrkNKamJoyUo382HRL7ATRpFZCw6tE= +github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/antlr4-go/antlr/v4 v4.13.0 h1:lxCg3LAv+EUK6t1i0y1V6/SLeUi0eKEKdhQAlS8TVTI= github.com/antlr4-go/antlr/v4 v4.13.0/go.mod h1:pfChB/xh/Unjila75QW7+VU4TSnWnnk9UTnmpPaOR2g= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= @@ -91,8 +96,12 @@ github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/census-instrumentation/opencensus-proto v0.4.1/go.mod h1:4T9NM4+4Vw91VeyqjLS6ao50K5bOcLKN6Q42XnYaRYw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= +github.com/cncf/xds/go v0.0.0-20240423153145-555b57ec207b/go.mod h1:W+zGtBO5Y1IgJhy4+A9GOqVhqLpfZi+vwmdNXUehLA8= +github.com/coreos/go-oidc v2.2.1+incompatible/go.mod h1:CgnwVTmzoESiwO9qyAFEMiHoZ1nMCKZlZ9V6mm3/LKc= github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4= github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec= github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs= @@ -112,6 +121,8 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/emicklei/go-restful/v3 v3.12.1 h1:PJMDIM/ak7btuL8Ex0iYET9hxM3CI2sjZtzpL63nKAU= github.com/emicklei/go-restful/v3 v3.12.1/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/envoyproxy/go-control-plane v0.12.0/go.mod h1:ZBTaoJ23lqITozF0M6G4/IragXCQKCnYbmlmtHvwRG0= +github.com/envoyproxy/protoc-gen-validate v1.0.4/go.mod h1:qys6tmnRsYrQqIhm2bvKZH4Blx/1gTIZ2UKVY1M+Yew= github.com/evanphx/json-patch v5.9.0+incompatible h1:fBXyNpNMuTTDdquAq/uisOr2lShz4oaXpDTX2bLe7ls= github.com/evanphx/json-patch v5.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= @@ -120,6 +131,8 @@ github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/ github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= +github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= +github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -146,6 +159,7 @@ github.com/golang-jwt/jwt/v4 v4.5.1 h1:JdqV9zKUdtaa9gdPlywC3aeoEsR681PlKC+4F5gQg github.com/golang-jwt/jwt/v4 v4.5.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/golang/glog v1.2.1/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/btree v1.0.1 h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4= @@ -166,6 +180,7 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 h1:+9834+KizmvFV7pXQGSXQTsaWhq2GjuNUt0aUU0YBYw= github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho= @@ -174,14 +189,17 @@ github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4 github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 h1:bkypFPDjIYGfCYD5mRBvpqxfYX1YCS1PXdKYWi8FsN0= github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0/go.mod h1:P+Lt/0by1T8bfcF3z737NnSbmxQAppXMRziHUxPOC8k= +github.com/ianlancetaylor/demangle v0.0.0-20240312041847-bd984b5ce465/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jonboulle/clockwork v0.4.0 h1:p4Cf1aMWXnXAUh8lVfewRBx1zaTSYKrKMF2g3ST4RZ4= github.com/jonboulle/clockwork v0.4.0/go.mod h1:xgRqUGwRcjKCO1vbZUEtSLrqKoPSsUpK7fnezOII0kc= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= github.com/keybase/go-keychain v0.0.0-20231219164618-57a3676c3af6 h1:IsMZxCuZqKuao2vNdfD82fjjgPLfyHLpR41Z88viRWs= github.com/keybase/go-keychain v0.0.0-20231219164618-57a3676c3af6/go.mod h1:3VeWNIJaW+O5xpRQbPp0Ybqu1vJd/pm7s2F473HRrkw= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= @@ -199,6 +217,8 @@ github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJ github.com/mattn/go-ieproxy v0.0.1/go.mod h1:pYabZ6IHcRpFh7vIaLfK7rdcWgFEb3SFJ6/gNWuh88E= github.com/mattn/go-ieproxy v0.0.11 h1:MQ/5BuGSgDAHZOJe6YY80IF2UVCfGkwfo6AeD7HtHYo= github.com/mattn/go-ieproxy v0.0.11/go.mod h1:/NsJd+kxZBmjMc5hrJCKMbP57B84rvq9BiDRbtO9AS0= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/moby/spdystream v0.5.0/go.mod h1:xBAYlnt/ay+11ShkdFKNAG7LsyK/tmNBVvVOwrfMgdI= github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -206,12 +226,16 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/montanaflynn/stats v0.7.0/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= github.com/onsi/ginkgo/v2 v2.22.0 h1:Yed107/8DjTr0lKCNt7Dn8yQ6ybuDRQoMGrNFKzMfHg= github.com/onsi/ginkgo/v2 v2.22.0/go.mod h1:7Du3c42kxCUegi0IImZ1wUQzMBVecgIHjR1C+NkhLQo= github.com/onsi/gomega v1.36.0 h1:Pb12RlruUtj4XUuPUqeEWc6j5DkVVVA49Uf6YLfC95Y= github.com/onsi/gomega v1.36.0/go.mod h1:PvZbdDc8J6XJEpDK4HCuRBm8a6Fzp9/DmhC9C7yFlog= +github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= @@ -219,6 +243,7 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pquerna/cachecontrol v0.1.0/go.mod h1:NrUG3Z7Rdu85UNR3vm7SOsl1nFIeSiQnrHV5K9mBcUI= github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y= github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE= github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= @@ -229,11 +254,12 @@ github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0leargg github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= github.com/redis/go-redis/v9 v9.6.1 h1:HHDteefn6ZkTtY5fGUE8tj8uy85AHk6zP7CpzIAM0y4= github.com/redis/go-redis/v9 v9.6.1/go.mod h1:0C0c6ycQsdpVNQpxb1njEQIqkx5UcsM8FJCQLgE9+RA= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/samber/lo v1.38.1 h1:j2XEAqXKb09Am4ebOg31SpvzUTTs6EN3VfgeLUhPdXM= -github.com/samber/lo v1.38.1/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA= +github.com/samber/lo v1.47.0 h1:z7RynLwP5nbyRscyvcD043DWYoOcYRv3mV8lBeqOCLc= +github.com/samber/lo v1.47.0/go.mod h1:RmDH9Ct32Qy3gduHQuKJ3gW1fMHAnE/fAzQuf6He5cU= github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= @@ -249,6 +275,7 @@ github.com/stoewer/go-strcase v1.3.0/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8w github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= @@ -262,6 +289,7 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75 h1:6fotK7 github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75/go.mod h1:KO6IkyS8Y3j8OdNO85qEYBsRPuteD+YciPomcXdrMnk= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +github.com/xhit/go-str2duration/v2 v2.1.0/go.mod h1:ohY8p+0f07DiV6Em5LKB0s2YpLtXVyJfNt1+BlmyAsU= github.com/xiang90/probing v0.0.0-20221125231312-a49e3df8f510 h1:S2dVYn90KE98chqDkyE9Z4N61UnQd+KOfgp5Iu53llk= github.com/xiang90/probing v0.0.0-20221125231312-a49e3df8f510/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -305,6 +333,7 @@ go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQD go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8= go.opentelemetry.io/proto/otlp v1.3.1 h1:TrMUixzpM0yuc/znrFTP9MMRh8trP93mkCiDVeXrui0= go.opentelemetry.io/proto/otlp v1.3.1/go.mod h1:0X1WI4de4ZsLrrJNLAQbFeLCm3T7yBkR0XqQ7niQU+8= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU= @@ -328,6 +357,7 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191112182307-2180aed22343/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -365,6 +395,7 @@ golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/telemetry v0.0.0-20240521205824-bda55230c457/go.mod h1:pRgIJT+bRLFKnoM1ldnzKoxTIn14Yxz928LQRYYgIN0= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -418,6 +449,7 @@ gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= +gopkg.in/square/go-jose.v2 v2.6.0/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= @@ -439,6 +471,8 @@ k8s.io/component-helpers v0.32.0 h1:pQEEBmRt3pDJJX98cQvZshDgJFeKRM4YtYkMmfOlczw= k8s.io/component-helpers v0.32.0/go.mod h1:9RuClQatbClcokXOcDWSzFKQm1huIf0FzQlPRpizlMc= k8s.io/controller-manager v0.32.0 h1:tpQl1rvH4huFB6Avl1nhowZHtZoCNWqn6OYdZPl7Ybc= k8s.io/controller-manager v0.32.0/go.mod h1:JRuYnYCkKj3NgBTy+KNQKIUm/lJRoDAvGbfdEmk9LhY= +k8s.io/cri-api v0.32.0/go.mod h1:DCzMuTh2padoinefWME0G678Mc3QFbLMF2vEweGzBAI= +k8s.io/gengo/v2 v2.0.0-20240826214909-a7b603a56eb7/go.mod h1:EJykeLsmFC60UQbYJezXkEsG2FLrt0GPNkU5iK5GWxU= k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= k8s.io/kms v0.32.0 h1:jwOfunHIrcdYl5FRcA+uUKKtg6qiqoPCwmS2T3XTYL4= diff --git a/internal/testutil/fixture/azure_loadbalancer.go b/internal/testutil/fixture/azure_loadbalancer.go index 866b127609..55339d621c 100644 --- a/internal/testutil/fixture/azure_loadbalancer.go +++ b/internal/testutil/fixture/azure_loadbalancer.go @@ -17,16 +17,15 @@ limitations under the License. package fixture import ( - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "k8s.io/utils/ptr" ) func (f *AzureFixture) LoadBalancer() *AzureLoadBalancerFixture { return &AzureLoadBalancerFixture{ - lb: &network.LoadBalancer{ - Name: ptr.To("lb"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ + lb: &armnetwork.LoadBalancer{ + Name: ptr.To("lb"), + Properties: &armnetwork.LoadBalancerPropertiesFormat{ // TODO }, }, @@ -34,11 +33,11 @@ func (f *AzureFixture) LoadBalancer() *AzureLoadBalancerFixture { } type AzureLoadBalancerFixture struct { - lb *network.LoadBalancer + lb *armnetwork.LoadBalancer } -func (f *AzureLoadBalancerFixture) Build() network.LoadBalancer { - return *f.lb +func (f *AzureLoadBalancerFixture) Build() *armnetwork.LoadBalancer { + return f.lb } func (f *AzureLoadBalancerFixture) IPv4Addresses() []string { diff --git a/internal/testutil/fixture/azure_publicip.go b/internal/testutil/fixture/azure_publicip.go index a444dc1774..b174074a38 100644 --- a/internal/testutil/fixture/azure_publicip.go +++ b/internal/testutil/fixture/azure_publicip.go @@ -19,8 +19,7 @@ package fixture import ( "fmt" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "k8s.io/utils/ptr" ) @@ -31,20 +30,20 @@ func (f *AzureFixture) PublicIPAddress(name string) *AzurePublicIPAddressFixture ) return &AzurePublicIPAddressFixture{ - pip: &network.PublicIPAddress{ - ID: ptr.To(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/publicIPAddresses/%s", SubscriptionID, ResourceGroup, name)), - Name: ptr.To(name), - Tags: make(map[string]*string), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{}, + pip: &armnetwork.PublicIPAddress{ + ID: ptr.To(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/publicIPAddresses/%s", SubscriptionID, ResourceGroup, name)), + Name: ptr.To(name), + Tags: make(map[string]*string), + Properties: &armnetwork.PublicIPAddressPropertiesFormat{}, }, } } type AzurePublicIPAddressFixture struct { - pip *network.PublicIPAddress + pip *armnetwork.PublicIPAddress } -func (f *AzurePublicIPAddressFixture) Build() network.PublicIPAddress { +func (f *AzurePublicIPAddressFixture) Build() armnetwork.PublicIPAddress { return *f.pip } @@ -54,6 +53,6 @@ func (f *AzurePublicIPAddressFixture) WithTag(key, value string) *AzurePublicIPA } func (f *AzurePublicIPAddressFixture) WithAddress(address string) *AzurePublicIPAddressFixture { - f.pip.PublicIPAddressPropertiesFormat.IPAddress = ptr.To(address) + f.pip.Properties.IPAddress = ptr.To(address) return f } diff --git a/pkg/azureclients/armauth/multi_tenant_token_provider.go b/pkg/azureclients/armauth/multi_tenant_token_provider.go deleted file mode 100644 index 947b8ae262..0000000000 --- a/pkg/azureclients/armauth/multi_tenant_token_provider.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright 2024 The Kubernetes Authors. - -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. -*/ - -package armauth - -import ( - "context" - "time" - - "github.com/Azure/azure-sdk-for-go/sdk/azcore" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" - "github.com/go-logr/logr" -) - -// MultiTenantTokenProvider is the track1 multi-tenant token provider wrapper for track2 implementation. -type MultiTenantTokenProvider struct { - logger logr.Logger - primaryCredential azcore.TokenCredential - auxiliaryCredentials []azcore.TokenCredential - timeout time.Duration - scope string -} - -func NewMultiTenantTokenProvider( - logger logr.Logger, - primaryCredential azcore.TokenCredential, - auxiliaryCredentials []azcore.TokenCredential, - scope string, -) (*MultiTenantTokenProvider, error) { - return &MultiTenantTokenProvider{ - logger: logger, - primaryCredential: primaryCredential, - auxiliaryCredentials: auxiliaryCredentials, - timeout: 10 * time.Second, - scope: scope, - }, nil -} - -func (p *MultiTenantTokenProvider) PrimaryOAuthToken() string { - p.logger.V(4).Info("Fetching primary oauth token") - ctx, cancel := context.WithTimeout(context.Background(), p.timeout) - defer cancel() - - token, err := p.primaryCredential.GetToken(ctx, policy.TokenRequestOptions{ - Scopes: []string{p.scope}, - }) - if err != nil { - p.logger.Error(err, "Failed to fetch primary OAuth token") - return "" - } - return token.Token -} - -func (p *MultiTenantTokenProvider) AuxiliaryOAuthTokens() []string { - p.logger.V(4).Info("Fetching auxiliary oauth token", "num-credentials", len(p.auxiliaryCredentials)) - ctx, cancel := context.WithTimeout(context.Background(), p.timeout) - defer cancel() - - var tokens []string - for _, cred := range p.auxiliaryCredentials { - token, err := cred.GetToken(ctx, policy.TokenRequestOptions{ - Scopes: []string{p.scope}, - }) - if err != nil { - p.logger.Error(err, "Failed to fetch auxiliary OAuth token") - return nil - } - - tokens = append(tokens, token.Token) - } - - return tokens -} diff --git a/pkg/azureclients/armauth/token_provider.go b/pkg/azureclients/armauth/token_provider.go deleted file mode 100644 index d853a25eb8..0000000000 --- a/pkg/azureclients/armauth/token_provider.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2024 The Kubernetes Authors. - -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. -*/ - -package armauth - -import ( - "context" - "time" - - "github.com/Azure/azure-sdk-for-go/sdk/azcore" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" - "github.com/go-logr/logr" -) - -// TokenProvider is the track1 token provider wrapper for track2 implementation. -type TokenProvider struct { - logger logr.Logger - credential azcore.TokenCredential - timeout time.Duration - scope string -} - -func NewTokenProvider( - logger logr.Logger, - credential azcore.TokenCredential, - scope string, -) (*TokenProvider, error) { - return &TokenProvider{ - logger: logger, - credential: credential, - timeout: 10 * time.Second, - scope: scope, - }, nil -} - -func (p *TokenProvider) OAuthToken() string { - p.logger.V(4).Info("Fetching OAuth token") - ctx, cancel := context.WithTimeout(context.Background(), p.timeout) - defer cancel() - - token, err := p.credential.GetToken(ctx, policy.TokenRequestOptions{ - Scopes: []string{p.scope}, - }) - if err != nil { - p.logger.Error(err, "Failed to fetch OAuth token") - return "" - } - p.logger.V(4).Info("Fetched OAuth token successfully", "token", token.Token) - return token.Token -} diff --git a/pkg/azureclients/armclient/azure_armclient.go b/pkg/azureclients/armclient/azure_armclient.go deleted file mode 100644 index 2c6b5c4709..0000000000 --- a/pkg/azureclients/armclient/azure_armclient.go +++ /dev/null @@ -1,741 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package armclient - -import ( - "context" - "crypto/tls" - "fmt" - "html" - "net" - "net/http" - "net/http/cookiejar" - "net/url" - "strings" - "sync" - "time" - "unicode" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "k8s.io/klog/v2" - - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" - "sigs.k8s.io/cloud-provider-azure/pkg/version" -) - -// there is one sender per TLS renegotiation type, i.e. count of tls.RenegotiationSupport enums - -type defaultSender struct { - sender autorest.Sender - init *sync.Once -} - -// each type of sender will be created on demand in sender() -var defaultSenders defaultSender - -func init() { - defaultSenders.init = &sync.Once{} -} - -var _ Interface = &Client{} - -// Client implements ARM client Interface. -type Client struct { - client autorest.Client - baseURI string - apiVersion string - regionalEndpoint string -} - -func sender() autorest.Sender { - // note that we can't init defaultSenders in init() since it will - // execute before calling code has had a chance to enable tracing - defaultSenders.init.Do(func() { - // copied from http.DefaultTransport with a TLS minimum version. - transport := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, // the same as default transport - KeepAlive: 30 * time.Second, // the same as default transport - }).DialContext, - ForceAttemptHTTP2: false, // respect custom dialer (default is true) - MaxIdleConns: 100, // Zero means no limit, the same as default transport - MaxIdleConnsPerHost: 100, // Default is 2, ref:https://cs.opensource.google/go/go/+/go1.18.4:src/net/http/transport.go;l=58 - IdleConnTimeout: 90 * time.Second, // the same as default transport - TLSHandshakeTimeout: 10 * time.Second, // the same as default transport - ExpectContinueTimeout: 1 * time.Second, // the same as default transport - ResponseHeaderTimeout: 60 * time.Second, - TLSClientConfig: &tls.Config{ - MinVersion: tls.VersionTLS12, //force to use TLS 1.2 - Renegotiation: tls.RenegotiateNever, // the same as default transport https://pkg.go.dev/crypto/tls#RenegotiationSupport - }, - } - var roundTripper http.RoundTripper = transport - if tracing.IsEnabled() { - roundTripper = tracing.NewTransport(transport) - } - j, _ := cookiejar.New(nil) - defaultSenders.sender = &http.Client{Jar: j, Transport: roundTripper} - - // In go-autorest SDK https://github.com/Azure/go-autorest/blob/master/autorest/sender.go#L258-L287, - // if ARM returns http.StatusTooManyRequests, the sender doesn't increase the retry attempt count, - // hence the Azure clients will keep retrying forever until it get a status code other than 429. - // So we explicitly removes http.StatusTooManyRequests from autorest.StatusCodesForRetry. - // Refer https://github.com/Azure/go-autorest/issues/398. - // TODO(feiskyer): Use autorest.SendDecorator to customize the retry policy when new Azure SDK is available. - statusCodesForRetry := make([]int, 0) - for _, code := range autorest.StatusCodesForRetry { - if code != http.StatusTooManyRequests { - statusCodesForRetry = append(statusCodesForRetry, code) - } - } - autorest.StatusCodesForRetry = statusCodesForRetry - }) - return defaultSenders.sender -} - -// New creates a ARM client -func New(authorizer autorest.Authorizer, clientConfig azureclients.ClientConfig, baseURI, apiVersion string, sendDecoraters ...autorest.SendDecorator) *Client { - restClient := autorest.NewClientWithUserAgent(clientConfig.UserAgent) - restClient.Authorizer = authorizer - restClient.Sender = sender() - - if clientConfig.UserAgent == "" { - restClient.UserAgent = GetUserAgent(restClient) - } - - if clientConfig.RestClientConfig.PollingDelay == nil { - restClient.PollingDelay = 5 * time.Second - } else { - restClient.PollingDelay = *clientConfig.RestClientConfig.PollingDelay - } - - if clientConfig.RestClientConfig.RetryAttempts == nil { - restClient.RetryAttempts = 3 - } else { - restClient.RetryAttempts = *clientConfig.RestClientConfig.RetryAttempts - } - - if clientConfig.RestClientConfig.RetryDuration == nil { - restClient.RetryDuration = 1 * time.Second - } else { - restClient.RetryDuration = *clientConfig.RestClientConfig.RetryDuration - } - - backoff := clientConfig.Backoff - if backoff == nil { - backoff = &retry.Backoff{} - } - if backoff.Steps == 0 { - // 1 steps means no retry. - backoff.Steps = 1 - } - - url, _ := url.Parse(baseURI) - - client := &Client{ - client: restClient, - baseURI: baseURI, - apiVersion: apiVersion, - regionalEndpoint: fmt.Sprintf("%s.%s", clientConfig.Location, url.Host), - } - client.client.Sender = autorest.DecorateSender(client.client, - autorest.DoCloseIfError(), - retry.DoExponentialBackoffRetry(backoff), - DoDumpRequest(10), - ) - - client.client.Sender = autorest.DecorateSender(client.client.Sender, sendDecoraters...) - - return client -} - -// GetUserAgent gets the autorest client with a user agent that -// includes "kubernetes" and the full kubernetes git version string -// example: -// Azure-SDK-for-Go/7.0.1 arm-network/2016-09-01; kubernetes-cloudprovider/v1.17.0; -func GetUserAgent(client autorest.Client) string { - k8sVersion := version.Get().GitVersion - return fmt.Sprintf("%s; kubernetes-cloudprovider/%s", client.UserAgent, k8sVersion) -} - -// NormalizeAzureRegion returns a normalized Azure region with white spaces removed and converted to lower case -func NormalizeAzureRegion(name string) string { - region := "" - for _, runeValue := range name { - if !unicode.IsSpace(runeValue) { - region += string(runeValue) - } - } - return strings.ToLower(region) -} - -// Send sends a http request to ARM service with possible retry to regional ARM endpoint. -func (c *Client) Send(_ context.Context, request *http.Request, decorators ...autorest.SendDecorator) (*http.Response, *retry.Error) { - response, err := autorest.SendWithSender( - c.client, - request, - decorators..., - ) - - if response == nil && err == nil { - return response, retry.NewError(false, fmt.Errorf("Empty response and no HTTP code")) - } - - return response, retry.GetError(response, err) -} - -// PreparePutRequest prepares put request -func (c *Client) PreparePutRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) { - decorators = append( - []autorest.PrepareDecorator{ - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(c.baseURI)}, - decorators...) - return c.prepareRequest(ctx, decorators...) -} - -// PreparePatchRequest prepares patch request -func (c *Client) PreparePatchRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) { - decorators = append( - []autorest.PrepareDecorator{ - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(c.baseURI)}, - decorators...) - return c.prepareRequest(ctx, decorators...) -} - -// PreparePostRequest prepares post request -func (c *Client) PreparePostRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) { - decorators = append( - []autorest.PrepareDecorator{ - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(c.baseURI)}, - decorators...) - return c.prepareRequest(ctx, decorators...) -} - -// PrepareGetRequest prepares get request -func (c *Client) PrepareGetRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) { - decorators = append( - []autorest.PrepareDecorator{ - autorest.AsGet(), - autorest.WithBaseURL(c.baseURI)}, - decorators...) - return c.prepareRequest(ctx, decorators...) -} - -// PrepareDeleteRequest preparse delete request -func (c *Client) PrepareDeleteRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) { - decorators = append( - []autorest.PrepareDecorator{ - autorest.AsDelete(), - autorest.WithBaseURL(c.baseURI)}, - decorators...) - return c.prepareRequest(ctx, decorators...) -} - -// PrepareHeadRequest prepares head request -func (c *Client) PrepareHeadRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) { - decorators = append( - []autorest.PrepareDecorator{ - autorest.AsHead(), - autorest.WithBaseURL(c.baseURI)}, - decorators...) - return c.prepareRequest(ctx, decorators...) -} - -// WaitForAsyncOperationCompletion waits for an operation completion -func (c *Client) WaitForAsyncOperationCompletion(ctx context.Context, future *azure.Future, asyncOperationName string) error { - err := future.WaitForCompletionRef(ctx, c.client) - if err != nil { - klog.V(5).Infof("Received error in WaitForCompletionRef: '%v'", err) - return err - } - - var done bool - done, err = future.DoneWithContext(ctx, c.client) - if err != nil { - klog.V(5).Infof("Received error in DoneWithContext: '%v'", err) - return autorest.NewErrorWithError(err, asyncOperationName, "Result", future.Response(), "Polling failure") - } - if !done { - return azure.NewAsyncOpIncompleteError(asyncOperationName) - } - - return nil -} - -// WaitForAsyncOperationResult waits for an operation result. -func (c *Client) WaitForAsyncOperationResult(ctx context.Context, future *azure.Future, _ string) (*http.Response, error) { - if err := future.WaitForCompletionRef(ctx, c.client); err != nil { - klog.V(5).Infof("Received error in WaitForAsyncOperationCompletion: '%v'", err) - return nil, err - } - return future.GetResult(c.client) -} - -// SendAsync send a request and return a future object representing the async result as well as the origin http response -func (c *Client) SendAsync(ctx context.Context, request *http.Request) (*azure.Future, *http.Response, *retry.Error) { - asyncResponse, rerr := c.Send(ctx, request) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "sendAsync.send", html.EscapeString(request.URL.String()), rerr.Error()) - return nil, nil, rerr - } - - future, err := azure.NewFutureFromResponse(asyncResponse) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "sendAsync.respond", html.EscapeString(request.URL.String()), err) - return nil, asyncResponse, retry.GetError(asyncResponse, err) - } - - return &future, asyncResponse, nil -} - -// GetResourceWithExpandQuery get a resource by resource ID with expand -func (c *Client) GetResourceWithExpandQuery(ctx context.Context, resourceID, expand string) (*http.Response, *retry.Error) { - var decorators []autorest.PrepareDecorator - if expand != "" { - queryParameters := map[string]interface{}{ - "$expand": autorest.Encode("query", expand), - } - decorators = append(decorators, autorest.WithQueryParameters(queryParameters)) - } - return c.GetResource(ctx, resourceID, decorators...) -} - -// GetResourceWithExpandAPIVersionQuery get a resource by resource ID with expand and API version. -func (c *Client) GetResourceWithExpandAPIVersionQuery(ctx context.Context, resourceID, expand, apiVersion string) (*http.Response, *retry.Error) { - decorators := []autorest.PrepareDecorator{ - withAPIVersion(apiVersion), - } - if expand != "" { - decorators = append(decorators, autorest.WithQueryParameters(map[string]interface{}{ - "$expand": autorest.Encode("query", expand), - })) - } - - return c.GetResource(ctx, resourceID, decorators...) -} - -// GetResourceWithQueries get a resource by resource ID with queries. -func (c *Client) GetResourceWithQueries(ctx context.Context, resourceID string, queries map[string]interface{}) (*http.Response, *retry.Error) { - - queryParameters := make(map[string]interface{}) - for queryKey, queryValue := range queries { - queryParameters[queryKey] = autorest.Encode("query", queryValue) - } - - decorators := []autorest.PrepareDecorator{ - autorest.WithQueryParameters(queryParameters), - } - - return c.GetResource(ctx, resourceID, decorators...) -} - -// GetResourceWithDecorators get a resource with decorators by resource ID -func (c *Client) GetResource(ctx context.Context, resourceID string, decorators ...autorest.PrepareDecorator) (*http.Response, *retry.Error) { - getDecorators := append([]autorest.PrepareDecorator{ - autorest.WithPathParameters("{resourceID}", map[string]interface{}{"resourceID": resourceID}), - }, decorators...) - request, err := c.PrepareGetRequest(ctx, getDecorators...) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "get.prepare", resourceID, err) - return nil, retry.NewError(false, err) - } - - return c.Send(ctx, request, DoHackRegionalRetryForGET(c)) -} - -// PutResource puts a resource by resource ID -func (c *Client) PutResource(ctx context.Context, resourceID string, parameters interface{}, decorators ...autorest.PrepareDecorator) (*http.Response, *retry.Error) { - future, rerr := c.PutResourceAsync(ctx, resourceID, parameters, decorators...) - if rerr != nil { - return nil, rerr - } - - response, err := c.WaitForAsyncOperationResult(ctx, future, "armclient.PutResource") - if err != nil { - if response != nil { - klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', response code %d", err.Error(), response.StatusCode) - } else { - klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', no response", err.Error()) - } - - retriableErr := retry.GetError(response, err) - if !retriableErr.Retriable && - strings.Contains(strings.ToUpper(err.Error()), strings.ToUpper("InternalServerError")) { - klog.V(5).Infof("Received InternalServerError in WaitForAsyncOperationResult: '%s', setting error retriable", err.Error()) - retriableErr.Retriable = true - } - return nil, retriableErr - } - - return response, nil -} - -func (c *Client) waitAsync(ctx context.Context, futures map[string]*azure.Future, previousResponses map[string]*PutResourcesResponse) { - wg := sync.WaitGroup{} - var responseLock sync.Mutex - for resourceID, future := range futures { - wg.Add(1) - go func(resourceID string, future *azure.Future) { - defer wg.Done() - response, err := c.WaitForAsyncOperationResult(ctx, future, "armclient.PutResource") - if err != nil { - if response != nil { - klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', response code %d", err.Error(), response.StatusCode) - } else { - klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', no response", err.Error()) - } - - retriableErr := retry.GetError(response, err) - if !retriableErr.Retriable && - strings.Contains(strings.ToUpper(err.Error()), strings.ToUpper("InternalServerError")) { - klog.V(5).Infof("Received InternalServerError in WaitForAsyncOperationResult: '%s', setting error retriable", err.Error()) - retriableErr.Retriable = true - } - - responseLock.Lock() - previousResponses[resourceID] = &PutResourcesResponse{ - Error: retriableErr, - } - responseLock.Unlock() - return - } - }(resourceID, future) - } - wg.Wait() -} - -// PutResourcesInBatches is similar with PutResources, but it sends sync request concurrently in batches. -func (c *Client) PutResourcesInBatches(ctx context.Context, resources map[string]interface{}, batchSize int) map[string]*PutResourcesResponse { - if len(resources) == 0 { - return nil - } - - if batchSize <= 0 { - klog.V(4).Infof("PutResourcesInBatches: batch size %d, put resources in sequence", batchSize) - batchSize = 1 - } - - if batchSize > len(resources) { - klog.V(4).Infof("PutResourcesInBatches: batch size %d, but the number of the resources is %d", batchSize, len(resources)) - batchSize = len(resources) - } - klog.V(4).Infof("PutResourcesInBatches: send sync requests in parallel with the batch size %d", batchSize) - - rateLimiter := make(chan struct{}, batchSize) - - // Concurrent sync requests in batches. - futures := make(map[string]*azure.Future) - responses := make(map[string]*PutResourcesResponse) - wg := sync.WaitGroup{} - var responseLock, futuresLock sync.Mutex - for resourceID, parameters := range resources { - rateLimiter <- struct{}{} - wg.Add(1) - go func(resourceID string, parameters interface{}) { - defer wg.Done() - defer func() { <-rateLimiter }() - future, rerr := c.PutResourceAsync(ctx, resourceID, parameters) - if rerr != nil { - responseLock.Lock() - responses[resourceID] = &PutResourcesResponse{ - Error: rerr, - } - responseLock.Unlock() - return - } - - futuresLock.Lock() - futures[resourceID] = future - futuresLock.Unlock() - }(resourceID, parameters) - } - wg.Wait() - close(rateLimiter) - - // Concurrent async requests. - c.waitAsync(ctx, futures, responses) - - return responses -} - -// PatchResource patches a resource by resource ID -func (c *Client) PatchResource(ctx context.Context, resourceID string, parameters interface{}, decorators ...autorest.PrepareDecorator) (*http.Response, *retry.Error) { - future, rerr := c.PatchResourceAsync(ctx, resourceID, parameters, decorators...) - if rerr != nil { - return nil, rerr - } - response, err := c.WaitForAsyncOperationResult(ctx, future, "armclient.PatchResource") - if err != nil { - if response != nil { - klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', response code %d", err.Error(), response.StatusCode) - } else { - klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', no response", err.Error()) - } - - retriableErr := retry.GetError(response, err) - if !retriableErr.Retriable && - strings.Contains(strings.ToUpper(err.Error()), strings.ToUpper("InternalServerError")) { - klog.V(5).Infof("Received InternalServerError in WaitForAsyncOperationResult: '%s', setting error retriable", err.Error()) - retriableErr.Retriable = true - } - return nil, retriableErr - } - - return response, nil -} - -// PatchResourceAsync patches a resource by resource ID asynchronously -func (c *Client) PatchResourceAsync(ctx context.Context, resourceID string, parameters interface{}, decorators ...autorest.PrepareDecorator) (*azure.Future, *retry.Error) { - decorators = append(decorators, - autorest.WithPathParameters("{resourceID}", map[string]interface{}{"resourceID": resourceID}), - autorest.WithJSON(parameters), - ) - - request, err := c.PreparePatchRequest(ctx, decorators...) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "patch.prepare", resourceID, err) - return nil, retry.NewError(false, err) - } - - future, resp, clientErr := c.SendAsync(ctx, request) - defer c.CloseResponse(ctx, resp) - if clientErr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "patch.send", resourceID, clientErr.Error()) - return nil, clientErr - } - return future, clientErr -} - -// PutResourceAsync puts a resource by resource ID in async mode -func (c *Client) PutResourceAsync(ctx context.Context, resourceID string, parameters interface{}, decorators ...autorest.PrepareDecorator) (*azure.Future, *retry.Error) { - decorators = append(decorators, - autorest.WithPathParameters("{resourceID}", map[string]interface{}{"resourceID": resourceID}), - autorest.WithJSON(parameters), - ) - - request, err := c.PreparePutRequest(ctx, decorators...) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "put.prepare", resourceID, err) - return nil, retry.NewError(false, err) - } - - future, resp, rErr := c.SendAsync(ctx, request) - defer c.CloseResponse(ctx, resp) - if rErr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "put.send", resourceID, rErr.Error()) - return nil, rErr - } - - return future, nil -} - -// PostResource posts a resource by resource ID -func (c *Client) PostResource(ctx context.Context, resourceID, action string, parameters interface{}, queryParameters map[string]interface{}) (*http.Response, *retry.Error) { - pathParameters := map[string]interface{}{ - "resourceID": resourceID, - "action": action, - } - - decorators := []autorest.PrepareDecorator{ - autorest.WithPathParameters("{resourceID}/{action}", pathParameters), - autorest.WithJSON(parameters), - } - if len(queryParameters) > 0 { - decorators = append(decorators, autorest.WithQueryParameters(queryParameters)) - } - - request, err := c.PreparePostRequest(ctx, decorators...) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "post.prepare", resourceID, err) - return nil, retry.NewError(false, err) - } - - return c.Send(ctx, request) -} - -// DeleteResource deletes a resource by resource ID -func (c *Client) DeleteResource(ctx context.Context, resourceID string, _ ...autorest.PrepareDecorator) *retry.Error { - future, clientErr := c.DeleteResourceAsync(ctx, resourceID) - if clientErr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "delete.request", resourceID, clientErr.Error()) - return clientErr - } - - if future == nil { - return nil - } - if err := future.WaitForCompletionRef(ctx, c.client); err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "delete.wait", resourceID, err) - return retry.NewError(true, err) - } - - return nil -} - -// HeadResource heads a resource by resource ID -func (c *Client) HeadResource(ctx context.Context, resourceID string) (*http.Response, *retry.Error) { - decorators := []autorest.PrepareDecorator{ - autorest.WithPathParameters("{resourceID}", map[string]interface{}{"resourceID": resourceID}), - } - request, err := c.PrepareHeadRequest(ctx, decorators...) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "head.prepare", resourceID, err) - return nil, retry.NewError(false, err) - } - - return c.Send(ctx, request) -} - -// DeleteResourceAsync delete a resource by resource ID and returns a future representing the async result -func (c *Client) DeleteResourceAsync(ctx context.Context, resourceID string, decorators ...autorest.PrepareDecorator) (*azure.Future, *retry.Error) { - decorators = append(decorators, - autorest.WithPathParameters("{resourceID}", map[string]interface{}{"resourceID": resourceID}), - ) - - deleteRequest, err := c.PrepareDeleteRequest(ctx, decorators...) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "deleteAsync.prepare", resourceID, err) - return nil, retry.NewError(false, err) - } - - resp, rerr := c.Send(ctx, deleteRequest) - defer c.CloseResponse(ctx, resp) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "deleteAsync.send", resourceID, rerr.Error()) - return nil, rerr - } - - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent, http.StatusNotFound)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "deleteAsync.respond", resourceID, err) - return nil, retry.GetError(resp, err) - } - - if resp.StatusCode == http.StatusNotFound { - return nil, nil - } - - future, err := azure.NewFutureFromResponse(resp) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "deleteAsync.future", resourceID, err) - return nil, retry.GetError(resp, err) - } - - return &future, nil -} - -// CloseResponse closes a response -func (c *Client) CloseResponse(_ context.Context, response *http.Response) { - if response != nil && response.Body != nil { - if err := response.Body.Close(); err != nil { - klog.Errorf("Error closing the response body: %v", err) - } - } -} - -func (c *Client) prepareRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) { - decorators = append( - decorators, - withAPIVersion(c.apiVersion)) - preparer := autorest.CreatePreparer(decorators...) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -func withAPIVersion(apiVersion string) autorest.PrepareDecorator { - const apiVersionKey = "api-version" - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, fmt.Errorf("Error in withAPIVersion: Invoked with a nil URL") - } - - v := r.URL.Query() - if len(v.Get(apiVersionKey)) > 0 { - return r, nil - } - - v.Add(apiVersionKey, apiVersion) - r.URL.RawQuery = v.Encode() - } - return r, err - }) - } -} - -// GetResourceID gets Azure resource ID -func GetResourceID(subscriptionID, resourceGroupName, resourceType, resourceName string) string { - return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/%s/%s", - autorest.Encode("path", subscriptionID), - autorest.Encode("path", resourceGroupName), - resourceType, - autorest.Encode("path", resourceName)) -} - -// GetResourceListID gets Azure resource list ID -func GetResourceListID(subscriptionID, resourceGroupName, resourceType string) string { - return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/%s", - autorest.Encode("path", subscriptionID), - autorest.Encode("path", resourceGroupName), - resourceType) -} - -// GetChildResourceID gets Azure child resource ID -func GetChildResourceID(subscriptionID, resourceGroupName, resourceType, resourceName, childResourceType, childResourceName string) string { - return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/%s/%s/%s/%s", - autorest.Encode("path", subscriptionID), - autorest.Encode("path", resourceGroupName), - resourceType, - autorest.Encode("path", resourceName), - childResourceType, - autorest.Encode("path", childResourceName)) -} - -// GetChildResourcesListID gets Azure child resources list ID -func GetChildResourcesListID(subscriptionID, resourceGroupName, resourceType, resourceName, childResourceType string) string { - return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/%s/%s/%s", - autorest.Encode("path", subscriptionID), - autorest.Encode("path", resourceGroupName), - resourceType, - autorest.Encode("path", resourceName), - childResourceType) -} - -// GetProviderResourceID gets Azure RP resource ID -func GetProviderResourceID(subscriptionID, providerNamespace string) string { - return fmt.Sprintf("/subscriptions/%s/providers/%s", - autorest.Encode("path", subscriptionID), - providerNamespace) -} - -// GetProviderResourcesListID gets Azure RP resources list ID -func GetProviderResourcesListID(subscriptionID string) string { - return fmt.Sprintf("/subscriptions/%s/providers", autorest.Encode("path", subscriptionID)) -} diff --git a/pkg/azureclients/armclient/azure_armclient_test.go b/pkg/azureclients/armclient/azure_armclient_test.go deleted file mode 100644 index b7a4074706..0000000000 --- a/pkg/azureclients/armclient/azure_armclient_test.go +++ /dev/null @@ -1,752 +0,0 @@ -/* -Copyright 2019 The Kubernetes Authors. - -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. -*/ - -package armclient - -import ( - "context" - "fmt" - "io" - "net/http" - "net/http/httptest" - "net/url" - "sync" - "testing" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/stretchr/testify/assert" - - "k8s.io/utils/ptr" - - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - testResourceID = "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP" - operationURI = "/subscriptions/subscription/providers/Microsoft.Network/locations/eastus/operations/op?api-version=2019-01-01" - expectedURI = "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP?api-version=2019-01-01" -) - -func TestSend(t *testing.T) { - count := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - if count <= 1 { - http.Error(w, "failed", http.StatusInternalServerError) - count++ - } - })) - - azConfig := azureclients.ClientConfig{Backoff: &retry.Backoff{Steps: 3}, UserAgent: "test", Location: "eastus"} - armClient := New(nil, azConfig, server.URL, "2019-01-01") - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", "testgroup"), - "subscriptionId": autorest.Encode("path", "testid"), - "resourceName": autorest.Encode("path", "testname"), - } - - decorators := []autorest.PrepareDecorator{ - autorest.WithPathParameters( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vNets/{resourceName}", pathParameters), - } - - ctx := context.Background() - request, err := armClient.PrepareGetRequest(ctx, decorators...) - assert.NoError(t, err) - - response, rerr := armClient.Send(ctx, request) - assert.Nil(t, rerr) - assert.Equal(t, 2, count) - assert.Equal(t, http.StatusOK, response.StatusCode) -} -func TestDoHackRegionalRetryForGET(t *testing.T) { - testcases := []struct { - description string - globalServerErrMsg string - globalServerCode int - globalServerContentLength *string - }{ - { - "RegionalRetry", - "{\"error\":{\"code\":\"ResourceGroupNotFound\"}}", - http.StatusInternalServerError, - ptr.To("100"), - }, - { - "ReplicationLatency-Content-Length-0", - "{}", - http.StatusOK, - ptr.To("0"), - }, - { - "ReplicationLatency-Content-Length-minus-1", - "{}", - http.StatusOK, - ptr.To("-1"), - }, - } - - for _, tc := range testcases { - t.Run(tc.description, func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method) - w.WriteHeader(http.StatusOK) - _, err := w.Write([]byte("{\"a\": \"b\"}")) - assert.NoError(t, err) - })) - - globalServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - if tc.globalServerContentLength != nil { - w.Header().Set("Content-Length", *tc.globalServerContentLength) - } - http.Error(w, tc.globalServerErrMsg, tc.globalServerCode) - })) - azConfig := azureclients.ClientConfig{Backoff: &retry.Backoff{Steps: 3}, UserAgent: "test", Location: "eastus"} - armClient := New(nil, azConfig, server.URL, "2019-01-01") - targetURL, _ := url.Parse(server.URL) - armClient.regionalEndpoint = targetURL.Host - armClient.baseURI = globalServer.URL - - resourceID := "/subscriptions/testid/resourceGroups/restgroup/providers/Microsoft.Network/vNets/testname" - ctx := context.Background() - response, rerr := armClient.GetResource(ctx, resourceID) - assert.Nil(t, rerr) - assert.NotNil(t, response) - assert.Equal(t, http.StatusOK, response.StatusCode) - assert.Equal(t, targetURL.Host, response.Request.URL.Host) - }) - } -} - -func TestSendFailure(t *testing.T) { - count := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - http.Error(w, "failed", http.StatusInternalServerError) - count++ - })) - - azConfig := azureclients.ClientConfig{Backoff: &retry.Backoff{Steps: 3}, UserAgent: "test", Location: "eastus"} - armClient := New(nil, azConfig, server.URL, "2019-01-01") - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", "testgroup"), - "subscriptionId": autorest.Encode("path", "testid"), - "resourceName": autorest.Encode("path", "testname"), - } - - decorators := []autorest.PrepareDecorator{ - autorest.WithPathParameters( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vNets/{resourceName}", pathParameters), - } - - ctx := context.Background() - request, err := armClient.PreparePatchRequest(ctx, decorators...) - assert.NoError(t, err) - - response, rerr := armClient.Send(ctx, request) - assert.NotNil(t, rerr) - assert.Equal(t, 3, count) - assert.Equal(t, http.StatusInternalServerError, response.StatusCode) -} - -func TestSendThrottled(t *testing.T) { - count := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set(consts.RetryAfterHeaderKey, "30") - http.Error(w, "failed", http.StatusTooManyRequests) - count++ - })) - - azConfig := azureclients.ClientConfig{Backoff: &retry.Backoff{Steps: 3}, UserAgent: "test", Location: "eastus"} - armClient := New(nil, azConfig, server.URL, "2019-01-01") - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", "testgroup"), - "subscriptionId": autorest.Encode("path", "testid"), - "resourceName": autorest.Encode("path", "testname"), - } - decorators := []autorest.PrepareDecorator{ - autorest.WithPathParameters( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vNets/{resourceName}", pathParameters), - } - - ctx := context.Background() - request, err := armClient.PrepareGetRequest(ctx, decorators...) - assert.NoError(t, err) - - response, rerr := armClient.Send(ctx, request) - assert.NotNil(t, rerr) - assert.Equal(t, 1, count) - assert.Equal(t, http.StatusTooManyRequests, response.StatusCode) -} - -func TestSendAsync(t *testing.T) { - count := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - count++ - http.Error(w, "failed", http.StatusForbidden) - })) - - azConfig := azureclients.ClientConfig{Backoff: &retry.Backoff{Steps: 1}, UserAgent: "test", Location: "eastus"} - armClient := New(nil, azConfig, server.URL, "2019-01-01") - armClient.client.RetryDuration = time.Millisecond * 1 - - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", "testgroup"), - "subscriptionId": autorest.Encode("path", "testid"), - "resourceName": autorest.Encode("path", "testname"), - } - decorators := []autorest.PrepareDecorator{ - autorest.WithPathParameters( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vNets/{resourceName}", pathParameters), - } - - ctx := context.Background() - request, err := armClient.PreparePutRequest(ctx, decorators...) - assert.NoError(t, err) - - future, response, rerr := armClient.SendAsync(ctx, request) - assert.Nil(t, future) - assert.Nil(t, response) - assert.Equal(t, 1, count) - assert.NotNil(t, rerr) - assert.Equal(t, false, rerr.Retriable) -} - -func TestSendAsyncSuccess(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - })) - - azConfig := azureclients.ClientConfig{Backoff: &retry.Backoff{Steps: 1}, UserAgent: "test", Location: "eastus"} - armClient := New(nil, azConfig, server.URL, "2019-01-01") - armClient.client.RetryDuration = time.Millisecond * 1 - - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", "testgroup"), - "subscriptionId": autorest.Encode("path", "testid"), - "resourceName": autorest.Encode("path", "testname"), - } - decorators := []autorest.PrepareDecorator{ - autorest.WithPathParameters( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vNets/{resourceName}", pathParameters), - } - - ctx := context.Background() - request, err := armClient.PreparePostRequest(ctx, decorators...) - assert.NoError(t, err) - - future, response, rerr := armClient.SendAsync(ctx, request) - assert.Nil(t, rerr) - assert.NotNil(t, response) - assert.NotNil(t, future) -} - -func TestNormalizeAzureRegion(t *testing.T) { - tests := []struct { - region string - expected string - }{ - { - region: "eastus", - expected: "eastus", - }, - { - region: " eastus ", - expected: "eastus", - }, - { - region: " eastus\t", - expected: "eastus", - }, - { - region: " eastus\v", - expected: "eastus", - }, - { - region: " eastus\v\r\f\n", - expected: "eastus", - }, - } - - for i, test := range tests { - realValue := NormalizeAzureRegion(test.region) - assert.Equal(t, test.expected, realValue, "test[%d]: NormalizeAzureRegion(%q) != %q", i, test.region, test.expected) - } -} - -func TestGetResource(t *testing.T) { - testcases := []struct { - description string - expectedURIResource string - apiVersion string - expectedAPIVersion string - params map[string]interface{} - getResource func(ctx context.Context, armClient *Client, apiVersion string, params map[string]interface{}) (*http.Response, *retry.Error) - }{ - { - description: "TestGetResource", - expectedURIResource: "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP?api-version=2019-01-01¶m1=value1¶m2=value2", - apiVersion: "2019-01-01", - expectedAPIVersion: "2019-01-01", - params: map[string]interface{}{ - "param1": "value1", - "param2": "value2", - }, - getResource: func(ctx context.Context, armClient *Client, _ string, params map[string]interface{}) (*http.Response, *retry.Error) { - decorators := []autorest.PrepareDecorator{ - autorest.WithQueryParameters(params), - } - return armClient.GetResource(ctx, testResourceID, decorators...) - }, - }, - { - description: "GetResourceWithExpandQuery", - expectedURIResource: "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP?%24expand=data&api-version=2019-01-01", - apiVersion: "2019-01-01", - expectedAPIVersion: "2019-01-01", - getResource: func(ctx context.Context, armClient *Client, _ string, _ map[string]interface{}) (*http.Response, *retry.Error) { - return armClient.GetResourceWithExpandQuery(ctx, testResourceID, "data") - }, - }, - { - description: "GetResourceWithExpandAPIVersionQuery", - expectedURIResource: "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP?%24expand=data&api-version=2019-01-01", - apiVersion: "2018-01-01", - expectedAPIVersion: "2019-01-01", - getResource: func(ctx context.Context, armClient *Client, apiVersion string, _ map[string]interface{}) (*http.Response, *retry.Error) { - return armClient.GetResourceWithExpandAPIVersionQuery(ctx, testResourceID, "data", apiVersion) - }, - }, - { - description: "GetResourceWithExpandAPIVersionQuery-empty-expand", - expectedURIResource: "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP?api-version=2019-01-01", - apiVersion: "2018-01-01", - expectedAPIVersion: "2019-01-01", - getResource: func(ctx context.Context, armClient *Client, apiVersion string, _ map[string]interface{}) (*http.Response, *retry.Error) { - return armClient.GetResourceWithExpandAPIVersionQuery(ctx, testResourceID, "", apiVersion) - }, - }, - { - description: "GetResourceWithQueries", - expectedURIResource: "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP?api-version=2019-01-01¶m1=value1¶m2=value2", - apiVersion: "2019-01-01", - expectedAPIVersion: "2019-01-01", - params: map[string]interface{}{ - "param1": "value1", - "param2": "value2", - }, - getResource: func(ctx context.Context, armClient *Client, _ string, params map[string]interface{}) (*http.Response, *retry.Error) { - return armClient.GetResourceWithQueries(ctx, testResourceID, params) - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.description, func(t *testing.T) { - count := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method) - assert.Equal(t, tc.expectedURIResource, r.URL.String()) - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte("{data: testPIP}")) - count++ - })) - - azConfig := azureclients.ClientConfig{Backoff: &retry.Backoff{Steps: 1}, UserAgent: "test", Location: "eastus"} - armClient := New(nil, azConfig, server.URL, tc.apiVersion) - armClient.client.RetryDuration = time.Millisecond * 1 - - ctx := context.Background() - response, rerr := tc.getResource(ctx, armClient, tc.expectedAPIVersion, tc.params) - assert.Nil(t, rerr) - assert.NotNil(t, response) - byteResponseBody, _ := io.ReadAll(response.Body) - stringResponseBody := string(byteResponseBody) - assert.Equal(t, "{data: testPIP}", stringResponseBody) - assert.Equal(t, 1, count) - }) - } -} - -func TestPutResource(t *testing.T) { - handlers := []func(http.ResponseWriter, *http.Request){ - func(rw http.ResponseWriter, req *http.Request) { - assert.Equal(t, "PUT", req.Method) - assert.Equal(t, expectedURI, req.URL.String()) - rw.Header().Set("Azure-AsyncOperation", - fmt.Sprintf("http://%s%s", req.Host, operationURI)) - rw.WriteHeader(http.StatusCreated) - }, - - func(rw http.ResponseWriter, req *http.Request) { - assert.Equal(t, "GET", req.Method) - assert.Equal(t, operationURI, req.URL.String()) - - rw.WriteHeader(http.StatusOK) - _, _ = rw.Write([]byte(`{"error":{"code":"InternalServerError"},"status":"Failed"}`)) - }, - } - - count := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - handlers[count](w, r) - count++ - if count > 1 { - count = 1 - } - })) - - azConfig := azureclients.ClientConfig{Backoff: &retry.Backoff{Steps: 1}, UserAgent: "test", Location: "eastus"} - armClient := New(nil, azConfig, server.URL, "2019-01-01") - armClient.client.RetryDuration = time.Millisecond * 1 - - ctx := context.Background() - response, rerr := armClient.PutResource(ctx, testResourceID, nil) - assert.Equal(t, 1, count) - assert.Nil(t, response) - assert.NotNil(t, rerr) - assert.Equal(t, true, rerr.Retriable) -} - -func getTestServer(t *testing.T, counter *int) *httptest.Server { - serverFuncs := []func(rw http.ResponseWriter, req *http.Request){ - func(rw http.ResponseWriter, req *http.Request) { - assert.Equal(t, "PUT", req.Method) - - rw.Header().Set("Azure-AsyncOperation", - fmt.Sprintf("http://%s%s", req.Host, "/id/1?api-version=2019-01-01")) - rw.WriteHeader(http.StatusCreated) - }, - func(rw http.ResponseWriter, req *http.Request) { - assert.Equal(t, "PUT", req.Method) - - rw.Header().Set("Azure-AsyncOperation", - fmt.Sprintf("http://%s%s", req.Host, "/id/2?api-version=2019-01-01")) - rw.WriteHeader(http.StatusInternalServerError) - }, - func(rw http.ResponseWriter, req *http.Request) { - assert.Equal(t, "GET", req.Method) - - rw.WriteHeader(http.StatusOK) - _, _ = rw.Write([]byte(`{"error":{"code":"InternalServerError"},"status":"Failed"}`)) - }, - func(rw http.ResponseWriter, req *http.Request) { - assert.Equal(t, "GET", req.Method) - - rw.WriteHeader(http.StatusOK) - _, _ = rw.Write([]byte(`{"error":{"code":"InternalServerError"},"status":"Failed"}`)) - }, - } - - i := 0 - var l sync.Mutex - return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - l.Lock() - serverFuncs[i](w, r) - i++ - if i > 3 { - i = 3 - } - *counter++ - l.Unlock() - })) -} - -func TestPutResourcesInBatches(t *testing.T) { - for _, testCase := range []struct { - description string - resources map[string]interface{} - batchSize, expectedCallTimes int - }{ - { - description: "", - resources: map[string]interface{}{ - "/id/1": nil, - "/id/2": nil, - }, - batchSize: 2, - expectedCallTimes: 3, - }, - { - description: "", - resources: map[string]interface{}{ - "/id/1": nil, - "/id/2": nil, - }, - batchSize: 1, - expectedCallTimes: 3, - }, - { - description: "", - resources: nil, - }, - { - description: "PutResourcesInBatches should set the batch size to the length of the resources if the batch size is larger than it", - resources: map[string]interface{}{ - "/id/1": nil, - "/id/2": nil, - }, - batchSize: 10, - expectedCallTimes: 3, - }, - { - description: "PutResourcesInBatches should call PutResources if the batch size is smaller than or equal to zero", - resources: map[string]interface{}{ - "/id/1": nil, - "/id/2": nil, - }, - expectedCallTimes: 3, - }, - } { - t.Run(testCase.description, func(t *testing.T) { - total := 0 - server := getTestServer(t, &total) - - azConfig := azureclients.ClientConfig{Backoff: &retry.Backoff{Steps: 1}, UserAgent: "test", Location: "eastus"} - armClient := New(nil, azConfig, server.URL, "2019-01-01") - armClient.client.RetryDuration = time.Millisecond * 1 - - ctx := context.Background() - responses := armClient.PutResourcesInBatches(ctx, testCase.resources, testCase.batchSize) - assert.Equal(t, testCase.resources == nil, responses == nil) - assert.Equal(t, testCase.expectedCallTimes, total) - }) - } -} - -func TestResourceAction(t *testing.T) { - for _, tc := range []struct { - description string - action func(armClient *Client, ctx context.Context, resourceID string, parameters interface{}) (*azure.Future, *http.Response, *retry.Error) - assertion func(count int, future *azure.Future, response *http.Response, rerr *retry.Error) - }{ - { - description: "put resource async", - action: func(armClient *Client, ctx context.Context, resourceID string, _ interface{}) (*azure.Future, *http.Response, *retry.Error) { - future, rerr := armClient.PutResourceAsync(ctx, resourceID, "") - return future, nil, rerr - }, - assertion: func(count int, future *azure.Future, _ *http.Response, rerr *retry.Error) { - assert.Equal(t, 3, count, "count") - assert.Nil(t, future, "future") - assert.NotNil(t, rerr, "rerr") - assert.Equal(t, true, rerr.Retriable, "rerr.Retriable") - }, - }, - { - description: "delete resource async", - action: func(armClient *Client, ctx context.Context, resourceID string, _ interface{}) (*azure.Future, *http.Response, *retry.Error) { - future, rerr := armClient.DeleteResourceAsync(ctx, resourceID) - return future, nil, rerr - }, - assertion: func(count int, future *azure.Future, _ *http.Response, rerr *retry.Error) { - assert.Equal(t, 3, count, "count") - assert.Nil(t, future, "future") - assert.NotNil(t, rerr, "rerr") - assert.Equal(t, true, rerr.Retriable, "rerr.Retriable") - }, - }, - { - description: "post resource", - action: func(armClient *Client, ctx context.Context, resourceID string, _ interface{}) (*azure.Future, *http.Response, *retry.Error) { - response, rerr := armClient.PostResource(ctx, resourceID, "post", "", map[string]interface{}{}) - return nil, response, rerr - }, - assertion: func(count int, _ *azure.Future, response *http.Response, rerr *retry.Error) { - assert.Equal(t, 3, count, "count") - assert.NotNil(t, response, "response") - assert.NotNil(t, rerr, "rerr") - assert.Equal(t, true, rerr.Retriable, "rerr.Retriable") - }, - }, - { - description: "delete resource", - action: func(armClient *Client, ctx context.Context, resourceID string, _ interface{}) (*azure.Future, *http.Response, *retry.Error) { - rerr := armClient.DeleteResource(ctx, resourceID) - return nil, nil, rerr - }, - assertion: func(count int, _ *azure.Future, _ *http.Response, rerr *retry.Error) { - assert.Equal(t, 3, count, "count") - assert.NotNil(t, rerr, "rerr") - assert.Equal(t, true, rerr.Retriable, "rerr.Retriable") - }, - }, - { - description: "head resource", - action: func(armClient *Client, ctx context.Context, resourceID string, _ interface{}) (*azure.Future, *http.Response, *retry.Error) { - response, rerr := armClient.HeadResource(ctx, resourceID) - return nil, response, rerr - }, - assertion: func(count int, _ *azure.Future, response *http.Response, rerr *retry.Error) { - assert.Equal(t, 3, count, "count") - assert.NotNil(t, response, "response") - assert.NotNil(t, rerr, "rerr") - assert.Equal(t, true, rerr.Retriable, "rerr.Retriable") - }, - }, - } { - t.Run(tc.description, func(_ *testing.T) { - count := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - count++ - http.Error(w, "failed", http.StatusInternalServerError) - })) - - azConfig := azureclients.ClientConfig{Backoff: &retry.Backoff{Steps: 3}, UserAgent: "test", Location: "eastus"} - armClient := New(nil, azConfig, server.URL, "2019-01-01") - armClient.client.RetryDuration = time.Millisecond * 1 - - ctx := context.Background() - resourceID := testResourceID - future, response, rerr := tc.action(armClient, ctx, resourceID, "") - tc.assertion(count, future, response, rerr) - }) - } -} - -func TestPatchResource(t *testing.T) { - handlers := []func(http.ResponseWriter, *http.Request){ - func(rw http.ResponseWriter, req *http.Request) { - assert.Equal(t, "PATCH", req.Method) - assert.Equal(t, expectedURI, req.URL.String()) - rw.Header().Set("Azure-AsyncOperation", - fmt.Sprintf("http://%s%s", req.Host, operationURI)) - rw.WriteHeader(http.StatusCreated) - }, - - func(rw http.ResponseWriter, req *http.Request) { - assert.Equal(t, "GET", req.Method) - assert.Equal(t, operationURI, req.URL.String()) - - rw.WriteHeader(http.StatusOK) - _, _ = rw.Write([]byte(`{"error":{"code":"InternalServerError"},"status":"Failed"}`)) - }, - } - - count := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - handlers[count](w, r) - count++ - if count > 1 { - count = 1 - } - })) - - azConfig := azureclients.ClientConfig{Backoff: &retry.Backoff{Steps: 1}, UserAgent: "test", Location: "eastus"} - armClient := New(nil, azConfig, server.URL, "2019-01-01") - armClient.client.RetryDuration = time.Millisecond * 1 - - ctx := context.Background() - response, rerr := armClient.PatchResource(ctx, testResourceID, nil) - assert.Equal(t, 1, count) - assert.Nil(t, response) - assert.NotNil(t, rerr) - assert.Equal(t, true, rerr.Retriable) -} - -func TestPatchResourceAsync(t *testing.T) { - expectedURI := "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP?api-version=2019-01-01" - operationURI := "/subscriptions/subscription/providers/Microsoft.Network/locations/eastus/operations/op?api-version=2019-01-01" - handlers := []func(http.ResponseWriter, *http.Request){ - func(rw http.ResponseWriter, req *http.Request) { - assert.Equal(t, "PATCH", req.Method) - assert.Equal(t, expectedURI, req.URL.String()) - rw.Header().Set("Azure-AsyncOperation", - fmt.Sprintf("http://%s%s", req.Host, operationURI)) - rw.WriteHeader(http.StatusCreated) - }, - - func(rw http.ResponseWriter, req *http.Request) { - assert.Equal(t, "GET", req.Method) - assert.Equal(t, operationURI, req.URL.String()) - - rw.WriteHeader(http.StatusOK) - _, _ = rw.Write([]byte(`{"error":{"code":"InternalServerError"},"status":"Failed"}`)) - }, - } - - count := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - handlers[count](w, r) - count++ - if count > 1 { - count = 1 - } - })) - - azConfig := azureclients.ClientConfig{Backoff: &retry.Backoff{Steps: 3}, UserAgent: "test", Location: "eastus"} - armClient := New(nil, azConfig, server.URL, "2019-01-01") - armClient.client.RetryDuration = time.Millisecond * 1 - - ctx := context.Background() - future, rerr := armClient.PatchResourceAsync(ctx, testResourceID, nil) - assert.Equal(t, 1, count) - assert.NotNil(t, future) - assert.Nil(t, rerr) -} - -func TestGetUserAgent(t *testing.T) { - armClient := New(nil, azureclients.ClientConfig{}, "", "2019-01-01") - assert.Contains(t, armClient.client.UserAgent, "kubernetes-cloudprovider") - - userAgent := GetUserAgent(armClient.client) - assert.Contains(t, userAgent, armClient.client.UserAgent) -} - -func TestGetResourceID(t *testing.T) { - for _, tc := range []struct { - description string - resourceID string - expectedResourceID string - }{ - { - description: "resource ID", - resourceID: GetResourceID("sub", "rg", "type", "name"), - expectedResourceID: "/subscriptions/sub/resourceGroups/rg/providers/type/name", - }, - { - description: "resource list ID", - resourceID: GetResourceListID("sub", "rg", "type"), - expectedResourceID: "/subscriptions/sub/resourceGroups/rg/providers/type", - }, - { - description: "child resource ID", - resourceID: GetChildResourceID("sub", "rg", "type", "name-1", "childType", "name-3"), - expectedResourceID: "/subscriptions/sub/resourceGroups/rg/providers/type/name-1/childType/name-3", - }, - { - description: "child resource list ID", - resourceID: GetChildResourcesListID("sub", "rg", "type", "name-1", "childType"), - expectedResourceID: "/subscriptions/sub/resourceGroups/rg/providers/type/name-1/childType", - }, - { - description: "provider resource ID", - resourceID: GetProviderResourceID("sub", "namespace"), - expectedResourceID: "/subscriptions/sub/providers/namespace", - }, - { - description: "provider resource list ID", - resourceID: GetProviderResourcesListID("sub"), - expectedResourceID: "/subscriptions/sub/providers", - }, - } { - t.Run(tc.description, func(t *testing.T) { - assert.Equal(t, tc.expectedResourceID, tc.resourceID) - }) - } -} diff --git a/pkg/azureclients/armclient/doc.go b/pkg/azureclients/armclient/doc.go deleted file mode 100644 index b033b164a2..0000000000 --- a/pkg/azureclients/armclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package armclient implements the client for ARM. -package armclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" diff --git a/pkg/azureclients/armclient/interface.go b/pkg/azureclients/armclient/interface.go deleted file mode 100644 index e66ba8a18b..0000000000 --- a/pkg/azureclients/armclient/interface.go +++ /dev/null @@ -1,106 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package armclient - -import ( - "context" - "net/http" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -// PutResourcesResponse defines the response for PutResources. -type PutResourcesResponse struct { - Response *http.Response - Error *retry.Error -} - -// Interface is the client interface for ARM. -// Don't forget to run "hack/update-mock-clients.sh" command to generate the mock client. -type Interface interface { - // Send sends a http request to ARM service with possible retry to regional ARM endpoint. - Send(ctx context.Context, request *http.Request, decorators ...autorest.SendDecorator) (*http.Response, *retry.Error) - - // PreparePutRequest prepares put request - PreparePutRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) - - // PreparePostRequest prepares post request - PreparePostRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) - - // PrepareGetRequest prepares get request - PrepareGetRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) - - // PrepareDeleteRequest preparse delete request - PrepareDeleteRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) - - // PrepareHeadRequest prepares head request - PrepareHeadRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) - - // WaitForAsyncOperationCompletion waits for an operation completion - WaitForAsyncOperationCompletion(ctx context.Context, future *azure.Future, asyncOperationName string) error - - // WaitForAsyncOperationResult waits for an operation result. - WaitForAsyncOperationResult(ctx context.Context, future *azure.Future, asyncOperationName string) (*http.Response, error) - - // SendAsync send a request and return a future object representing the async result as well as the origin http response - SendAsync(ctx context.Context, request *http.Request) (*azure.Future, *http.Response, *retry.Error) - - // PutResource puts a resource by resource ID - PutResource(ctx context.Context, resourceID string, parameters interface{}, decorators ...autorest.PrepareDecorator) (*http.Response, *retry.Error) - - // PutResourceAsync puts a resource by resource ID in async mode - PutResourceAsync(ctx context.Context, resourceID string, parameters interface{}, decorators ...autorest.PrepareDecorator) (*azure.Future, *retry.Error) - - // PutResourcesInBatches is similar with PutResources, but it sends sync request concurrently in batches. - PutResourcesInBatches(ctx context.Context, resources map[string]interface{}, batchSize int) map[string]*PutResourcesResponse - - // PatchResource patches a resource by resource ID - PatchResource(ctx context.Context, resourceID string, parameters interface{}, decorators ...autorest.PrepareDecorator) (*http.Response, *retry.Error) - - // PatchResourceAsync patches a resource by resource ID asynchronously - PatchResourceAsync(ctx context.Context, resourceID string, parameters interface{}, decorators ...autorest.PrepareDecorator) (*azure.Future, *retry.Error) - - // HeadResource heads a resource by resource ID - HeadResource(ctx context.Context, resourceID string) (*http.Response, *retry.Error) - - // GetResourceWithExpandQuery get a resource by resource ID with expand - GetResourceWithExpandQuery(ctx context.Context, resourceID, expand string) (*http.Response, *retry.Error) - - // GetResourceWithExpandAPIVersionQuery get a resource by resource ID with expand and API version. - GetResourceWithExpandAPIVersionQuery(ctx context.Context, resourceID, expand, apiVersion string) (*http.Response, *retry.Error) - - // GetResourceWithQueries get a resource by resource ID with queries. - GetResourceWithQueries(ctx context.Context, resourceID string, queries map[string]interface{}) (*http.Response, *retry.Error) - - // GetResource get a resource with decorators by resource ID - GetResource(ctx context.Context, resourceID string, decorators ...autorest.PrepareDecorator) (*http.Response, *retry.Error) - - // PostResource posts a resource by resource ID - PostResource(ctx context.Context, resourceID, action string, parameters interface{}, queryParameters map[string]interface{}) (*http.Response, *retry.Error) - - // DeleteResource deletes a resource by resource ID - DeleteResource(ctx context.Context, resourceID string, decorators ...autorest.PrepareDecorator) *retry.Error - - // DeleteResourceAsync delete a resource by resource ID and returns a future representing the async result - DeleteResourceAsync(ctx context.Context, resourceID string, decorators ...autorest.PrepareDecorator) (*azure.Future, *retry.Error) - - // CloseResponse closes a response - CloseResponse(ctx context.Context, response *http.Response) -} diff --git a/pkg/azureclients/armclient/mockarmclient/doc.go b/pkg/azureclients/armclient/mockarmclient/doc.go deleted file mode 100644 index 960299919a..0000000000 --- a/pkg/azureclients/armclient/mockarmclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package mockarmclient implements the mock client for ARM. -package mockarmclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient/mockarmclient" diff --git a/pkg/azureclients/armclient/mockarmclient/interface.go b/pkg/azureclients/armclient/mockarmclient/interface.go deleted file mode 100644 index 9dc11c6128..0000000000 --- a/pkg/azureclients/armclient/mockarmclient/interface.go +++ /dev/null @@ -1,467 +0,0 @@ -// /* -// Copyright The Kubernetes Authors. -// -// 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 MockGen. DO NOT EDIT. -// Source: pkg/azureclients/armclient/interface.go -// -// Generated by this command: -// -// mockgen -copyright_file=/home/runner/work/cloud-provider-azure/cloud-provider-azure/hack/boilerplate/boilerplate.generatego.txt -source=pkg/azureclients/armclient/interface.go -package=mockarmclient Interface -// - -// Package mockarmclient is a generated GoMock package. -package mockarmclient - -import ( - context "context" - http "net/http" - reflect "reflect" - - autorest "github.com/Azure/go-autorest/autorest" - azure "github.com/Azure/go-autorest/autorest/azure" - gomock "go.uber.org/mock/gomock" - armclient "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - retry "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -// MockInterface is a mock of Interface interface. -type MockInterface struct { - ctrl *gomock.Controller - recorder *MockInterfaceMockRecorder -} - -// MockInterfaceMockRecorder is the mock recorder for MockInterface. -type MockInterfaceMockRecorder struct { - mock *MockInterface -} - -// NewMockInterface creates a new mock instance. -func NewMockInterface(ctrl *gomock.Controller) *MockInterface { - mock := &MockInterface{ctrl: ctrl} - mock.recorder = &MockInterfaceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { - return m.recorder -} - -// CloseResponse mocks base method. -func (m *MockInterface) CloseResponse(ctx context.Context, response *http.Response) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "CloseResponse", ctx, response) -} - -// CloseResponse indicates an expected call of CloseResponse. -func (mr *MockInterfaceMockRecorder) CloseResponse(ctx, response any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CloseResponse", reflect.TypeOf((*MockInterface)(nil).CloseResponse), ctx, response) -} - -// DeleteResource mocks base method. -func (m *MockInterface) DeleteResource(ctx context.Context, resourceID string, decorators ...autorest.PrepareDecorator) *retry.Error { - m.ctrl.T.Helper() - varargs := []any{ctx, resourceID} - for _, a := range decorators { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "DeleteResource", varargs...) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// DeleteResource indicates an expected call of DeleteResource. -func (mr *MockInterfaceMockRecorder) DeleteResource(ctx, resourceID any, decorators ...any) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]any{ctx, resourceID}, decorators...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteResource", reflect.TypeOf((*MockInterface)(nil).DeleteResource), varargs...) -} - -// DeleteResourceAsync mocks base method. -func (m *MockInterface) DeleteResourceAsync(ctx context.Context, resourceID string, decorators ...autorest.PrepareDecorator) (*azure.Future, *retry.Error) { - m.ctrl.T.Helper() - varargs := []any{ctx, resourceID} - for _, a := range decorators { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "DeleteResourceAsync", varargs...) - ret0, _ := ret[0].(*azure.Future) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// DeleteResourceAsync indicates an expected call of DeleteResourceAsync. -func (mr *MockInterfaceMockRecorder) DeleteResourceAsync(ctx, resourceID any, decorators ...any) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]any{ctx, resourceID}, decorators...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteResourceAsync", reflect.TypeOf((*MockInterface)(nil).DeleteResourceAsync), varargs...) -} - -// GetResource mocks base method. -func (m *MockInterface) GetResource(ctx context.Context, resourceID string, decorators ...autorest.PrepareDecorator) (*http.Response, *retry.Error) { - m.ctrl.T.Helper() - varargs := []any{ctx, resourceID} - for _, a := range decorators { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "GetResource", varargs...) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// GetResource indicates an expected call of GetResource. -func (mr *MockInterfaceMockRecorder) GetResource(ctx, resourceID any, decorators ...any) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]any{ctx, resourceID}, decorators...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetResource", reflect.TypeOf((*MockInterface)(nil).GetResource), varargs...) -} - -// GetResourceWithExpandAPIVersionQuery mocks base method. -func (m *MockInterface) GetResourceWithExpandAPIVersionQuery(ctx context.Context, resourceID, expand, apiVersion string) (*http.Response, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetResourceWithExpandAPIVersionQuery", ctx, resourceID, expand, apiVersion) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// GetResourceWithExpandAPIVersionQuery indicates an expected call of GetResourceWithExpandAPIVersionQuery. -func (mr *MockInterfaceMockRecorder) GetResourceWithExpandAPIVersionQuery(ctx, resourceID, expand, apiVersion any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetResourceWithExpandAPIVersionQuery", reflect.TypeOf((*MockInterface)(nil).GetResourceWithExpandAPIVersionQuery), ctx, resourceID, expand, apiVersion) -} - -// GetResourceWithExpandQuery mocks base method. -func (m *MockInterface) GetResourceWithExpandQuery(ctx context.Context, resourceID, expand string) (*http.Response, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetResourceWithExpandQuery", ctx, resourceID, expand) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// GetResourceWithExpandQuery indicates an expected call of GetResourceWithExpandQuery. -func (mr *MockInterfaceMockRecorder) GetResourceWithExpandQuery(ctx, resourceID, expand any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetResourceWithExpandQuery", reflect.TypeOf((*MockInterface)(nil).GetResourceWithExpandQuery), ctx, resourceID, expand) -} - -// GetResourceWithQueries mocks base method. -func (m *MockInterface) GetResourceWithQueries(ctx context.Context, resourceID string, queries map[string]any) (*http.Response, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetResourceWithQueries", ctx, resourceID, queries) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// GetResourceWithQueries indicates an expected call of GetResourceWithQueries. -func (mr *MockInterfaceMockRecorder) GetResourceWithQueries(ctx, resourceID, queries any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetResourceWithQueries", reflect.TypeOf((*MockInterface)(nil).GetResourceWithQueries), ctx, resourceID, queries) -} - -// HeadResource mocks base method. -func (m *MockInterface) HeadResource(ctx context.Context, resourceID string) (*http.Response, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HeadResource", ctx, resourceID) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// HeadResource indicates an expected call of HeadResource. -func (mr *MockInterfaceMockRecorder) HeadResource(ctx, resourceID any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HeadResource", reflect.TypeOf((*MockInterface)(nil).HeadResource), ctx, resourceID) -} - -// PatchResource mocks base method. -func (m *MockInterface) PatchResource(ctx context.Context, resourceID string, parameters any, decorators ...autorest.PrepareDecorator) (*http.Response, *retry.Error) { - m.ctrl.T.Helper() - varargs := []any{ctx, resourceID, parameters} - for _, a := range decorators { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "PatchResource", varargs...) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// PatchResource indicates an expected call of PatchResource. -func (mr *MockInterfaceMockRecorder) PatchResource(ctx, resourceID, parameters any, decorators ...any) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]any{ctx, resourceID, parameters}, decorators...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PatchResource", reflect.TypeOf((*MockInterface)(nil).PatchResource), varargs...) -} - -// PatchResourceAsync mocks base method. -func (m *MockInterface) PatchResourceAsync(ctx context.Context, resourceID string, parameters any, decorators ...autorest.PrepareDecorator) (*azure.Future, *retry.Error) { - m.ctrl.T.Helper() - varargs := []any{ctx, resourceID, parameters} - for _, a := range decorators { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "PatchResourceAsync", varargs...) - ret0, _ := ret[0].(*azure.Future) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// PatchResourceAsync indicates an expected call of PatchResourceAsync. -func (mr *MockInterfaceMockRecorder) PatchResourceAsync(ctx, resourceID, parameters any, decorators ...any) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]any{ctx, resourceID, parameters}, decorators...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PatchResourceAsync", reflect.TypeOf((*MockInterface)(nil).PatchResourceAsync), varargs...) -} - -// PostResource mocks base method. -func (m *MockInterface) PostResource(ctx context.Context, resourceID, action string, parameters any, queryParameters map[string]any) (*http.Response, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PostResource", ctx, resourceID, action, parameters, queryParameters) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// PostResource indicates an expected call of PostResource. -func (mr *MockInterfaceMockRecorder) PostResource(ctx, resourceID, action, parameters, queryParameters any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostResource", reflect.TypeOf((*MockInterface)(nil).PostResource), ctx, resourceID, action, parameters, queryParameters) -} - -// PrepareDeleteRequest mocks base method. -func (m *MockInterface) PrepareDeleteRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) { - m.ctrl.T.Helper() - varargs := []any{ctx} - for _, a := range decorators { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "PrepareDeleteRequest", varargs...) - ret0, _ := ret[0].(*http.Request) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PrepareDeleteRequest indicates an expected call of PrepareDeleteRequest. -func (mr *MockInterfaceMockRecorder) PrepareDeleteRequest(ctx any, decorators ...any) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]any{ctx}, decorators...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrepareDeleteRequest", reflect.TypeOf((*MockInterface)(nil).PrepareDeleteRequest), varargs...) -} - -// PrepareGetRequest mocks base method. -func (m *MockInterface) PrepareGetRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) { - m.ctrl.T.Helper() - varargs := []any{ctx} - for _, a := range decorators { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "PrepareGetRequest", varargs...) - ret0, _ := ret[0].(*http.Request) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PrepareGetRequest indicates an expected call of PrepareGetRequest. -func (mr *MockInterfaceMockRecorder) PrepareGetRequest(ctx any, decorators ...any) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]any{ctx}, decorators...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrepareGetRequest", reflect.TypeOf((*MockInterface)(nil).PrepareGetRequest), varargs...) -} - -// PrepareHeadRequest mocks base method. -func (m *MockInterface) PrepareHeadRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) { - m.ctrl.T.Helper() - varargs := []any{ctx} - for _, a := range decorators { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "PrepareHeadRequest", varargs...) - ret0, _ := ret[0].(*http.Request) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PrepareHeadRequest indicates an expected call of PrepareHeadRequest. -func (mr *MockInterfaceMockRecorder) PrepareHeadRequest(ctx any, decorators ...any) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]any{ctx}, decorators...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrepareHeadRequest", reflect.TypeOf((*MockInterface)(nil).PrepareHeadRequest), varargs...) -} - -// PreparePostRequest mocks base method. -func (m *MockInterface) PreparePostRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) { - m.ctrl.T.Helper() - varargs := []any{ctx} - for _, a := range decorators { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "PreparePostRequest", varargs...) - ret0, _ := ret[0].(*http.Request) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PreparePostRequest indicates an expected call of PreparePostRequest. -func (mr *MockInterfaceMockRecorder) PreparePostRequest(ctx any, decorators ...any) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]any{ctx}, decorators...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PreparePostRequest", reflect.TypeOf((*MockInterface)(nil).PreparePostRequest), varargs...) -} - -// PreparePutRequest mocks base method. -func (m *MockInterface) PreparePutRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) { - m.ctrl.T.Helper() - varargs := []any{ctx} - for _, a := range decorators { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "PreparePutRequest", varargs...) - ret0, _ := ret[0].(*http.Request) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PreparePutRequest indicates an expected call of PreparePutRequest. -func (mr *MockInterfaceMockRecorder) PreparePutRequest(ctx any, decorators ...any) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]any{ctx}, decorators...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PreparePutRequest", reflect.TypeOf((*MockInterface)(nil).PreparePutRequest), varargs...) -} - -// PutResource mocks base method. -func (m *MockInterface) PutResource(ctx context.Context, resourceID string, parameters any, decorators ...autorest.PrepareDecorator) (*http.Response, *retry.Error) { - m.ctrl.T.Helper() - varargs := []any{ctx, resourceID, parameters} - for _, a := range decorators { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "PutResource", varargs...) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// PutResource indicates an expected call of PutResource. -func (mr *MockInterfaceMockRecorder) PutResource(ctx, resourceID, parameters any, decorators ...any) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]any{ctx, resourceID, parameters}, decorators...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutResource", reflect.TypeOf((*MockInterface)(nil).PutResource), varargs...) -} - -// PutResourceAsync mocks base method. -func (m *MockInterface) PutResourceAsync(ctx context.Context, resourceID string, parameters any, decorators ...autorest.PrepareDecorator) (*azure.Future, *retry.Error) { - m.ctrl.T.Helper() - varargs := []any{ctx, resourceID, parameters} - for _, a := range decorators { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "PutResourceAsync", varargs...) - ret0, _ := ret[0].(*azure.Future) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// PutResourceAsync indicates an expected call of PutResourceAsync. -func (mr *MockInterfaceMockRecorder) PutResourceAsync(ctx, resourceID, parameters any, decorators ...any) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]any{ctx, resourceID, parameters}, decorators...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutResourceAsync", reflect.TypeOf((*MockInterface)(nil).PutResourceAsync), varargs...) -} - -// PutResourcesInBatches mocks base method. -func (m *MockInterface) PutResourcesInBatches(ctx context.Context, resources map[string]any, batchSize int) map[string]*armclient.PutResourcesResponse { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PutResourcesInBatches", ctx, resources, batchSize) - ret0, _ := ret[0].(map[string]*armclient.PutResourcesResponse) - return ret0 -} - -// PutResourcesInBatches indicates an expected call of PutResourcesInBatches. -func (mr *MockInterfaceMockRecorder) PutResourcesInBatches(ctx, resources, batchSize any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutResourcesInBatches", reflect.TypeOf((*MockInterface)(nil).PutResourcesInBatches), ctx, resources, batchSize) -} - -// Send mocks base method. -func (m *MockInterface) Send(ctx context.Context, request *http.Request, decorators ...autorest.SendDecorator) (*http.Response, *retry.Error) { - m.ctrl.T.Helper() - varargs := []any{ctx, request} - for _, a := range decorators { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "Send", varargs...) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// Send indicates an expected call of Send. -func (mr *MockInterfaceMockRecorder) Send(ctx, request any, decorators ...any) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]any{ctx, request}, decorators...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Send", reflect.TypeOf((*MockInterface)(nil).Send), varargs...) -} - -// SendAsync mocks base method. -func (m *MockInterface) SendAsync(ctx context.Context, request *http.Request) (*azure.Future, *http.Response, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SendAsync", ctx, request) - ret0, _ := ret[0].(*azure.Future) - ret1, _ := ret[1].(*http.Response) - ret2, _ := ret[2].(*retry.Error) - return ret0, ret1, ret2 -} - -// SendAsync indicates an expected call of SendAsync. -func (mr *MockInterfaceMockRecorder) SendAsync(ctx, request any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAsync", reflect.TypeOf((*MockInterface)(nil).SendAsync), ctx, request) -} - -// WaitForAsyncOperationCompletion mocks base method. -func (m *MockInterface) WaitForAsyncOperationCompletion(ctx context.Context, future *azure.Future, asyncOperationName string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WaitForAsyncOperationCompletion", ctx, future, asyncOperationName) - ret0, _ := ret[0].(error) - return ret0 -} - -// WaitForAsyncOperationCompletion indicates an expected call of WaitForAsyncOperationCompletion. -func (mr *MockInterfaceMockRecorder) WaitForAsyncOperationCompletion(ctx, future, asyncOperationName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitForAsyncOperationCompletion", reflect.TypeOf((*MockInterface)(nil).WaitForAsyncOperationCompletion), ctx, future, asyncOperationName) -} - -// WaitForAsyncOperationResult mocks base method. -func (m *MockInterface) WaitForAsyncOperationResult(ctx context.Context, future *azure.Future, asyncOperationName string) (*http.Response, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WaitForAsyncOperationResult", ctx, future, asyncOperationName) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WaitForAsyncOperationResult indicates an expected call of WaitForAsyncOperationResult. -func (mr *MockInterfaceMockRecorder) WaitForAsyncOperationResult(ctx, future, asyncOperationName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitForAsyncOperationResult", reflect.TypeOf((*MockInterface)(nil).WaitForAsyncOperationResult), ctx, future, asyncOperationName) -} diff --git a/pkg/azureclients/armclient/util.go b/pkg/azureclients/armclient/util.go deleted file mode 100644 index 806c4a0b6c..0000000000 --- a/pkg/azureclients/armclient/util.go +++ /dev/null @@ -1,197 +0,0 @@ -/* -Copyright 2022 The Kubernetes Authors. - -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. -*/ - -package armclient - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "html" - "io" - "net/http" - "net/http/httputil" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest" - "k8s.io/client-go/util/flowcontrol" - "k8s.io/klog/v2" - - "sigs.k8s.io/cloud-provider-azure/pkg/metrics" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -func NewRateLimitSendDecorater(ratelimiter flowcontrol.RateLimiter, mc *metrics.MetricContext) autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - if !ratelimiter.TryAccept() { - mc.RateLimitedCount() - return nil, fmt.Errorf("rate limit reached") - } - return s.Do(r) - }) - } -} - -func NewThrottledSendDecorater(mc *metrics.MetricContext) autorest.SendDecorator { - var retryTimer time.Time - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - if retryTimer.After(time.Now()) { - mc.ThrottledCount() - return nil, fmt.Errorf("request is throttled") - } - resp, err := s.Do(r) - rerr := retry.GetError(resp, err) - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - retryTimer = rerr.RetryAfter - } - return resp, err - }) - } -} - -func NewErrorCounterSendDecorator(mc *metrics.MetricContext) autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - rerr := retry.GetError(resp, err) - mc.Observe(rerr) - return resp, err - }) - } -} - -func DoDumpRequest(v klog.Level) autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - - return autorest.SenderFunc(func(request *http.Request) (*http.Response, error) { - if request != nil { - requestDump, err := httputil.DumpRequest(request, true) - if err != nil { - klog.Errorf("Failed to dump request: %v", err) - } else { - klog.V(v).Infof("Dumping request: %s", string(requestDump)) - } - } - return s.Do(request) - }) - } -} - -func WithMetricsSendDecoratorWrapper(prefix, request, resourceGroup, subscriptionID, source string, factory func(mc *metrics.MetricContext) []autorest.SendDecorator) autorest.SendDecorator { - mc := metrics.NewMetricContext(prefix, request, resourceGroup, subscriptionID, source) - if factory != nil { - return func(s autorest.Sender) autorest.Sender { - return autorest.DecorateSender(s, factory(mc)...) - } - } - return nil -} - -// DoHackRegionalRetryForGET checks if GET request returns empty response and retries regional server or returns error. -func DoHackRegionalRetryForGET(c *Client) autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(request *http.Request) (*http.Response, error) { - response, rerr := s.Do(request) - if response == nil { - klog.V(2).Infof("response is empty") - return response, rerr - } - - bodyBytes, _ := io.ReadAll(response.Body) - defer func() { - response.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) - }() - - bodyString := string(bodyBytes) - trimmed := strings.TrimSpace(bodyString) - klog.V(6).Infof("%s %s got response with ContentLength %d, StatusCode %d and responseBody length %d", request.Method, request.URL.Path, response.ContentLength, response.StatusCode, len(trimmed)) - - // Hack: retry the regional ARM endpoint in case of ARM traffic split and arm resource group replication is too slow - // Empty content and 2xx http status code are returned in this case. - // Issue: https://github.com/kubernetes-sigs/cloud-provider-azure/issues/1296 - // Such situation also needs retrying that ContentLength is -1, StatusCode is 200 and an empty body is returned. - emptyResp := (response.ContentLength == 0 || trimmed == "" || trimmed == "{}") && response.StatusCode >= 200 && response.StatusCode < 300 - if !emptyResp { - if rerr == nil || response.StatusCode == http.StatusNotFound || c.regionalEndpoint == "" { - return response, rerr - } - - var body map[string]interface{} - if e := json.Unmarshal(bodyBytes, &body); e != nil { - klog.Errorf("Send.sendRequest: error in parsing response body string %q: %s, Skip retrying regional host", bodyBytes, e.Error()) - return response, rerr - } - - err, ok := body["error"].(map[string]interface{}) - if !ok || err["code"] == nil || !strings.EqualFold(err["code"].(string), "ResourceGroupNotFound") { - klog.V(5).Infof("Send.sendRequest: response body does not contain ResourceGroupNotFound error code. Skip retrying regional host") - return response, rerr - } - } - - // Do regional request - currentHost := request.URL.Host - if request.Host != "" { - currentHost = request.Host - } - - if strings.HasPrefix(strings.ToLower(currentHost), c.regionalEndpoint) { - klog.V(5).Infof("Send.sendRequest: current host %s is regional host. Skip retrying regional host.", html.EscapeString(currentHost)) - return response, rerr - } - - request.Host = c.regionalEndpoint - request.URL.Host = c.regionalEndpoint - klog.V(6).Infof("Send.sendRegionalRequest on ResourceGroupNotFound error. Retrying regional host: %s", html.EscapeString(request.Host)) - - regionalResponse, regionalError := s.Do(request) - - // only use the result if the regional request actually goes through and returns 2xx status code, for two reasons: - // 1. the retry on regional ARM host approach is a hack. - // 2. the concatenated regional uri could be wrong as the rule is not officially declared by ARM. - if regionalResponse == nil || regionalResponse.StatusCode > 299 { - regionalErrStr := "" - if regionalError != nil { - regionalErrStr = regionalError.Error() - } - - klog.V(6).Infof("Send.sendRegionalRequest failed to get response from regional host, error: %q. Ignoring the result.", regionalErrStr) - return response, rerr - } - - // Do the same check on regional response just like the global one - bodyBytes, _ = io.ReadAll(regionalResponse.Body) - defer func() { - regionalResponse.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) - }() - bodyString = string(bodyBytes) - trimmed = strings.TrimSpace(bodyString) - emptyResp = (regionalResponse.ContentLength == 0 || trimmed == "" || trimmed == "{}") && regionalResponse.StatusCode >= 200 && regionalResponse.StatusCode < 300 - if emptyResp { - contentLengthErrStr := fmt.Sprintf("empty response with trimmed body %q, ContentLength %d and StatusCode %d", trimmed, regionalResponse.ContentLength, regionalResponse.StatusCode) - klog.Error(contentLengthErrStr) - return response, errors.New(contentLengthErrStr) - } - - return regionalResponse, regionalError - }) - } -} diff --git a/pkg/azureclients/azure_client_config.go b/pkg/azureclients/azure_client_config.go index e25f5caa96..476039ac7a 100644 --- a/pkg/azureclients/azure_client_config.go +++ b/pkg/azureclients/azure_client_config.go @@ -17,36 +17,9 @@ limitations under the License. package azureclients import ( - "time" - - "github.com/Azure/go-autorest/autorest" "k8s.io/client-go/util/flowcontrol" - - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) -// ClientConfig contains all essential information to create an Azure client. -type ClientConfig struct { - CloudName string - Location string - ExtendedLocation *ExtendedLocation - SubscriptionID string - ResourceManagerEndpoint string - Authorizer autorest.Authorizer - RateLimitConfig *RateLimitConfig - RestClientConfig RestClientConfig - Backoff *retry.Backoff - UserAgent string - DisableAzureStackCloud bool -} - -// WithRateLimiter returns a new ClientConfig with rateLimitConfig set. -func (cfg *ClientConfig) WithRateLimiter(rl *RateLimitConfig) *ClientConfig { - newClientConfig := *cfg - newClientConfig.RateLimitConfig = rl - return &newClientConfig -} - // RateLimitConfig indicates the rate limit config options. type RateLimitConfig struct { // Enable rate limiting @@ -61,12 +34,6 @@ type RateLimitConfig struct { CloudProviderRateLimitBucketWrite int `json:"cloudProviderRateLimitBucketWrite,omitempty" yaml:"cloudProviderRateLimitBucketWrite,omitempty"` } -type RestClientConfig struct { - PollingDelay *time.Duration - RetryAttempts *int - RetryDuration *time.Duration -} - // ExtendedLocation contains additional info about the location of resources. type ExtendedLocation struct { // Name - The name of the extended location. diff --git a/pkg/azureclients/azure_client_config_test.go b/pkg/azureclients/azure_client_config_test.go index f9df84ee97..c9e53d8e1b 100644 --- a/pkg/azureclients/azure_client_config_test.go +++ b/pkg/azureclients/azure_client_config_test.go @@ -23,15 +23,6 @@ import ( "k8s.io/client-go/util/flowcontrol" ) -func TestWithRateLimiter(t *testing.T) { - config := &ClientConfig{} - assert.Nil(t, config.RateLimitConfig) - c := config.WithRateLimiter(&RateLimitConfig{CloudProviderRateLimit: true}) - assert.Equal(t, &RateLimitConfig{CloudProviderRateLimit: true}, c.RateLimitConfig) - config.WithRateLimiter(nil) - assert.Nil(t, config.RateLimitConfig) -} - func TestRateLimitEnabled(t *testing.T) { assert.Equal(t, false, RateLimitEnabled(nil)) config := &RateLimitConfig{} diff --git a/pkg/azureclients/diskclient/azure_diskclient.go b/pkg/azureclients/diskclient/azure_diskclient.go deleted file mode 100644 index d3095b041c..0000000000 --- a/pkg/azureclients/diskclient/azure_diskclient.go +++ /dev/null @@ -1,472 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package diskclient - -import ( - "context" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/klog/v2" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/metrics" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -var _ Interface = &Client{} - -const diskResourceType = "Microsoft.Compute/disks" - -// Client implements Disk client Interface. -type Client struct { - armClient armclient.Interface - subscriptionID string - cloudName string - - // Rate limiting configures. - rateLimiterReader flowcontrol.RateLimiter - rateLimiterWriter flowcontrol.RateLimiter - - // ARM throttling configures. - RetryAfterReader time.Time - RetryAfterWriter time.Time -} - -// New creates a new Disk client with ratelimiting. -func New(config *azclients.ClientConfig) *Client { - baseURI := config.ResourceManagerEndpoint - authorizer := config.Authorizer - apiVersion := APIVersion - - if strings.EqualFold(config.CloudName, AzureStackCloudName) && !config.DisableAzureStackCloud { - apiVersion = AzureStackCloudAPIVersion - } - - klog.V(2).Infof("Azure DisksClient using API version: %s", apiVersion) - armClient := armclient.New(authorizer, *config, baseURI, apiVersion) - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig) - - if azclients.RateLimitEnabled(config.RateLimitConfig) { - klog.V(2).Infof("Azure DisksClient (read ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPS, - config.RateLimitConfig.CloudProviderRateLimitBucket) - klog.V(2).Infof("Azure DisksClient (write ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPSWrite, - config.RateLimitConfig.CloudProviderRateLimitBucketWrite) - } - - client := &Client{ - armClient: armClient, - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - subscriptionID: config.SubscriptionID, - cloudName: config.CloudName, - } - - return client -} - -// Get gets a Disk. -func (c *Client) Get(ctx context.Context, subsID, resourceGroupName, diskName string) (compute.Disk, *retry.Error) { - if subsID == "" { - subsID = c.subscriptionID - } - mc := metrics.NewMetricContext("disks", "get", resourceGroupName, subsID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return compute.Disk{}, retry.GetRateLimitError(false, "GetDisk") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("GetDisk", "client throttled", c.RetryAfterReader) - return compute.Disk{}, rerr - } - - result, rerr := c.getDisk(ctx, subsID, resourceGroupName, diskName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// getDisk gets a Disk. -func (c *Client) getDisk(ctx context.Context, subsID, resourceGroupName, diskName string) (compute.Disk, *retry.Error) { - resourceID := armclient.GetResourceID( - subsID, - resourceGroupName, - diskResourceType, - diskName, - ) - result := compute.Disk{} - - response, rerr := c.armClient.GetResource(ctx, resourceID) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "disk.get.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "disk.get.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} - -// CreateOrUpdate creates or updates a Disk. -func (c *Client) CreateOrUpdate(ctx context.Context, subsID, resourceGroupName, diskName string, diskParameter compute.Disk) *retry.Error { - if subsID == "" { - subsID = c.subscriptionID - } - mc := metrics.NewMetricContext("disks", "create_or_update", resourceGroupName, subsID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "DiskCreateOrUpdate") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("DiskCreateOrUpdate", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.createOrUpdateDisk(ctx, subsID, resourceGroupName, diskName, diskParameter) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// createOrUpdateDisk creates or updates a Disk. -func (c *Client) createOrUpdateDisk(ctx context.Context, subsID, resourceGroupName, diskName string, diskParameter compute.Disk) *retry.Error { - resourceID := armclient.GetResourceID( - subsID, - resourceGroupName, - diskResourceType, - diskName, - ) - - response, rerr := c.armClient.PutResource(ctx, resourceID, diskParameter) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "disk.put.request", resourceID, rerr.Error()) - return rerr - } - - if response != nil && response.StatusCode != http.StatusNoContent { - _, rerr = c.createOrUpdateResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "disk.put.respond", resourceID, rerr.Error()) - return rerr - } - } - - return nil -} - -func (c *Client) createOrUpdateResponder(resp *http.Response) (*compute.Disk, *retry.Error) { - result := &compute.Disk{} - err := autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return result, retry.GetError(resp, err) -} - -// Update creates or updates a Disk. -func (c *Client) Update(ctx context.Context, subsID, resourceGroupName, diskName string, diskParameter compute.DiskUpdate) *retry.Error { - if subsID == "" { - subsID = c.subscriptionID - } - mc := metrics.NewMetricContext("disks", "update", resourceGroupName, subsID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "DiskUpdate") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("DiskUpdate", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.updateDisk(ctx, subsID, resourceGroupName, diskName, diskParameter) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// updateDisk updates a Disk. -func (c *Client) updateDisk(ctx context.Context, subsID, resourceGroupName, diskName string, diskParameter compute.DiskUpdate) *retry.Error { - resourceID := armclient.GetResourceID( - subsID, - resourceGroupName, - diskResourceType, - diskName, - ) - - response, rerr := c.armClient.PatchResource(ctx, resourceID, diskParameter) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "disk.put.request", resourceID, rerr.Error()) - return rerr - } - - if response != nil && response.StatusCode != http.StatusNoContent { - _, rerr = c.updateResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "disk.put.respond", resourceID, rerr.Error()) - return rerr - } - } - - return nil -} - -func (c *Client) updateResponder(resp *http.Response) (*compute.Disk, *retry.Error) { - result := &compute.Disk{} - err := autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return result, retry.GetError(resp, err) -} - -// Delete deletes a Disk by name. -func (c *Client) Delete(ctx context.Context, subsID, resourceGroupName, diskName string) *retry.Error { - if subsID == "" { - subsID = c.subscriptionID - } - mc := metrics.NewMetricContext("disks", "delete", resourceGroupName, subsID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "DiskDelete") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("DiskDelete", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.deleteDisk(ctx, subsID, resourceGroupName, diskName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// deleteDisk deletes a PublicIPAddress by name. -func (c *Client) deleteDisk(ctx context.Context, subsID, resourceGroupName string, diskName string) *retry.Error { - resourceID := armclient.GetResourceID( - subsID, - resourceGroupName, - diskResourceType, - diskName, - ) - - return c.armClient.DeleteResource(ctx, resourceID) -} - -// ListByResourceGroup lists all the disks under a resource group. -func (c *Client) ListByResourceGroup(ctx context.Context, subsID, resourceGroupName string) ([]compute.Disk, *retry.Error) { - if subsID == "" { - subsID = c.subscriptionID - } - resourceID := armclient.GetResourceListID(subsID, resourceGroupName, diskResourceType) - - result := make([]compute.Disk, 0) - page := &DiskListPage{} - page.fn = c.listNextResults - - resp, rerr := c.armClient.GetResource(ctx, resourceID) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "disk.list.request", resourceID, rerr.Error()) - return result, rerr - } - - var err error - page.dl, err = c.listResponder(resp) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "disk.list.respond", resourceID, err) - return result, retry.GetError(resp, err) - } - - for { - result = append(result, page.Values()...) - - // Abort the loop when there's no nextLink in the response. - if ptr.Deref(page.Response().NextLink, "") == "" { - break - } - - if err = page.NextWithContext(ctx); err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "disk.list.next", resourceID, err) - return result, retry.GetError(page.Response().Response.Response, err) - } - } - - return result, nil -} - -// listNextResults retrieves the next set of results, if any. -func (c *Client) listNextResults(ctx context.Context, lastResults compute.DiskList) (result compute.DiskList, err error) { - req, err := c.diskListPreparer(ctx, lastResults) - if err != nil { - return result, autorest.NewErrorWithError(err, "diskclient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - - resp, rerr := c.armClient.Send(ctx, req) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(rerr.Error(), "diskclient", "listNextResults", resp, "Failure sending next results request") - } - - result, err = c.listResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "diskclient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// listResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (c *Client) listResponder(resp *http.Response) (result compute.DiskList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -func (c *Client) diskListPreparer(ctx context.Context, lr compute.DiskList) (*http.Request, error) { - if lr.NextLink == nil || len(ptr.Deref(lr.NextLink, "")) < 1 { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(ptr.Deref(lr.NextLink, ""))) -} - -// DiskListPage contains a page of Disk values. -type DiskListPage struct { - fn func(context.Context, compute.DiskList) (compute.DiskList, error) - dl compute.DiskList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *DiskListPage) NextWithContext(ctx context.Context) (err error) { - next, err := page.fn(ctx, page.dl) - if err != nil { - return err - } - page.dl = next - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *DiskListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page DiskListPage) NotDone() bool { - return !page.dl.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page DiskListPage) Response() compute.DiskList { - return page.dl -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page DiskListPage) Values() []compute.Disk { - if page.dl.IsEmpty() { - return nil - } - return *page.dl.Value -} diff --git a/pkg/azureclients/diskclient/azure_diskclient_test.go b/pkg/azureclients/diskclient/azure_diskclient_test.go deleted file mode 100644 index fec642f392..0000000000 --- a/pkg/azureclients/diskclient/azure_diskclient_test.go +++ /dev/null @@ -1,267 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package diskclient - -import ( - "bytes" - "context" - "fmt" - "io" - "net/http" - "testing" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest" - "github.com/stretchr/testify/assert" - - "go.uber.org/mock/gomock" - - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient/mockarmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - testResourceID = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/disks/disk1" -) - -func TestNew(t *testing.T) { - config := &azclients.ClientConfig{ - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - diskClient := New(config) - assert.Equal(t, "sub", diskClient.subscriptionID) - assert.NotEmpty(t, diskClient.rateLimiterReader) - assert.NotEmpty(t, diskClient.rateLimiterWriter) -} - -func TestNewAzureStack(t *testing.T) { - config := &azclients.ClientConfig{ - CloudName: "AZURESTACKCLOUD", - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - diskClient := New(config) - assert.Equal(t, "AZURESTACKCLOUD", diskClient.cloudName) - assert.Equal(t, "sub", diskClient.subscriptionID) -} - -func TestGetNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - diskClient := getTestDiskClient(armClient) - expected := compute.Disk{Response: autorest.Response{}} - result, rerr := diskClient.Get(context.TODO(), "", "rg", "disk1") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestGetInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - diskClient := getTestDiskClient(armClient) - expected := compute.Disk{Response: autorest.Response{}} - result, rerr := diskClient.Get(context.TODO(), "", "rg", "disk1") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestGetThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - diskClient := getTestDiskClient(armClient) - result, rerr := diskClient.Get(context.TODO(), "", "rg", "disk1") - assert.Empty(t, result) - assert.Equal(t, throttleErr, rerr) -} - -func TestCreateOrUpdate(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - disk := getTestDisk("disk1") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(disk.ID, ""), disk).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - diskClient := getTestDiskClient(armClient) - rerr := diskClient.CreateOrUpdate(context.TODO(), "", "rg", "disk1", disk) - assert.Nil(t, rerr) - - response = &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(disk.ID, ""), disk).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - rerr = diskClient.CreateOrUpdate(context.TODO(), "", "rg", "disk1", disk) - assert.Equal(t, throttleErr, rerr) -} - -func TestUpdate(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - diskUpdate := getTestDiskUpdate() - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PatchResource(gomock.Any(), testResourceID, diskUpdate).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - diskClient := getTestDiskClient(armClient) - rerr := diskClient.Update(context.TODO(), "", "rg", "disk1", diskUpdate) - assert.Nil(t, rerr) - - response = &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - armClient.EXPECT().PatchResource(gomock.Any(), testResourceID, diskUpdate).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - rerr = diskClient.Update(context.TODO(), "", "rg", "disk1", diskUpdate) - assert.Equal(t, throttleErr, rerr) -} - -func getTestDiskUpdate() compute.DiskUpdate { - return compute.DiskUpdate{ - DiskUpdateProperties: &compute.DiskUpdateProperties{ - DiskSizeGB: ptr.To(int32(100)), - }, - } -} - -func TestDelete(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - r := getTestDisk("disk1") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().DeleteResource(gomock.Any(), ptr.Deref(r.ID, "")).Return(nil).Times(1) - - diskClient := getTestDiskClient(armClient) - rerr := diskClient.Delete(context.TODO(), "", "rg", "disk1") - assert.Nil(t, rerr) - - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient.EXPECT().DeleteResource(gomock.Any(), ptr.Deref(r.ID, "")).Return(throttleErr).Times(1) - rerr = diskClient.Delete(context.TODO(), "", "rg", "disk1") - assert.Equal(t, throttleErr, rerr) -} - -func getTestDisk(name string) compute.Disk { - return compute.Disk{ - ID: ptr.To(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/disks/%s", name)), - Name: ptr.To(name), - Location: ptr.To("eastus"), - } -} - -func getTestDiskClient(armClient armclient.Interface) *Client { - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(&azclients.RateLimitConfig{}) - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} diff --git a/pkg/azureclients/diskclient/doc.go b/pkg/azureclients/diskclient/doc.go deleted file mode 100644 index ca4ec9a954..0000000000 --- a/pkg/azureclients/diskclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package diskclient implements the client for Disks. -package diskclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/diskclient" diff --git a/pkg/azureclients/diskclient/interface.go b/pkg/azureclients/diskclient/interface.go deleted file mode 100644 index 4259213b6e..0000000000 --- a/pkg/azureclients/diskclient/interface.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package diskclient - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - // APIVersion is the API version for compute. - APIVersion = "2022-07-02" - // AzureStackCloudAPIVersion is the API version for Azure Stack - AzureStackCloudAPIVersion = "2019-03-01" - // AzureStackCloudName is the cloud name of Azure Stack - AzureStackCloudName = "AZURESTACKCLOUD" -) - -// Interface is the client interface for Disks. -// Don't forget to run "hack/update-mock-clients.sh" command to generate the mock client. -type Interface interface { - // Get gets a Disk. - Get(ctx context.Context, subsID, resourceGroupName, diskName string) (result compute.Disk, rerr *retry.Error) - - // CreateOrUpdate creates or updates a Disk. - CreateOrUpdate(ctx context.Context, subsID, resourceGroupName, diskName string, diskParameter compute.Disk) *retry.Error - - // Update updates a Disk. - Update(ctx context.Context, subsID, resourceGroupName, diskName string, diskParameter compute.DiskUpdate) *retry.Error - - // Delete deletes a Disk by name. - Delete(ctx context.Context, subsID, resourceGroupName, diskName string) *retry.Error - - // ListByResourceGroup lists all the disks under a resource group. - ListByResourceGroup(ctx context.Context, subsID, resourceGroupName string) ([]compute.Disk, *retry.Error) -} diff --git a/pkg/azureclients/diskclient/mockdiskclient/doc.go b/pkg/azureclients/diskclient/mockdiskclient/doc.go deleted file mode 100644 index bc3c2e09b3..0000000000 --- a/pkg/azureclients/diskclient/mockdiskclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package mockdiskclient implements the mock client for Disks. -package mockdiskclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/diskclient/mockdiskclient" diff --git a/pkg/azureclients/diskclient/mockdiskclient/interface.go b/pkg/azureclients/diskclient/mockdiskclient/interface.go deleted file mode 100644 index b7108d37c2..0000000000 --- a/pkg/azureclients/diskclient/mockdiskclient/interface.go +++ /dev/null @@ -1,131 +0,0 @@ -// /* -// Copyright The Kubernetes Authors. -// -// 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 MockGen. DO NOT EDIT. -// Source: pkg/azureclients/diskclient/interface.go -// -// Generated by this command: -// -// mockgen -copyright_file=/home/runner/work/cloud-provider-azure/cloud-provider-azure/hack/boilerplate/boilerplate.generatego.txt -source=pkg/azureclients/diskclient/interface.go -package=mockdiskclient Interface -// - -// Package mockdiskclient is a generated GoMock package. -package mockdiskclient - -import ( - context "context" - reflect "reflect" - - compute "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - gomock "go.uber.org/mock/gomock" - retry "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -// MockInterface is a mock of Interface interface. -type MockInterface struct { - ctrl *gomock.Controller - recorder *MockInterfaceMockRecorder -} - -// MockInterfaceMockRecorder is the mock recorder for MockInterface. -type MockInterfaceMockRecorder struct { - mock *MockInterface -} - -// NewMockInterface creates a new mock instance. -func NewMockInterface(ctrl *gomock.Controller) *MockInterface { - mock := &MockInterface{ctrl: ctrl} - mock.recorder = &MockInterfaceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { - return m.recorder -} - -// CreateOrUpdate mocks base method. -func (m *MockInterface) CreateOrUpdate(ctx context.Context, subsID, resourceGroupName, diskName string, diskParameter compute.Disk) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrUpdate", ctx, subsID, resourceGroupName, diskName, diskParameter) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// CreateOrUpdate indicates an expected call of CreateOrUpdate. -func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, subsID, resourceGroupName, diskName, diskParameter any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdate", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, subsID, resourceGroupName, diskName, diskParameter) -} - -// Delete mocks base method. -func (m *MockInterface) Delete(ctx context.Context, subsID, resourceGroupName, diskName string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Delete", ctx, subsID, resourceGroupName, diskName) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// Delete indicates an expected call of Delete. -func (mr *MockInterfaceMockRecorder) Delete(ctx, subsID, resourceGroupName, diskName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, subsID, resourceGroupName, diskName) -} - -// Get mocks base method. -func (m *MockInterface) Get(ctx context.Context, subsID, resourceGroupName, diskName string) (compute.Disk, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", ctx, subsID, resourceGroupName, diskName) - ret0, _ := ret[0].(compute.Disk) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockInterfaceMockRecorder) Get(ctx, subsID, resourceGroupName, diskName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInterface)(nil).Get), ctx, subsID, resourceGroupName, diskName) -} - -// ListByResourceGroup mocks base method. -func (m *MockInterface) ListByResourceGroup(ctx context.Context, subsID, resourceGroupName string) ([]compute.Disk, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListByResourceGroup", ctx, subsID, resourceGroupName) - ret0, _ := ret[0].([]compute.Disk) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// ListByResourceGroup indicates an expected call of ListByResourceGroup. -func (mr *MockInterfaceMockRecorder) ListByResourceGroup(ctx, subsID, resourceGroupName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListByResourceGroup", reflect.TypeOf((*MockInterface)(nil).ListByResourceGroup), ctx, subsID, resourceGroupName) -} - -// Update mocks base method. -func (m *MockInterface) Update(ctx context.Context, subsID, resourceGroupName, diskName string, diskParameter compute.DiskUpdate) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Update", ctx, subsID, resourceGroupName, diskName, diskParameter) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// Update indicates an expected call of Update. -func (mr *MockInterfaceMockRecorder) Update(ctx, subsID, resourceGroupName, diskName, diskParameter any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockInterface)(nil).Update), ctx, subsID, resourceGroupName, diskName, diskParameter) -} diff --git a/pkg/azureclients/interfaceclient/azure_interfaceclient.go b/pkg/azureclients/interfaceclient/azure_interfaceclient.go deleted file mode 100644 index 5366abe454..0000000000 --- a/pkg/azureclients/interfaceclient/azure_interfaceclient.go +++ /dev/null @@ -1,337 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package interfaceclient - -import ( - "context" - "fmt" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/klog/v2" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/metrics" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -var _ Interface = &Client{} - -const netInterfaceResourceType = "Microsoft.Network/networkInterfaces" - -// Client implements network interface client. -type Client struct { - armClient armclient.Interface - subscriptionID string - cloudName string - disableAzureStackCloud bool - - // Rate limiting configures. - rateLimiterReader flowcontrol.RateLimiter - rateLimiterWriter flowcontrol.RateLimiter - - // ARM throttling configures. - RetryAfterReader time.Time - RetryAfterWriter time.Time - - computeAPIVersion string -} - -// New creates a new network interface client with ratelimiting. -func New(config *azclients.ClientConfig) *Client { - baseURI := config.ResourceManagerEndpoint - authorizer := config.Authorizer - apiVersion := APIVersion - if strings.EqualFold(config.CloudName, AzureStackCloudName) && !config.DisableAzureStackCloud { - apiVersion = AzureStackCloudAPIVersion - } - armClient := armclient.New(authorizer, *config, baseURI, apiVersion) - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig) - - if azclients.RateLimitEnabled(config.RateLimitConfig) { - klog.V(2).Infof("Azure InterfacesClient (read ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPS, - config.RateLimitConfig.CloudProviderRateLimitBucket) - klog.V(2).Infof("Azure InterfacesClient (write ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPSWrite, - config.RateLimitConfig.CloudProviderRateLimitBucketWrite) - } - - computeAPIVersion := ComputeAPIVersion - if strings.EqualFold(config.CloudName, AzureStackCloudName) && !config.DisableAzureStackCloud { - computeAPIVersion = AzureStackComputeAPIVersion - } - - client := &Client{ - armClient: armClient, - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - subscriptionID: config.SubscriptionID, - cloudName: config.CloudName, - disableAzureStackCloud: config.DisableAzureStackCloud, - computeAPIVersion: computeAPIVersion, - } - - return client -} - -// Get gets a network.Interface. -func (c *Client) Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, expand string) (network.Interface, *retry.Error) { - mc := metrics.NewMetricContext("interfaces", "get", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return network.Interface{}, retry.GetRateLimitError(false, "NicGet") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("NicGet", "client throttled", c.RetryAfterReader) - return network.Interface{}, rerr - } - - result, rerr := c.getNetworkInterface(ctx, resourceGroupName, networkInterfaceName, expand) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// getNetworkInterface gets a network.Interface. -func (c *Client) getNetworkInterface(ctx context.Context, resourceGroupName string, networkInterfaceName string, expand string) (network.Interface, *retry.Error) { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - netInterfaceResourceType, - networkInterfaceName, - ) - result := network.Interface{} - - response, rerr := c.armClient.GetResourceWithExpandQuery(ctx, resourceID, expand) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "nic.get.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "nic.get.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} - -// GetVirtualMachineScaleSetNetworkInterface gets a network.Interface of VMSS VM. -func (c *Client) GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (network.Interface, *retry.Error) { - mc := metrics.NewMetricContext("interfaces", "get_vmss_nic", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return network.Interface{}, retry.GetRateLimitError(false, "NicGetVirtualMachineScaleSetNetworkInterface") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("NicGetVirtualMachineScaleSetNetworkInterface", "client throttled", c.RetryAfterReader) - return network.Interface{}, rerr - } - - result, rerr := c.getVMSSNetworkInterface(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// getVMSSNetworkInterface gets a network.Interface of VMSS VM. -func (c *Client) getVMSSNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (network.Interface, *retry.Error) { - resourceID := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachineScaleSets/%s/virtualMachines/%s/networkInterfaces/%s", - autorest.Encode("path", c.subscriptionID), - autorest.Encode("path", resourceGroupName), - autorest.Encode("path", virtualMachineScaleSetName), - autorest.Encode("path", virtualmachineIndex), - autorest.Encode("path", networkInterfaceName), - ) - - result := network.Interface{} - - response, rerr := c.armClient.GetResourceWithExpandAPIVersionQuery(ctx, resourceID, expand, c.computeAPIVersion) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmssnic.get.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmssnic.get.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} - -// CreateOrUpdate creates or updates a network.Interface. -func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters network.Interface) *retry.Error { - mc := metrics.NewMetricContext("interfaces", "create_or_update", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "NicCreateOrUpdate") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("NicCreateOrUpdate", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.createOrUpdateInterface(ctx, resourceGroupName, networkInterfaceName, parameters) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// createOrUpdateInterface creates or updates a network.Interface. -func (c *Client) createOrUpdateInterface(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters network.Interface) *retry.Error { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - netInterfaceResourceType, - networkInterfaceName, - ) - decorators := []autorest.PrepareDecorator{} - if ptr.Deref(parameters.Etag, "") != "" { - decorators = append(decorators, autorest.WithHeader("If-Match", autorest.String(ptr.Deref(parameters.Etag, "")))) - } - - response, rerr := c.armClient.PutResource(ctx, resourceID, parameters, decorators...) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "nic.put.request", resourceID, rerr.Error()) - return rerr - } - - if response != nil && response.StatusCode != http.StatusNoContent { - _, rerr = c.createOrUpdateResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "nic.put.respond", resourceID, rerr.Error()) - return rerr - } - } - - return nil -} - -func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.Interface, *retry.Error) { - result := &network.Interface{} - err := autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return result, retry.GetError(resp, err) -} - -// Delete deletes a network interface by name. -func (c *Client) Delete(ctx context.Context, resourceGroupName string, networkInterfaceName string) *retry.Error { - mc := metrics.NewMetricContext("interfaces", "delete", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "NicDelete") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("NicDelete", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.deleteInterface(ctx, resourceGroupName, networkInterfaceName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// deleteInterface deletes a network interface by name. -func (c *Client) deleteInterface(ctx context.Context, resourceGroupName string, networkInterfaceName string) *retry.Error { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - netInterfaceResourceType, - networkInterfaceName, - ) - - return c.armClient.DeleteResource(ctx, resourceID) -} diff --git a/pkg/azureclients/interfaceclient/azure_interfaceclient_test.go b/pkg/azureclients/interfaceclient/azure_interfaceclient_test.go deleted file mode 100644 index 24c79f9467..0000000000 --- a/pkg/azureclients/interfaceclient/azure_interfaceclient_test.go +++ /dev/null @@ -1,280 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package interfaceclient - -import ( - "bytes" - "context" - "fmt" - "io" - "net/http" - "testing" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - "github.com/Azure/go-autorest/autorest" - "github.com/stretchr/testify/assert" - - "go.uber.org/mock/gomock" - - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient/mockarmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const testResourceID = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic1" - -func TestNew(t *testing.T) { - config := &azclients.ClientConfig{ - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - interfaceClient := New(config) - assert.Equal(t, "sub", interfaceClient.subscriptionID) - assert.NotEmpty(t, interfaceClient.rateLimiterReader) - assert.NotEmpty(t, interfaceClient.rateLimiterWriter) -} - -func TestNewAzureStack(t *testing.T) { - config := &azclients.ClientConfig{ - CloudName: "AZURESTACKCLOUD", - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - interfaceClient := New(config) - assert.Equal(t, "AZURESTACKCLOUD", interfaceClient.cloudName) - assert.Equal(t, "sub", interfaceClient.subscriptionID) -} - -func TestGetNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - nicClient := getTestInterfaceClient(armClient) - expected := network.Interface{Response: autorest.Response{}} - result, rerr := nicClient.Get(context.TODO(), "rg", "nic1", "") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestGetInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - nicClient := getTestInterfaceClient(armClient) - expected := network.Interface{Response: autorest.Response{}} - result, rerr := nicClient.Get(context.TODO(), "rg", "nic1", "") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestGetThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - nicClient := getTestInterfaceClient(armClient) - result, rerr := nicClient.Get(context.TODO(), "rg", "nic1", "") - assert.Empty(t, result) - assert.Equal(t, throttleErr, rerr) -} - -func TestGetVirtualMachineScaleSetNetworkInterface(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic1" - testInterface := getTestVMSSInterface("nic1") - networkInterface, err := testInterface.MarshalJSON() - assert.NoError(t, err) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(networkInterface)), - } - armClient := mockarmclient.NewMockInterface(ctrl) - expand := "" - armClient.EXPECT().GetResourceWithExpandAPIVersionQuery(gomock.Any(), resourceID, expand, AzureStackCloudAPIVersion).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - nicClient := getTestInterfaceClient(armClient) - nicClient.computeAPIVersion = AzureStackCloudAPIVersion - expected := getTestVMSSInterface("nic1") - expected.Response = autorest.Response{Response: response} - result, rerr := nicClient.GetVirtualMachineScaleSetNetworkInterface(context.TODO(), "rg", "vmss", "0", "nic1", expand) - assert.Equal(t, expected, result) - assert.Nil(t, rerr) - - response = &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - expand = "test" - armClient.EXPECT().GetResourceWithExpandAPIVersionQuery(gomock.Any(), resourceID, expand, AzureStackCloudAPIVersion).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - result, rerr = nicClient.GetVirtualMachineScaleSetNetworkInterface(context.TODO(), "rg", "vmss", "0", "nic1", expand) - assert.Empty(t, result) - assert.Equal(t, throttleErr, rerr) -} - -func TestCreateOrUpdate(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - testInterface := getTestInterface("nic1") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(testInterface.ID, ""), testInterface, gomock.Any()).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - nicClient := getTestInterfaceClient(armClient) - rerr := nicClient.CreateOrUpdate(context.TODO(), "rg", "nic1", testInterface) - assert.Nil(t, rerr) - - response = &http.Response{ - StatusCode: http.StatusNoContent, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - noContentErr := &retry.Error{ - HTTPStatusCode: http.StatusNoContent, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(testInterface.ID, ""), testInterface, gomock.Any()).Return(response, noContentErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - rerr = nicClient.CreateOrUpdate(context.TODO(), "rg", "nic1", testInterface) - assert.Equal(t, noContentErr, rerr) -} - -func TestDelete(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - r := getTestInterface("interface1") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().DeleteResource(gomock.Any(), ptr.Deref(r.ID, "")).Return(nil).Times(1) - - nicClient := getTestInterfaceClient(armClient) - rerr := nicClient.Delete(context.TODO(), "rg", "interface1") - assert.Nil(t, rerr) - - noContentErr := &retry.Error{ - HTTPStatusCode: http.StatusNoContent, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient.EXPECT().DeleteResource(gomock.Any(), ptr.Deref(r.ID, "")).Return(noContentErr).Times(1) - - rerr = nicClient.Delete(context.TODO(), "rg", "interface1") - assert.Equal(t, noContentErr, rerr) -} - -func getTestInterface(name string) network.Interface { - resourceID := fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/%s", name) - return network.Interface{ - ID: ptr.To(resourceID), - Name: ptr.To(name), - Location: ptr.To("eastus"), - } -} - -func getTestVMSSInterface(name string) network.Interface { - resourceID := fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/%s", name) - return network.Interface{ - ID: ptr.To(resourceID), - Location: ptr.To("eastus"), - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - EnableAcceleratedNetworking: ptr.To(true), - }, - } -} - -func getTestInterfaceClient(armClient armclient.Interface) *Client { - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(&azclients.RateLimitConfig{}) - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} diff --git a/pkg/azureclients/interfaceclient/doc.go b/pkg/azureclients/interfaceclient/doc.go deleted file mode 100644 index 3b071ae0bd..0000000000 --- a/pkg/azureclients/interfaceclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package interfaceclient implements the client for network interfaces. -package interfaceclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient" diff --git a/pkg/azureclients/interfaceclient/interface.go b/pkg/azureclients/interfaceclient/interface.go deleted file mode 100644 index 3d9ae10ed1..0000000000 --- a/pkg/azureclients/interfaceclient/interface.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package interfaceclient - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - // APIVersion is the API version for network. - APIVersion = "2022-07-01" - // AzureStackCloudAPIVersion is the API version for Azure Stack - AzureStackCloudAPIVersion = "2018-11-01" - - // ComputeAPIVersion is the API version for compute. It is required to get VMSS network interface. - ComputeAPIVersion = "2017-03-30" - // AzureStackComputeAPIVersion is the API version for compute for Azure Stack. It is required to get VMSS network interface. - AzureStackComputeAPIVersion = "2018-11-01" - - // AzureStackCloudName is the cloud name of Azure Stack - AzureStackCloudName = "AZURESTACKCLOUD" -) - -// Interface is the client interface for NetworkInterface. -// Don't forget to run "hack/update-mock-clients.sh" command to generate the mock client. -type Interface interface { - // Get gets a network.Interface. - Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, expand string) (result network.Interface, rerr *retry.Error) - - // GetVirtualMachineScaleSetNetworkInterface gets a network.Interface of VMSS VM. - GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (result network.Interface, rerr *retry.Error) - - // CreateOrUpdate creates or updates a network.Interface. - CreateOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters network.Interface) *retry.Error - - // Delete deletes a network interface by name. - Delete(ctx context.Context, resourceGroupName string, networkInterfaceName string) *retry.Error -} diff --git a/pkg/azureclients/interfaceclient/mockinterfaceclient/doc.go b/pkg/azureclients/interfaceclient/mockinterfaceclient/doc.go deleted file mode 100644 index 02de29dd01..0000000000 --- a/pkg/azureclients/interfaceclient/mockinterfaceclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package mockinterfaceclient implements the mock client for network interfaces. -package mockinterfaceclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" diff --git a/pkg/azureclients/interfaceclient/mockinterfaceclient/interface.go b/pkg/azureclients/interfaceclient/mockinterfaceclient/interface.go deleted file mode 100644 index c19b892049..0000000000 --- a/pkg/azureclients/interfaceclient/mockinterfaceclient/interface.go +++ /dev/null @@ -1,117 +0,0 @@ -// /* -// Copyright The Kubernetes Authors. -// -// 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 MockGen. DO NOT EDIT. -// Source: pkg/azureclients/interfaceclient/interface.go -// -// Generated by this command: -// -// mockgen -copyright_file=/home/runner/work/cloud-provider-azure/cloud-provider-azure/hack/boilerplate/boilerplate.generatego.txt -source=pkg/azureclients/interfaceclient/interface.go -package=mockinterfaceclient Interface -// - -// Package mockinterfaceclient is a generated GoMock package. -package mockinterfaceclient - -import ( - context "context" - reflect "reflect" - - network "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - gomock "go.uber.org/mock/gomock" - retry "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -// MockInterface is a mock of Interface interface. -type MockInterface struct { - ctrl *gomock.Controller - recorder *MockInterfaceMockRecorder -} - -// MockInterfaceMockRecorder is the mock recorder for MockInterface. -type MockInterfaceMockRecorder struct { - mock *MockInterface -} - -// NewMockInterface creates a new mock instance. -func NewMockInterface(ctrl *gomock.Controller) *MockInterface { - mock := &MockInterface{ctrl: ctrl} - mock.recorder = &MockInterfaceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { - return m.recorder -} - -// CreateOrUpdate mocks base method. -func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, networkInterfaceName string, parameters network.Interface) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrUpdate", ctx, resourceGroupName, networkInterfaceName, parameters) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// CreateOrUpdate indicates an expected call of CreateOrUpdate. -func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, networkInterfaceName, parameters any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdate", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, networkInterfaceName, parameters) -} - -// Delete mocks base method. -func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, networkInterfaceName string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Delete", ctx, resourceGroupName, networkInterfaceName) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// Delete indicates an expected call of Delete. -func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, networkInterfaceName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, networkInterfaceName) -} - -// Get mocks base method. -func (m *MockInterface) Get(ctx context.Context, resourceGroupName, networkInterfaceName, expand string) (network.Interface, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", ctx, resourceGroupName, networkInterfaceName, expand) - ret0, _ := ret[0].(network.Interface) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, networkInterfaceName, expand any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, networkInterfaceName, expand) -} - -// GetVirtualMachineScaleSetNetworkInterface mocks base method. -func (m *MockInterface) GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand string) (network.Interface, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetVirtualMachineScaleSetNetworkInterface", ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand) - ret0, _ := ret[0].(network.Interface) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// GetVirtualMachineScaleSetNetworkInterface indicates an expected call of GetVirtualMachineScaleSetNetworkInterface. -func (mr *MockInterfaceMockRecorder) GetVirtualMachineScaleSetNetworkInterface(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetVirtualMachineScaleSetNetworkInterface", reflect.TypeOf((*MockInterface)(nil).GetVirtualMachineScaleSetNetworkInterface), ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand) -} diff --git a/pkg/azureclients/loadbalancerclient/azure_loadbalancerclient.go b/pkg/azureclients/loadbalancerclient/azure_loadbalancerclient.go deleted file mode 100644 index e53bbf78fc..0000000000 --- a/pkg/azureclients/loadbalancerclient/azure_loadbalancerclient.go +++ /dev/null @@ -1,659 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package loadbalancerclient - -import ( - "context" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/klog/v2" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/metrics" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -var _ Interface = &Client{} - -const lbResourceType = "Microsoft.Network/loadBalancers" - -// Client implements LoadBalancer client Interface. -type Client struct { - armClient armclient.Interface - subscriptionID string - cloudName string - - // Rate limiting configures. - rateLimiterReader flowcontrol.RateLimiter - rateLimiterWriter flowcontrol.RateLimiter - - // ARM throttling configures. - RetryAfterReader time.Time - RetryAfterWriter time.Time -} - -type backendPoolsToBeMigrated struct { - BackendPoolNames []string `json:"pools"` -} - -// New creates a new LoadBalancer client with ratelimiting. -func New(config *azclients.ClientConfig) *Client { - baseURI := config.ResourceManagerEndpoint - authorizer := config.Authorizer - apiVersion := APIVersion - if strings.EqualFold(config.CloudName, AzureStackCloudName) && !config.DisableAzureStackCloud { - apiVersion = AzureStackCloudAPIVersion - } - armClient := armclient.New(authorizer, *config, baseURI, apiVersion) - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig) - - if azclients.RateLimitEnabled(config.RateLimitConfig) { - klog.V(2).Infof("Azure LoadBalancersClient (read ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPS, - config.RateLimitConfig.CloudProviderRateLimitBucket) - klog.V(2).Infof("Azure LoadBalancersClient (write ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPSWrite, - config.RateLimitConfig.CloudProviderRateLimitBucketWrite) - } - - client := &Client{ - armClient: armClient, - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - subscriptionID: config.SubscriptionID, - cloudName: config.CloudName, - } - - return client -} - -// Get gets a LoadBalancer. -func (c *Client) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, expand string) (network.LoadBalancer, *retry.Error) { - mc := metrics.NewMetricContext("load_balancers", "get", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return network.LoadBalancer{}, retry.GetRateLimitError(false, "LBGet") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("LBGet", "client throttled", c.RetryAfterReader) - return network.LoadBalancer{}, rerr - } - - result, rerr := c.getLB(ctx, resourceGroupName, loadBalancerName, expand) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// getLB gets a LoadBalancer. -func (c *Client) getLB(ctx context.Context, resourceGroupName string, loadBalancerName string, expand string) (network.LoadBalancer, *retry.Error) { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - lbResourceType, - loadBalancerName, - ) - result := network.LoadBalancer{} - - response, rerr := c.armClient.GetResourceWithExpandQuery(ctx, resourceID, expand) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "loadbalancer.get.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "loadbalancer.get.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} - -// List gets a list of LoadBalancer in the resource group. -func (c *Client) List(ctx context.Context, resourceGroupName string) ([]network.LoadBalancer, *retry.Error) { - mc := metrics.NewMetricContext("load_balancers", "list", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(false, "LBList") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("LBList", "client throttled", c.RetryAfterReader) - return nil, rerr - } - - result, rerr := c.listLB(ctx, resourceGroupName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// listLB gets a list of LoadBalancers in the resource group. -func (c *Client) listLB(ctx context.Context, resourceGroupName string) ([]network.LoadBalancer, *retry.Error) { - resourceID := armclient.GetResourceListID(c.subscriptionID, resourceGroupName, "Microsoft.Network/loadBalancers") - result := make([]network.LoadBalancer, 0) - page := &LoadBalancerListResultPage{} - page.fn = c.listNextResults - - resp, rerr := c.armClient.GetResource(ctx, resourceID) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "loadbalancer.list.request", resourceID, rerr.Error()) - return result, rerr - } - - var err error - page.lblr, err = c.listResponder(resp) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "loadbalancer.list.respond", resourceID, err) - return result, retry.GetError(resp, err) - } - - for { - result = append(result, page.Values()...) - - // Abort the loop when there's no nextLink in the response. - if ptr.Deref(page.Response().NextLink, "") == "" { - break - } - - if err = page.NextWithContext(ctx); err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "loadbalancer.list.next", resourceID, err) - return result, retry.GetError(page.Response().Response.Response, err) - } - } - - return result, nil -} - -// CreateOrUpdate creates or updates a LoadBalancer. -func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters network.LoadBalancer, etag string) *retry.Error { - mc := metrics.NewMetricContext("load_balancers", "create_or_update", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "LBCreateOrUpdate") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("LBCreateOrUpdate", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.createOrUpdateLB(ctx, resourceGroupName, loadBalancerName, parameters, etag) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// createOrUpdateLB creates or updates a LoadBalancer. -func (c *Client) createOrUpdateLB(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters network.LoadBalancer, etag string) *retry.Error { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - lbResourceType, - loadBalancerName, - ) - decorators := []autorest.PrepareDecorator{} - if etag != "" { - decorators = append(decorators, autorest.WithHeader("If-Match", autorest.String(etag))) - } - - response, rerr := c.armClient.PutResource(ctx, resourceID, parameters, decorators...) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "loadbalancer.put.request", resourceID, rerr.Error()) - return rerr - } - - if response != nil && response.StatusCode != http.StatusNoContent { - _, rerr = c.createOrUpdateResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "loadbalancer.put.respond", resourceID, rerr.Error()) - return rerr - } - } - - return nil -} - -func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.LoadBalancer, *retry.Error) { - result := &network.LoadBalancer{} - err := autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return result, retry.GetError(resp, err) -} - -// Delete deletes a LoadBalancer by name. -func (c *Client) Delete(ctx context.Context, resourceGroupName string, loadBalancerName string) *retry.Error { - mc := metrics.NewMetricContext("load_balancers", "delete", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "LBDelete") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("LBDelete", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.deleteLB(ctx, resourceGroupName, loadBalancerName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// deleteLB deletes a LoadBalancer by name. -func (c *Client) deleteLB(ctx context.Context, resourceGroupName string, loadBalancerName string) *retry.Error { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - lbResourceType, - loadBalancerName, - ) - - return c.armClient.DeleteResource(ctx, resourceID) -} - -func (c *Client) listResponder(resp *http.Response) (result network.LoadBalancerListResult, err error) { - err = autorest.Respond( - resp, - autorest.ByIgnoring(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return -} - -// loadBalancerListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (c *Client) loadBalancerListResultPreparer(ctx context.Context, lblr network.LoadBalancerListResult) (*http.Request, error) { - if lblr.NextLink == nil || len(ptr.Deref(lblr.NextLink, "")) < 1 { - return nil, nil - } - - decorators := []autorest.PrepareDecorator{ - autorest.WithBaseURL(ptr.Deref(lblr.NextLink, "")), - } - return c.armClient.PrepareGetRequest(ctx, decorators...) -} - -// listNextResults retrieves the next set of results, if any. -func (c *Client) listNextResults(ctx context.Context, lastResults network.LoadBalancerListResult) (result network.LoadBalancerListResult, err error) { - req, err := c.loadBalancerListResultPreparer(ctx, lastResults) - if err != nil { - return result, autorest.NewErrorWithError(err, "loadbalancerclient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - - resp, rerr := c.armClient.Send(ctx, req) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(rerr.Error(), "loadbalancerclient", "listNextResults", resp, "Failure sending next results request") - } - - result, err = c.listResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "loadbalancerclient", "listNextResults", resp, "Failure responding to next results request") - } - - return -} - -// LoadBalancerListResultPage contains a page of LoadBalancer values. -type LoadBalancerListResultPage struct { - fn func(context.Context, network.LoadBalancerListResult) (network.LoadBalancerListResult, error) - lblr network.LoadBalancerListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LoadBalancerListResultPage) NextWithContext(ctx context.Context) (err error) { - next, err := page.fn(ctx, page.lblr) - if err != nil { - return err - } - page.lblr = next - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LoadBalancerListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LoadBalancerListResultPage) NotDone() bool { - return !page.lblr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LoadBalancerListResultPage) Response() network.LoadBalancerListResult { - return page.lblr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LoadBalancerListResultPage) Values() []network.LoadBalancer { - if page.lblr.IsEmpty() { - return nil - } - return *page.lblr.Value -} - -// GetLBBackendPool gets a LoadBalancer backend pool. -func (c *Client) GetLBBackendPool(ctx context.Context, resourceGroupName string, loadBalancerName string, backendPoolName string, expand string) (network.BackendAddressPool, *retry.Error) { - mc := metrics.NewMetricContext("load_balancers", "get_backend_pool", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return network.BackendAddressPool{}, retry.GetRateLimitError(false, "LBGet") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("LBBackendPoolGet", "client throttled", c.RetryAfterReader) - return network.BackendAddressPool{}, rerr - } - - result, rerr := c.getLBBackendPool(ctx, resourceGroupName, loadBalancerName, backendPoolName, expand) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// getLBBackendPool gets a LoadBalancer backend pool. -func (c *Client) getLBBackendPool(ctx context.Context, resourceGroupName string, loadBalancerName string, backendPoolName string, expand string) (network.BackendAddressPool, *retry.Error) { - resourceID := armclient.GetChildResourceID( - c.subscriptionID, - resourceGroupName, - lbResourceType, - loadBalancerName, - "backendAddressPools", - backendPoolName, - ) - result := network.BackendAddressPool{} - - response, rerr := c.armClient.GetResourceWithExpandQuery(ctx, resourceID, expand) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "loadbalancer.backendpool.get.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "loadbalancer.backendpool.get.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} - -// CreateOrUpdateBackendPools creates or updates a LoadBalancer backend pool. -func (c *Client) CreateOrUpdateBackendPools(ctx context.Context, resourceGroupName string, loadBalancerName string, backendPoolName string, parameters network.BackendAddressPool, etag string) *retry.Error { - mc := metrics.NewMetricContext("load_balancers", "create_or_update_backend_pools", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "LBCreateOrUpdateBackendPools") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("LBCreateOrUpdateBackendPools", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.createOrUpdateLBBackendPool(ctx, resourceGroupName, loadBalancerName, backendPoolName, parameters, etag) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// createOrUpdateLBBackendPool creates or updates a LoadBalancer. -func (c *Client) createOrUpdateLBBackendPool(ctx context.Context, resourceGroupName string, loadBalancerName string, backendPoolName string, parameters network.BackendAddressPool, etag string) *retry.Error { - resourceID := armclient.GetChildResourceID( - c.subscriptionID, - resourceGroupName, - lbResourceType, - loadBalancerName, - "backendAddressPools", - backendPoolName, - ) - decorators := []autorest.PrepareDecorator{} - if etag != "" { - decorators = append(decorators, autorest.WithHeader("If-Match", autorest.String(etag))) - } - - response, rerr := c.armClient.PutResource(ctx, resourceID, parameters, decorators...) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "loadbalancer.backendpool.put.request", resourceID, rerr.Error()) - return rerr - } - - if response != nil && response.StatusCode != http.StatusNoContent { - _, rerr = c.createOrUpdateBackendPoolResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "loadbalancer.backendpool.put.respond", resourceID, rerr.Error()) - return rerr - } - } - - return nil -} - -// DeleteLBBackendPool deletes a LoadBalancer backend pool by name. -func (c *Client) DeleteLBBackendPool(ctx context.Context, resourceGroupName, loadBalancerName, backendPoolName string) *retry.Error { - mc := metrics.NewMetricContext("load_balancers", "delete_backend_pool", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "LBDeleteBackendPool") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("LBDeleteBackendPool", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.deleteLBBackendPool(ctx, resourceGroupName, loadBalancerName, backendPoolName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -func (c *Client) deleteLBBackendPool(ctx context.Context, resourceGroupName, loadBalancerName, backendPoolName string) *retry.Error { - resourceID := armclient.GetChildResourceID( - c.subscriptionID, - resourceGroupName, - lbResourceType, - loadBalancerName, - "backendAddressPools", - backendPoolName, - ) - return c.armClient.DeleteResource(ctx, resourceID) -} - -func (c *Client) createOrUpdateBackendPoolResponder(resp *http.Response) (*network.BackendAddressPool, *retry.Error) { - result := &network.BackendAddressPool{} - err := autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return result, retry.GetError(resp, err) -} - -// MigrateToIPBasedBackendPool migrates a NIC-based backend pool to IP-based. -func (c *Client) MigrateToIPBasedBackendPool(ctx context.Context, resourceGroupName string, loadBalancerName string, backendPoolNames []string) *retry.Error { - mc := metrics.NewMetricContext("load_balancers", "migrate_to_ip_based_backend_pool", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "LBMigrateToIPBasedBackendPool") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("LBMigrateToIPBasedBackendPool", "client throttled", c.RetryAfterWriter) - return rerr - } - - parameters := backendPoolsToBeMigrated{ - BackendPoolNames: backendPoolNames, - } - rerr := c.migrateToIPBasedBackendPool(ctx, resourceGroupName, loadBalancerName, parameters) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -func (c *Client) migrateToIPBasedBackendPool(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters backendPoolsToBeMigrated) *retry.Error { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - lbResourceType, - loadBalancerName, - ) - - response, rerr := c.armClient.PostResource(ctx, resourceID, "migrateToIpBased", parameters, map[string]interface{}{}) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "loadbalancerbackendpool.migrate.request", resourceID, rerr.Error()) - return rerr - } - - klog.Infof("Response: %v", response) - return nil -} diff --git a/pkg/azureclients/loadbalancerclient/azure_loadbalancerclient_test.go b/pkg/azureclients/loadbalancerclient/azure_loadbalancerclient_test.go deleted file mode 100644 index 5669d8e936..0000000000 --- a/pkg/azureclients/loadbalancerclient/azure_loadbalancerclient_test.go +++ /dev/null @@ -1,421 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package loadbalancerclient - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "testing" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - "github.com/Azure/go-autorest/autorest" - "github.com/stretchr/testify/assert" - - "go.uber.org/mock/gomock" - - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient/mockarmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - testResourceID = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb1" - testBackendPoolResourceID = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb1/backendAddressPools/lb1" - testResourcePrefix = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/loadBalancers" -) - -func TestNew(t *testing.T) { - config := &azclients.ClientConfig{ - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - lbClient := New(config) - assert.Equal(t, "sub", lbClient.subscriptionID) - assert.NotEmpty(t, lbClient.rateLimiterReader) - assert.NotEmpty(t, lbClient.rateLimiterWriter) -} - -func TestNewAzureStack(t *testing.T) { - config := &azclients.ClientConfig{ - CloudName: "AZURESTACKCLOUD", - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - lbClient := New(config) - assert.Equal(t, "AZURESTACKCLOUD", lbClient.cloudName) - assert.Equal(t, "sub", lbClient.subscriptionID) -} - -func TestGetNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - lbClient := getTestLoadBalancerClient(armClient) - expected := network.LoadBalancer{Response: autorest.Response{}} - result, rerr := lbClient.Get(context.TODO(), "rg", "lb1", "") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestGetInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - lbClient := getTestLoadBalancerClient(armClient) - expected := network.LoadBalancer{Response: autorest.Response{}} - result, rerr := lbClient.Get(context.TODO(), "rg", "lb1", "") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestGetThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - lbClient := getTestLoadBalancerClient(armClient) - result, rerr := lbClient.Get(context.TODO(), "rg", "lb1", "") - assert.Empty(t, result) - assert.Equal(t, throttleErr, rerr) -} - -func TestList(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - lbList := []network.LoadBalancer{getTestLoadBalancer("lb1"), getTestLoadBalancer("lb2"), getTestLoadBalancer("lb3")} - responseBody, err := json.Marshal(network.LoadBalancerListResult{Value: &lbList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - lbClient := getTestLoadBalancerClient(armClient) - result, rerr := lbClient.List(context.TODO(), "rg") - assert.Nil(t, rerr) - assert.Equal(t, 3, len(result)) - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - _, rerr = lbClient.List(context.TODO(), "rg") - assert.Equal(t, throttleErr, rerr) -} - -func TestListWithNextPage(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - lbList := []network.LoadBalancer{getTestLoadBalancer("lb1"), getTestLoadBalancer("lb2"), getTestLoadBalancer("lb3")} - partialResponse, err := json.Marshal(network.LoadBalancerListResult{Value: &lbList, NextLink: ptr.To("nextLink")}) - assert.NoError(t, err) - _, err = json.Marshal(network.LoadBalancerListResult{Value: &lbList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(partialResponse)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - lbClient := getTestLoadBalancerClient(armClient) - result, rerr := lbClient.List(context.TODO(), "rg") - assert.Nil(t, rerr) - assert.Equal(t, 3, len(result)) -} - -func TestListNextResultsMultiPages(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - prepareErr error - sendErr *retry.Error - }{ - { - prepareErr: nil, - sendErr: nil, - }, - { - prepareErr: fmt.Errorf("error"), - }, - { - sendErr: &retry.Error{RawError: fmt.Errorf("error")}, - }, - } - - lastResult := network.LoadBalancerListResult{ - NextLink: ptr.To("next"), - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - lbClient := getTestLoadBalancerClient(armClient) - result, err := lbClient.listNextResults(context.TODO(), lastResult) - if test.prepareErr != nil || test.sendErr != nil { - assert.Error(t, err) - } else { - assert.NoError(t, err) - } - if test.prepareErr != nil { - assert.Empty(t, result) - } else { - assert.NotEmpty(t, result) - } - } -} - -func TestCreateOrUpdate(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - lb := getTestLoadBalancer("lb1") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(lb.ID, ""), lb, gomock.Any()).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - lbClient := getTestLoadBalancerClient(armClient) - rerr := lbClient.CreateOrUpdate(context.TODO(), "rg", "lb1", lb, "") - assert.Nil(t, rerr) -} - -func TestCreateOrUpdateBackendPools(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - backendAddressPool := getTestBackendAddressPool("lb1", "backendAddressPool1") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(backendAddressPool.ID, ""), backendAddressPool, gomock.Any()).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - lbClient := getTestLoadBalancerClient(armClient) - rerr := lbClient.CreateOrUpdateBackendPools(context.TODO(), "rg", "lb1", "backendAddressPool1", backendAddressPool, "") - assert.Nil(t, rerr) -} - -func TestDelete(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - description string - armClientErr *retry.Error - expectedErr *retry.Error - }{ - { - description: "Delete should report the throttling error", - armClientErr: &retry.Error{HTTPStatusCode: http.StatusTooManyRequests}, - expectedErr: &retry.Error{HTTPStatusCode: http.StatusTooManyRequests}, - }, - { - description: "Delete should not report any error if there's no error from arm client", - }, - } - - lb := getTestLoadBalancer("lb1") - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().DeleteResource(gomock.Any(), ptr.Deref(lb.ID, "")).Return(test.armClientErr) - - lbClient := getTestLoadBalancerClient(armClient) - rerr := lbClient.Delete(context.TODO(), "rg", "lb1") - assert.Equal(t, test.expectedErr, rerr) - } -} - -func TestGetLBBackendPoolInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testBackendPoolResourceID, "").Return(response, nil) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - - lbClient := getTestLoadBalancerClient(armClient) - expected := network.BackendAddressPool{Response: autorest.Response{}} - result, rerr := lbClient.GetLBBackendPool(context.TODO(), "rg", "lb1", "lb1", "") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestGetLBBackendPoolThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testBackendPoolResourceID, "").Return(response, throttleErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - - lbClient := getTestLoadBalancerClient(armClient) - result, rerr := lbClient.GetLBBackendPool(context.TODO(), "rg", "lb1", "lb1", "") - assert.Empty(t, result) - assert.Equal(t, throttleErr, rerr) -} - -func TestMigrateToIpBasedBackendPools(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PostResource(gomock.Any(), testResourceID, "migrateToIpBased", backendPoolsToBeMigrated{BackendPoolNames: []string{"lb1"}}, gomock.Any()).Return(response, nil) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - - lbClient := getTestLoadBalancerClient(armClient) - rerr := lbClient.MigrateToIPBasedBackendPool(context.TODO(), "rg", "lb1", []string{"lb1"}) - assert.Nil(t, rerr) -} - -func getTestLoadBalancer(name string) network.LoadBalancer { - return network.LoadBalancer{ - ID: ptr.To(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/%s", name)), - Name: ptr.To(name), - Location: ptr.To("eastus"), - } -} - -func getTestBackendAddressPool(lbName, backendPoolName string) network.BackendAddressPool { - return network.BackendAddressPool{ - ID: ptr.To(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/%s/backendAddressPools/%s", lbName, backendPoolName)), - Name: ptr.To(backendPoolName), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - Location: ptr.To("eastus"), - }, - } -} - -func getTestLoadBalancerClient(armClient armclient.Interface) *Client { - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(&azclients.RateLimitConfig{}) - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} diff --git a/pkg/azureclients/loadbalancerclient/doc.go b/pkg/azureclients/loadbalancerclient/doc.go deleted file mode 100644 index a77686d311..0000000000 --- a/pkg/azureclients/loadbalancerclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package loadbalancerclient implements the client for LoadBalancer. -package loadbalancerclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient" diff --git a/pkg/azureclients/loadbalancerclient/interface.go b/pkg/azureclients/loadbalancerclient/interface.go deleted file mode 100644 index 6f0feb22f8..0000000000 --- a/pkg/azureclients/loadbalancerclient/interface.go +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package loadbalancerclient - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - // APIVersion is the API version for network. - APIVersion = "2022-07-01" - // AzureStackCloudAPIVersion is the API version for Azure Stack - AzureStackCloudAPIVersion = "2018-11-01" - // AzureStackCloudName is the cloud name of Azure Stack - AzureStackCloudName = "AZURESTACKCLOUD" -) - -// Interface is the client interface for LoadBalancer. -// Don't forget to run "hack/update-mock-clients.sh" command to generate the mock client. -type Interface interface { - // Get gets a LoadBalancer. - Get(ctx context.Context, resourceGroupName string, loadBalancerName string, expand string) (result network.LoadBalancer, rerr *retry.Error) - - // List gets a list of LoadBalancer in the resource group. - List(ctx context.Context, resourceGroupName string) (result []network.LoadBalancer, rerr *retry.Error) - - // CreateOrUpdate creates or updates a LoadBalancer. - CreateOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters network.LoadBalancer, etag string) *retry.Error - - // CreateOrUpdateBackendPools creates or updates loadbalancer's backend address pool. - CreateOrUpdateBackendPools(ctx context.Context, resourceGroupName string, loadBalancerName string, backendPoolName string, parameters network.BackendAddressPool, etag string) *retry.Error - - // Delete deletes a LoadBalancer by name. - Delete(ctx context.Context, resourceGroupName string, loadBalancerName string) *retry.Error - - // GetLBBackendPool gets a LoadBalancer backend pool. - GetLBBackendPool(ctx context.Context, resourceGroupName string, loadBalancerName string, backendPoolName string, expand string) (network.BackendAddressPool, *retry.Error) - - // DeleteLBBackendPool deletes a LoadBalancer backend pool by name. - DeleteLBBackendPool(ctx context.Context, resourceGroupName, loadBalancerName, backendPoolName string) *retry.Error - - // MigrateToIPBasedBackendPool migrates a NIC-based backend pool to IP-based. - MigrateToIPBasedBackendPool(ctx context.Context, resourceGroupName string, loadBalancerName string, backendPoolNames []string) *retry.Error -} diff --git a/pkg/azureclients/loadbalancerclient/mockloadbalancerclient/doc.go b/pkg/azureclients/loadbalancerclient/mockloadbalancerclient/doc.go deleted file mode 100644 index 424e5ffbbf..0000000000 --- a/pkg/azureclients/loadbalancerclient/mockloadbalancerclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package mockloadbalancerclient implements the mock client for LoadBalancer. -package mockloadbalancerclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient/mockloadbalancerclient" diff --git a/pkg/azureclients/loadbalancerclient/mockloadbalancerclient/interface.go b/pkg/azureclients/loadbalancerclient/mockloadbalancerclient/interface.go deleted file mode 100644 index e7b095994f..0000000000 --- a/pkg/azureclients/loadbalancerclient/mockloadbalancerclient/interface.go +++ /dev/null @@ -1,174 +0,0 @@ -// /* -// Copyright The Kubernetes Authors. -// -// 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 MockGen. DO NOT EDIT. -// Source: pkg/azureclients/loadbalancerclient/interface.go -// -// Generated by this command: -// -// mockgen -copyright_file=/home/runner/work/cloud-provider-azure/cloud-provider-azure/hack/boilerplate/boilerplate.generatego.txt -source=pkg/azureclients/loadbalancerclient/interface.go -package=mockloadbalancerclient Interface -// - -// Package mockloadbalancerclient is a generated GoMock package. -package mockloadbalancerclient - -import ( - context "context" - reflect "reflect" - - network "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - gomock "go.uber.org/mock/gomock" - retry "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -// MockInterface is a mock of Interface interface. -type MockInterface struct { - ctrl *gomock.Controller - recorder *MockInterfaceMockRecorder -} - -// MockInterfaceMockRecorder is the mock recorder for MockInterface. -type MockInterfaceMockRecorder struct { - mock *MockInterface -} - -// NewMockInterface creates a new mock instance. -func NewMockInterface(ctrl *gomock.Controller) *MockInterface { - mock := &MockInterface{ctrl: ctrl} - mock.recorder = &MockInterfaceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { - return m.recorder -} - -// CreateOrUpdate mocks base method. -func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, loadBalancerName string, parameters network.LoadBalancer, etag string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrUpdate", ctx, resourceGroupName, loadBalancerName, parameters, etag) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// CreateOrUpdate indicates an expected call of CreateOrUpdate. -func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, loadBalancerName, parameters, etag any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdate", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, loadBalancerName, parameters, etag) -} - -// CreateOrUpdateBackendPools mocks base method. -func (m *MockInterface) CreateOrUpdateBackendPools(ctx context.Context, resourceGroupName, loadBalancerName, backendPoolName string, parameters network.BackendAddressPool, etag string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrUpdateBackendPools", ctx, resourceGroupName, loadBalancerName, backendPoolName, parameters, etag) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// CreateOrUpdateBackendPools indicates an expected call of CreateOrUpdateBackendPools. -func (mr *MockInterfaceMockRecorder) CreateOrUpdateBackendPools(ctx, resourceGroupName, loadBalancerName, backendPoolName, parameters, etag any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdateBackendPools", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdateBackendPools), ctx, resourceGroupName, loadBalancerName, backendPoolName, parameters, etag) -} - -// Delete mocks base method. -func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, loadBalancerName string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Delete", ctx, resourceGroupName, loadBalancerName) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// Delete indicates an expected call of Delete. -func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, loadBalancerName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, loadBalancerName) -} - -// DeleteLBBackendPool mocks base method. -func (m *MockInterface) DeleteLBBackendPool(ctx context.Context, resourceGroupName, loadBalancerName, backendPoolName string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteLBBackendPool", ctx, resourceGroupName, loadBalancerName, backendPoolName) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// DeleteLBBackendPool indicates an expected call of DeleteLBBackendPool. -func (mr *MockInterfaceMockRecorder) DeleteLBBackendPool(ctx, resourceGroupName, loadBalancerName, backendPoolName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteLBBackendPool", reflect.TypeOf((*MockInterface)(nil).DeleteLBBackendPool), ctx, resourceGroupName, loadBalancerName, backendPoolName) -} - -// Get mocks base method. -func (m *MockInterface) Get(ctx context.Context, resourceGroupName, loadBalancerName, expand string) (network.LoadBalancer, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", ctx, resourceGroupName, loadBalancerName, expand) - ret0, _ := ret[0].(network.LoadBalancer) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, loadBalancerName, expand any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, loadBalancerName, expand) -} - -// GetLBBackendPool mocks base method. -func (m *MockInterface) GetLBBackendPool(ctx context.Context, resourceGroupName, loadBalancerName, backendPoolName, expand string) (network.BackendAddressPool, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetLBBackendPool", ctx, resourceGroupName, loadBalancerName, backendPoolName, expand) - ret0, _ := ret[0].(network.BackendAddressPool) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// GetLBBackendPool indicates an expected call of GetLBBackendPool. -func (mr *MockInterfaceMockRecorder) GetLBBackendPool(ctx, resourceGroupName, loadBalancerName, backendPoolName, expand any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLBBackendPool", reflect.TypeOf((*MockInterface)(nil).GetLBBackendPool), ctx, resourceGroupName, loadBalancerName, backendPoolName, expand) -} - -// List mocks base method. -func (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]network.LoadBalancer, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "List", ctx, resourceGroupName) - ret0, _ := ret[0].([]network.LoadBalancer) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// List indicates an expected call of List. -func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName) -} - -// MigrateToIPBasedBackendPool mocks base method. -func (m *MockInterface) MigrateToIPBasedBackendPool(ctx context.Context, resourceGroupName, loadBalancerName string, backendPoolNames []string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "MigrateToIPBasedBackendPool", ctx, resourceGroupName, loadBalancerName, backendPoolNames) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// MigrateToIPBasedBackendPool indicates an expected call of MigrateToIPBasedBackendPool. -func (mr *MockInterfaceMockRecorder) MigrateToIPBasedBackendPool(ctx, resourceGroupName, loadBalancerName, backendPoolNames any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MigrateToIPBasedBackendPool", reflect.TypeOf((*MockInterface)(nil).MigrateToIPBasedBackendPool), ctx, resourceGroupName, loadBalancerName, backendPoolNames) -} diff --git a/pkg/azureclients/publicipclient/azure_publicipclient.go b/pkg/azureclients/publicipclient/azure_publicipclient.go deleted file mode 100644 index c03924e64e..0000000000 --- a/pkg/azureclients/publicipclient/azure_publicipclient.go +++ /dev/null @@ -1,557 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package publicipclient - -import ( - "context" - "fmt" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/klog/v2" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/metrics" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -var _ Interface = &Client{} - -const publicIPResourceType = "Microsoft.Network/publicIPAddresses" - -// Client implements PublicIPAddress client Interface. -type Client struct { - armClient armclient.Interface - subscriptionID string - cloudName string - disableAzureStackCloud bool - - // Rate limiting configures. - rateLimiterReader flowcontrol.RateLimiter - rateLimiterWriter flowcontrol.RateLimiter - - // ARM throttling configures. - RetryAfterReader time.Time - RetryAfterWriter time.Time - - computeAPIVersion string -} - -// New creates a new PublicIPAddress client with ratelimiting. -func New(config *azclients.ClientConfig) *Client { - baseURI := config.ResourceManagerEndpoint - authorizer := config.Authorizer - apiVersion := APIVersion - if strings.EqualFold(config.CloudName, AzureStackCloudName) && !config.DisableAzureStackCloud { - apiVersion = AzureStackCloudAPIVersion - } - armClient := armclient.New(authorizer, *config, baseURI, apiVersion) - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig) - - if azclients.RateLimitEnabled(config.RateLimitConfig) { - klog.V(2).Infof("Azure PublicIPAddressesClient (read ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPS, - config.RateLimitConfig.CloudProviderRateLimitBucket) - klog.V(2).Infof("Azure PublicIPAddressesClient (write ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPSWrite, - config.RateLimitConfig.CloudProviderRateLimitBucketWrite) - } - - computeAPIVersion := ComputeAPIVersion - if strings.EqualFold(config.CloudName, AzureStackCloudName) && !config.DisableAzureStackCloud { - computeAPIVersion = AzureStackComputeAPIVersion - } - - client := &Client{ - armClient: armClient, - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - subscriptionID: config.SubscriptionID, - cloudName: config.CloudName, - disableAzureStackCloud: config.DisableAzureStackCloud, - computeAPIVersion: computeAPIVersion, - } - - return client -} - -// Get gets a PublicIPAddress. -func (c *Client) Get(ctx context.Context, resourceGroupName string, publicIPAddressName string, expand string) (network.PublicIPAddress, *retry.Error) { - mc := metrics.NewMetricContext("public_ip_addresses", "get", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return network.PublicIPAddress{}, retry.GetRateLimitError(false, "PublicIPGet") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("PublicIPGet", "client throttled", c.RetryAfterReader) - return network.PublicIPAddress{}, rerr - } - - result, rerr := c.getPublicIPAddress(ctx, resourceGroupName, publicIPAddressName, expand) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// getPublicIPAddress gets a PublicIPAddress. -func (c *Client) getPublicIPAddress(ctx context.Context, resourceGroupName string, publicIPAddressName string, expand string) (network.PublicIPAddress, *retry.Error) { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - publicIPResourceType, - publicIPAddressName, - ) - result := network.PublicIPAddress{} - - response, rerr := c.armClient.GetResourceWithExpandQuery(ctx, resourceID, expand) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "publicip.get.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "publicip.get.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} - -// GetVirtualMachineScaleSetPublicIPAddress gets a PublicIPAddress for VMSS VM. -func (c *Client) GetVirtualMachineScaleSetPublicIPAddress(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string, expand string) (network.PublicIPAddress, *retry.Error) { - mc := metrics.NewMetricContext("vmss_public_ip_addresses", "get", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return network.PublicIPAddress{}, retry.GetRateLimitError(false, "VMSSPublicIPGet") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSPublicIPGet", "client throttled", c.RetryAfterReader) - return network.PublicIPAddress{}, rerr - } - - result, rerr := c.getVMSSPublicIPAddress(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// getVMSSPublicIPAddress gets a PublicIPAddress for VMSS VM. -func (c *Client) getVMSSPublicIPAddress(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string, expand string) (network.PublicIPAddress, *retry.Error) { - resourceID := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachineScaleSets/%s/virtualMachines/%s/networkInterfaces/%s/ipconfigurations/%s/publicipaddresses/%s", - autorest.Encode("path", c.subscriptionID), - autorest.Encode("path", resourceGroupName), - autorest.Encode("path", virtualMachineScaleSetName), - autorest.Encode("path", virtualmachineIndex), - autorest.Encode("path", networkInterfaceName), - autorest.Encode("path", IPConfigurationName), - autorest.Encode("path", publicIPAddressName), - ) - - result := network.PublicIPAddress{} - response, rerr := c.armClient.GetResourceWithExpandAPIVersionQuery(ctx, resourceID, expand, c.computeAPIVersion) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmsspublicip.get.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmsspublicip.get.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} - -// List gets a list of PublicIPAddress in the resource group. -func (c *Client) List(ctx context.Context, resourceGroupName string) ([]network.PublicIPAddress, *retry.Error) { - mc := metrics.NewMetricContext("public_ip_addresses", "list", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(false, "PublicIPList") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("PublicIPList", "client throttled", c.RetryAfterReader) - return nil, rerr - } - - result, rerr := c.listPublicIPAddress(ctx, resourceGroupName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// listPublicIPAddress gets a list of PublicIPAddress in the resource group. -func (c *Client) listPublicIPAddress(ctx context.Context, resourceGroupName string) ([]network.PublicIPAddress, *retry.Error) { - resourceID := armclient.GetResourceListID(c.subscriptionID, resourceGroupName, publicIPResourceType) - result := make([]network.PublicIPAddress, 0) - page := &PublicIPAddressListResultPage{} - page.fn = c.listNextResults - - resp, rerr := c.armClient.GetResource(ctx, resourceID) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "publicip.list.request", resourceID, rerr.Error()) - return result, rerr - } - - var err error - page.pialr, err = c.listResponder(resp) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "publicip.list.respond", resourceID, err) - return result, retry.GetError(resp, err) - } - - for { - result = append(result, page.Values()...) - - // Abort the loop when there's no nextLink in the response. - if ptr.Deref(page.Response().NextLink, "") == "" { - break - } - - if err = page.NextWithContext(ctx); err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "publicip.list.next", resourceID, err) - return result, retry.GetError(page.Response().Response.Response, err) - } - } - - return result, nil -} - -// CreateOrUpdate creates or updates a PublicIPAddress. -func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters network.PublicIPAddress) *retry.Error { - mc := metrics.NewMetricContext("public_ip_addresses", "create_or_update", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "PublicIPCreateOrUpdate") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("PublicIPCreateOrUpdate", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.createOrUpdatePublicIP(ctx, resourceGroupName, publicIPAddressName, parameters) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// createOrUpdatePublicIP creates or updates a PublicIPAddress. -func (c *Client) createOrUpdatePublicIP(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters network.PublicIPAddress) *retry.Error { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - publicIPResourceType, - publicIPAddressName, - ) - - response, rerr := c.armClient.PutResource(ctx, resourceID, parameters) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "publicip.put.request", resourceID, rerr.Error()) - return rerr - } - - if response != nil && response.StatusCode != http.StatusNoContent { - _, rerr = c.createOrUpdateResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "publicip.put.respond", resourceID, rerr.Error()) - return rerr - } - } - - return nil -} - -func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.PublicIPAddress, *retry.Error) { - result := &network.PublicIPAddress{} - err := autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return result, retry.GetError(resp, err) -} - -// Delete deletes a PublicIPAddress by name. -func (c *Client) Delete(ctx context.Context, resourceGroupName string, publicIPAddressName string) *retry.Error { - mc := metrics.NewMetricContext("public_ip_addresses", "delete", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "PublicIPDelete") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("PublicIPDelete", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.deletePublicIP(ctx, resourceGroupName, publicIPAddressName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// deletePublicIP deletes a PublicIPAddress by name. -func (c *Client) deletePublicIP(ctx context.Context, resourceGroupName string, publicIPAddressName string) *retry.Error { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - publicIPResourceType, - publicIPAddressName, - ) - - return c.armClient.DeleteResource(ctx, resourceID) -} - -func (c *Client) listResponder(resp *http.Response) (result network.PublicIPAddressListResult, err error) { - err = autorest.Respond( - resp, - autorest.ByIgnoring(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return -} - -// publicIPAddressListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (c *Client) publicIPAddressListResultPreparer(ctx context.Context, lr network.PublicIPAddressListResult) (*http.Request, error) { - if lr.NextLink == nil || len(ptr.Deref(lr.NextLink, "")) < 1 { - return nil, nil - } - - decorators := []autorest.PrepareDecorator{ - autorest.WithBaseURL(ptr.Deref(lr.NextLink, "")), - } - return c.armClient.PrepareGetRequest(ctx, decorators...) -} - -// listNextResults retrieves the next set of results, if any. -func (c *Client) listNextResults(ctx context.Context, lastResults network.PublicIPAddressListResult) (result network.PublicIPAddressListResult, err error) { - req, err := c.publicIPAddressListResultPreparer(ctx, lastResults) - if err != nil { - return result, autorest.NewErrorWithError(err, "publicipclient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - - resp, rerr := c.armClient.Send(ctx, req) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(rerr.Error(), "publicipclient", "listNextResults", resp, "Failure sending next results request") - } - - result, err = c.listResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "publicipclient", "listNextResults", resp, "Failure responding to next results request") - } - - return -} - -// PublicIPAddressListResultPage contains a page of PublicIPAddress values. -type PublicIPAddressListResultPage struct { - fn func(context.Context, network.PublicIPAddressListResult) (network.PublicIPAddressListResult, error) - pialr network.PublicIPAddressListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PublicIPAddressListResultPage) NextWithContext(ctx context.Context) (err error) { - next, err := page.fn(ctx, page.pialr) - if err != nil { - return err - } - page.pialr = next - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PublicIPAddressListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PublicIPAddressListResultPage) NotDone() bool { - return !page.pialr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PublicIPAddressListResultPage) Response() network.PublicIPAddressListResult { - return page.pialr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PublicIPAddressListResultPage) Values() []network.PublicIPAddress { - if page.pialr.IsEmpty() { - return nil - } - return *page.pialr.Value -} - -// ListAll gets all of PublicIPAddress in the subscription. -func (c *Client) ListAll(ctx context.Context) ([]network.PublicIPAddress, *retry.Error) { - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - return nil, retry.GetRateLimitError(false, "PublicIPListAll") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - rerr := retry.GetThrottlingError("PublicIPListAll", "client throttled", c.RetryAfterReader) - return nil, rerr - } - - result, rerr := c.listAllPublicIPAddress(ctx) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// listAllPublicIPAddress gets all of PublicIPAddress in the subscription. -func (c *Client) listAllPublicIPAddress(ctx context.Context) ([]network.PublicIPAddress, *retry.Error) { - resourceID := armclient.GetProviderResourceID(c.subscriptionID, publicIPResourceType) - result := make([]network.PublicIPAddress, 0) - page := &PublicIPAddressListResultPage{} - page.fn = c.listNextResults - - resp, rerr := c.armClient.GetResource(ctx, resourceID) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "publicip.listall.request", resourceID, rerr.Error()) - return result, rerr - } - - var err error - page.pialr, err = c.listResponder(resp) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "publicip.listall.respond", resourceID, err) - return result, retry.GetError(resp, err) - } - - for { - result = append(result, page.Values()...) - - // Abort the loop when there's no nextLink in the response. - if ptr.Deref(page.Response().NextLink, "") == "" { - break - } - - if err = page.NextWithContext(ctx); err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "publicip.listall.next", resourceID, err) - return result, retry.GetError(page.Response().Response.Response, err) - } - } - - return result, nil -} diff --git a/pkg/azureclients/publicipclient/azure_publicipclient_test.go b/pkg/azureclients/publicipclient/azure_publicipclient_test.go deleted file mode 100644 index 08965cceaa..0000000000 --- a/pkg/azureclients/publicipclient/azure_publicipclient_test.go +++ /dev/null @@ -1,915 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package publicipclient - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "testing" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - "github.com/Azure/go-autorest/autorest" - "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient/mockarmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - testResourceID = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pip1" - testVMSSResourceID = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic/ipconfigurations/ipConfig/publicipaddresses/pip1" - resourceIDPrefix = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses" - subResourceIDPrefix = "/subscriptions/subscriptionID/providers/Microsoft.Network/publicIPAddresses" -) - -func TestNew(t *testing.T) { - config := &azclients.ClientConfig{ - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - pipClient := New(config) - assert.Equal(t, "sub", pipClient.subscriptionID) - assert.NotEmpty(t, pipClient.rateLimiterReader) - assert.NotEmpty(t, pipClient.rateLimiterWriter) -} - -func TestNewAzureStack(t *testing.T) { - config := &azclients.ClientConfig{ - CloudName: "AZURESTACKCLOUD", - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - pipClient := New(config) - assert.Equal(t, "AZURESTACKCLOUD", pipClient.cloudName) - assert.Equal(t, "sub", pipClient.subscriptionID) -} - -func TestGet(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - expected := network.PublicIPAddress{Response: autorest.Response{Response: response}} - pipClient := getTestPublicIPAddressClient(armClient) - result, rerr := pipClient.Get(context.TODO(), "rg", "pip1", "") - assert.Equal(t, expected, result) - assert.Nil(t, rerr) -} - -func TestGetNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - pipGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "PublicIPGet"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - pipClient := getTestPublicIPAddressClientWithNeverRateLimiter(armClient) - expected := network.PublicIPAddress{} - result, rerr := pipClient.Get(context.TODO(), "rg", "pip1", "") - assert.Equal(t, expected, result) - assert.Equal(t, pipGetErr, rerr) -} - -func TestGetRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - pipGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "PublicIPGet", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - pipClient := getTestPublicIPAddressClientWithRetryAfterReader(armClient) - expected := network.PublicIPAddress{} - result, rerr := pipClient.Get(context.TODO(), "rg", "pip1", "") - assert.Equal(t, expected, result) - assert.Equal(t, pipGetErr, rerr) -} - -func TestGetNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - expected := network.PublicIPAddress{Response: autorest.Response{}} - result, rerr := pipClient.Get(context.TODO(), "rg", "pip1", "") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestGetInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - expected := network.PublicIPAddress{Response: autorest.Response{}} - result, rerr := pipClient.Get(context.TODO(), "rg", "pip1", "") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestGetThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - result, rerr := pipClient.Get(context.TODO(), "rg", "pip1", "") - assert.Empty(t, result) - assert.Equal(t, throttleErr, rerr) -} - -func TestGetVMSSPublicIPAddress(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - testPip := network.PublicIPAddress{ - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("10.10.10.10"), - }, - } - pip, err := testPip.MarshalJSON() - assert.NoError(t, err) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(pip)), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandAPIVersionQuery(gomock.Any(), testVMSSResourceID, "", AzureStackCloudAPIVersion).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - pipClient.computeAPIVersion = AzureStackCloudAPIVersion - expected := network.PublicIPAddress{ - Response: autorest.Response{Response: response}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("10.10.10.10"), - }, - } - result, rerr := pipClient.GetVirtualMachineScaleSetPublicIPAddress(context.TODO(), "rg", "vmss", "0", "nic", "ipConfig", "pip1", "") - assert.Equal(t, expected, result) - assert.Nil(t, rerr) -} - -func TestGetVMSSPublicIPAddressNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - pipGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "VMSSPublicIPGet"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - pipClient := getTestPublicIPAddressClientWithNeverRateLimiter(armClient) - expected := network.PublicIPAddress{} - result, rerr := pipClient.GetVirtualMachineScaleSetPublicIPAddress(context.TODO(), "rg", "vmss", "0", "nic", "ipConfig", "pip1", "") - assert.Equal(t, expected, result) - assert.Equal(t, pipGetErr, rerr) -} - -func TestGetVMSSPublicIPAddressRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - pipGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMSSPublicIPGet", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - pipClient := getTestPublicIPAddressClientWithRetryAfterReader(armClient) - expected := network.PublicIPAddress{} - result, rerr := pipClient.GetVirtualMachineScaleSetPublicIPAddress(context.TODO(), "rg", "vmss", "0", "nic", "ipConfig", "pip1", "") - assert.Equal(t, expected, result) - assert.Equal(t, pipGetErr, rerr) -} - -func TestGetVMSSPublicIPAddressNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandAPIVersionQuery(gomock.Any(), testVMSSResourceID, "", AzureStackCloudAPIVersion).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - pipClient.computeAPIVersion = AzureStackCloudAPIVersion - expected := network.PublicIPAddress{Response: autorest.Response{}} - result, rerr := pipClient.GetVirtualMachineScaleSetPublicIPAddress(context.TODO(), "rg", "vmss", "0", "nic", "ipConfig", "pip1", "") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestGetVMSSPublicIPAddressInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandAPIVersionQuery(gomock.Any(), testVMSSResourceID, "", AzureStackCloudAPIVersion).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - pipClient.computeAPIVersion = AzureStackCloudAPIVersion - expected := network.PublicIPAddress{Response: autorest.Response{}} - result, rerr := pipClient.GetVirtualMachineScaleSetPublicIPAddress(context.TODO(), "rg", "vmss", "0", "nic", "ipConfig", "pip1", "") - - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestGetVMSSPublicIPAddressThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandAPIVersionQuery(gomock.Any(), testVMSSResourceID, "", AzureStackCloudAPIVersion).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - pipClient.computeAPIVersion = AzureStackCloudAPIVersion - result, rerr := pipClient.GetVirtualMachineScaleSetPublicIPAddress(context.TODO(), "rg", "vmss", "0", "nic", "ipConfig", "pip1", "") - assert.Empty(t, result) - assert.Equal(t, throttleErr, rerr) -} - -func TestList(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - pipList := []network.PublicIPAddress{getTestPublicIPAddress("pip1"), getTestPublicIPAddress("pip2"), getTestPublicIPAddress("pip3")} - responseBody, err := json.Marshal(network.PublicIPAddressListResult{Value: &pipList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), resourceIDPrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - result, rerr := pipClient.List(context.TODO(), "rg") - assert.Nil(t, rerr) - assert.Equal(t, 3, len(result)) -} - -func TestListNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), resourceIDPrefix).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - expected := []network.PublicIPAddress{} - result, rerr := pipClient.List(context.TODO(), "rg") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestListInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), resourceIDPrefix).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - expected := []network.PublicIPAddress{} - result, rerr := pipClient.List(context.TODO(), "rg") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestListThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient.EXPECT().GetResource(gomock.Any(), resourceIDPrefix).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - pipClient := getTestPublicIPAddressClient(armClient) - result, rerr := pipClient.List(context.TODO(), "rg") - assert.Empty(t, result) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestListWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - pipList := []network.PublicIPAddress{getTestPublicIPAddress("pip1"), getTestPublicIPAddress("pip2"), getTestPublicIPAddress("pip3")} - responseBody, err := json.Marshal(network.PublicIPAddressListResult{Value: &pipList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), resourceIDPrefix).Return( - &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - pipClient := getTestPublicIPAddressClient(armClient) - result, rerr := pipClient.List(context.TODO(), "rg") - assert.NotNil(t, rerr) - assert.Equal(t, 0, len(result)) -} - -func TestListWithNextPage(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - pipList := []network.PublicIPAddress{getTestPublicIPAddress("pip1"), getTestPublicIPAddress("pip2"), getTestPublicIPAddress("pip3")} - partialResponse, err := json.Marshal(network.PublicIPAddressListResult{Value: &pipList, NextLink: ptr.To("nextLink")}) - assert.NoError(t, err) - pagedResponse, err := json.Marshal(network.PublicIPAddressListResult{Value: &pipList}) - assert.NoError(t, err) - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(&http.Request{}, nil) - armClient.EXPECT().Send(gomock.Any(), gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(pagedResponse)), - }, nil) - armClient.EXPECT().GetResource(gomock.Any(), resourceIDPrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(partialResponse)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(2) - pipClient := getTestPublicIPAddressClient(armClient) - result, rerr := pipClient.List(context.TODO(), "rg") - assert.Nil(t, rerr) - assert.Equal(t, 6, len(result)) -} - -func TestListNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - pipListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "PublicIPList"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - pipClient := getTestPublicIPAddressClientWithNeverRateLimiter(armClient) - result, rerr := pipClient.List(context.TODO(), "rg") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, pipListErr, rerr) -} - -func TestListRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - pipListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "PublicIPList", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - pipClient := getTestPublicIPAddressClientWithRetryAfterReader(armClient) - result, rerr := pipClient.List(context.TODO(), "rg") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, pipListErr, rerr) -} - -func TestListNextResultsMultiPages(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - prepareErr error - sendErr *retry.Error - }{ - { - prepareErr: nil, - sendErr: nil, - }, - { - prepareErr: fmt.Errorf("error"), - }, - { - sendErr: &retry.Error{RawError: fmt.Errorf("error")}, - }, - } - - lastResult := network.PublicIPAddressListResult{ - NextLink: ptr.To("next"), - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - pipClient := getTestPublicIPAddressClient(armClient) - result, err := pipClient.listNextResults(context.TODO(), lastResult) - if test.prepareErr != nil || test.sendErr != nil { - assert.Error(t, err) - } else { - assert.NoError(t, err) - } - if test.prepareErr != nil { - assert.Empty(t, result) - } else { - assert.NotEmpty(t, result) - } - } -} - -func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - test := struct { - prepareErr error - sendErr *retry.Error - }{ - prepareErr: nil, - sendErr: nil, - } - - lastResult := network.PublicIPAddressListResult{ - NextLink: ptr.To("next"), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewBuffer([]byte(`{"foo":"bar"}`))), - } - expected := network.PublicIPAddressListResult{} - expected.Response = autorest.Response{Response: response} - pipClient := getTestPublicIPAddressClient(armClient) - result, err := pipClient.listNextResults(context.TODO(), lastResult) - assert.Error(t, err) - assert.Equal(t, expected, result) -} - -func TestCreateOrUpdate(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - pip := getTestPublicIPAddress("pip1") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(pip.ID, ""), pip).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - rerr := pipClient.CreateOrUpdate(context.TODO(), "rg", "pip1", pip) - assert.Nil(t, rerr) -} - -func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - pip := getTestPublicIPAddress("pip1") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(pip.ID, ""), pip).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - rerr := pipClient.CreateOrUpdate(context.TODO(), "rg", "pip1", pip) - assert.NotNil(t, rerr) -} - -func TestCreateOrUpdateNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - pipCreateOrUpdateErr := retry.GetRateLimitError(true, "PublicIPCreateOrUpdate") - - armClient := mockarmclient.NewMockInterface(ctrl) - pipClient := getTestPublicIPAddressClientWithNeverRateLimiter(armClient) - pip := getTestPublicIPAddress("pip1") - rerr := pipClient.CreateOrUpdate(context.TODO(), "rg", "pip1", pip) - assert.NotNil(t, rerr) - assert.Equal(t, pipCreateOrUpdateErr, rerr) -} - -func TestCreateOrUpdateRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - pipCreateOrUpdateErr := retry.GetThrottlingError("PublicIPCreateOrUpdate", "client throttled", getFutureTime()) - - pip := getTestPublicIPAddress("pip1") - armClient := mockarmclient.NewMockInterface(ctrl) - pipClient := getTestPublicIPAddressClientWithRetryAfterReader(armClient) - rerr := pipClient.CreateOrUpdate(context.TODO(), "rg", "pip1", pip) - assert.NotNil(t, rerr) - assert.Equal(t, pipCreateOrUpdateErr, rerr) -} - -func TestCreateOrUpdateThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - pip := getTestPublicIPAddress("pip1") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(pip.ID, ""), pip).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - rerr := pipClient.CreateOrUpdate(context.TODO(), "rg", "pip1", pip) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestDelete(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - pip := getTestPublicIPAddress("pip1") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().DeleteResource(gomock.Any(), ptr.Deref(pip.ID, "")).Return(nil).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - rerr := pipClient.Delete(context.TODO(), "rg", "pip1") - assert.Nil(t, rerr) -} - -func TestDeleteNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - pipDeleteErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "write", "PublicIPDelete"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - pipClient := getTestPublicIPAddressClientWithNeverRateLimiter(armClient) - rerr := pipClient.Delete(context.TODO(), "rg", "pip1") - assert.NotNil(t, rerr) - assert.Equal(t, pipDeleteErr, rerr) -} - -func TestDeleteRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - pipDeleteErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "PublicIPDelete", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - pipClient := getTestPublicIPAddressClientWithRetryAfterReader(armClient) - rerr := pipClient.Delete(context.TODO(), "rg", "pip1") - assert.NotNil(t, rerr) - assert.Equal(t, pipDeleteErr, rerr) -} - -func TestDeleteThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - pip := getTestPublicIPAddress("pip1") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().DeleteResource(gomock.Any(), ptr.Deref(pip.ID, "")).Return(throttleErr).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - rerr := pipClient.Delete(context.TODO(), "rg", "pip1") - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -// 2065-01-24 05:20:00 +0000 UTC -func getFutureTime() time.Time { - return time.Unix(3000000000, 0) -} - -func getTestPublicIPAddress(name string) network.PublicIPAddress { - return network.PublicIPAddress{ - ID: ptr.To(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/%s", name)), - Name: ptr.To(name), - Location: ptr.To("eastus"), - } -} - -func getTestPublicIPAddressClient(armClient armclient.Interface) *Client { - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(&azclients.RateLimitConfig{}) - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestPublicIPAddressClientWithNeverRateLimiter(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeNeverRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeNeverRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestPublicIPAddressClientWithRetryAfterReader(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeAlwaysRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeAlwaysRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - RetryAfterReader: getFutureTime(), - RetryAfterWriter: getFutureTime(), - } -} - -func TestListAll(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - pipList := []network.PublicIPAddress{getTestPublicIPAddress("pip1"), getTestPublicIPAddress("pip2"), getTestPublicIPAddress("pip3")} - responseBody, err := json.Marshal(network.PublicIPAddressListResult{Value: &pipList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), subResourceIDPrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - result, rerr := pipClient.ListAll(context.TODO()) - assert.Nil(t, rerr) - assert.Equal(t, 3, len(result)) -} - -func TestListAllNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), subResourceIDPrefix).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - expected := []network.PublicIPAddress{} - result, rerr := pipClient.ListAll(context.TODO()) - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestListAllInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), subResourceIDPrefix).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - pipClient := getTestPublicIPAddressClient(armClient) - expected := []network.PublicIPAddress{} - result, rerr := pipClient.ListAll(context.TODO()) - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestListAllThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient.EXPECT().GetResource(gomock.Any(), subResourceIDPrefix).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - pipClient := getTestPublicIPAddressClient(armClient) - result, rerr := pipClient.ListAll(context.TODO()) - assert.Empty(t, result) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestListAllWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - pipList := []network.PublicIPAddress{getTestPublicIPAddress("pip1"), getTestPublicIPAddress("pip2"), getTestPublicIPAddress("pip3")} - responseBody, err := json.Marshal(network.PublicIPAddressListResult{Value: &pipList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), subResourceIDPrefix).Return( - &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - pipClient := getTestPublicIPAddressClient(armClient) - result, rerr := pipClient.ListAll(context.TODO()) - assert.NotNil(t, rerr) - assert.Equal(t, 0, len(result)) -} diff --git a/pkg/azureclients/publicipclient/doc.go b/pkg/azureclients/publicipclient/doc.go deleted file mode 100644 index 1576dc7ece..0000000000 --- a/pkg/azureclients/publicipclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package publicipclient implements the client for PublicIPAddress. -package publicipclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient" diff --git a/pkg/azureclients/publicipclient/interface.go b/pkg/azureclients/publicipclient/interface.go deleted file mode 100644 index 241216151c..0000000000 --- a/pkg/azureclients/publicipclient/interface.go +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package publicipclient - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - // APIVersion is the API version for network. - APIVersion = "2022-07-01" - // AzureStackCloudAPIVersion is the API version for Azure Stack - AzureStackCloudAPIVersion = "2018-11-01" - - // ComputeAPIVersion is the API version for compute. It is required to get VMSS public IP. - ComputeAPIVersion = "2017-03-30" - // AzureStackComputeAPIVersion is the API version for compute for Azure Stack. It is required to get VMSS network interface. - AzureStackComputeAPIVersion = "2018-11-01" - - // AzureStackCloudName is the cloud name of Azure Stack - AzureStackCloudName = "AZURESTACKCLOUD" -) - -// Interface is the client interface for PublicIPAddress. -// Don't forget to run "hack/update-mock-clients.sh" command to generate the mock client. -type Interface interface { - // Get gets a PublicIPAddress. - Get(ctx context.Context, resourceGroupName string, publicIPAddressName string, expand string) (result network.PublicIPAddress, rerr *retry.Error) - - // GetVirtualMachineScaleSetPublicIPAddress gets a PublicIPAddress for VMSS VM. - GetVirtualMachineScaleSetPublicIPAddress(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string, expand string) (result network.PublicIPAddress, rerr *retry.Error) - - // List gets a list of PublicIPAddress in the resource group. - List(ctx context.Context, resourceGroupName string) (result []network.PublicIPAddress, rerr *retry.Error) - - // ListAll gets all of PublicIPAddress in the subscription. - ListAll(ctx context.Context) (result []network.PublicIPAddress, rerr *retry.Error) - - // CreateOrUpdate creates or updates a PublicIPAddress. - CreateOrUpdate(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters network.PublicIPAddress) *retry.Error - - // Delete deletes a PublicIPAddress by name. - Delete(ctx context.Context, resourceGroupName string, publicIPAddressName string) *retry.Error -} diff --git a/pkg/azureclients/publicipclient/mockpublicipclient/doc.go b/pkg/azureclients/publicipclient/mockpublicipclient/doc.go deleted file mode 100644 index 4d30b17fdd..0000000000 --- a/pkg/azureclients/publicipclient/mockpublicipclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package mockpublicipclient implements the mock client for PublicIPAddress. -package mockpublicipclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" diff --git a/pkg/azureclients/publicipclient/mockpublicipclient/interface.go b/pkg/azureclients/publicipclient/mockpublicipclient/interface.go deleted file mode 100644 index e2ecaf4575..0000000000 --- a/pkg/azureclients/publicipclient/mockpublicipclient/interface.go +++ /dev/null @@ -1,147 +0,0 @@ -// /* -// Copyright The Kubernetes Authors. -// -// 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 MockGen. DO NOT EDIT. -// Source: pkg/azureclients/publicipclient/interface.go -// -// Generated by this command: -// -// mockgen -copyright_file=/home/runner/work/cloud-provider-azure/cloud-provider-azure/hack/boilerplate/boilerplate.generatego.txt -source=pkg/azureclients/publicipclient/interface.go -package=mockpublicipclient Interface -// - -// Package mockpublicipclient is a generated GoMock package. -package mockpublicipclient - -import ( - context "context" - reflect "reflect" - - network "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - gomock "go.uber.org/mock/gomock" - retry "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -// MockInterface is a mock of Interface interface. -type MockInterface struct { - ctrl *gomock.Controller - recorder *MockInterfaceMockRecorder -} - -// MockInterfaceMockRecorder is the mock recorder for MockInterface. -type MockInterfaceMockRecorder struct { - mock *MockInterface -} - -// NewMockInterface creates a new mock instance. -func NewMockInterface(ctrl *gomock.Controller) *MockInterface { - mock := &MockInterface{ctrl: ctrl} - mock.recorder = &MockInterfaceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { - return m.recorder -} - -// CreateOrUpdate mocks base method. -func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, publicIPAddressName string, parameters network.PublicIPAddress) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrUpdate", ctx, resourceGroupName, publicIPAddressName, parameters) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// CreateOrUpdate indicates an expected call of CreateOrUpdate. -func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, publicIPAddressName, parameters any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdate", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, publicIPAddressName, parameters) -} - -// Delete mocks base method. -func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, publicIPAddressName string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Delete", ctx, resourceGroupName, publicIPAddressName) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// Delete indicates an expected call of Delete. -func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, publicIPAddressName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, publicIPAddressName) -} - -// Get mocks base method. -func (m *MockInterface) Get(ctx context.Context, resourceGroupName, publicIPAddressName, expand string) (network.PublicIPAddress, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", ctx, resourceGroupName, publicIPAddressName, expand) - ret0, _ := ret[0].(network.PublicIPAddress) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, publicIPAddressName, expand any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, publicIPAddressName, expand) -} - -// GetVirtualMachineScaleSetPublicIPAddress mocks base method. -func (m *MockInterface) GetVirtualMachineScaleSetPublicIPAddress(ctx context.Context, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand string) (network.PublicIPAddress, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetVirtualMachineScaleSetPublicIPAddress", ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand) - ret0, _ := ret[0].(network.PublicIPAddress) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// GetVirtualMachineScaleSetPublicIPAddress indicates an expected call of GetVirtualMachineScaleSetPublicIPAddress. -func (mr *MockInterfaceMockRecorder) GetVirtualMachineScaleSetPublicIPAddress(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetVirtualMachineScaleSetPublicIPAddress", reflect.TypeOf((*MockInterface)(nil).GetVirtualMachineScaleSetPublicIPAddress), ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand) -} - -// List mocks base method. -func (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]network.PublicIPAddress, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "List", ctx, resourceGroupName) - ret0, _ := ret[0].([]network.PublicIPAddress) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// List indicates an expected call of List. -func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName) -} - -// ListAll mocks base method. -func (m *MockInterface) ListAll(ctx context.Context) ([]network.PublicIPAddress, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListAll", ctx) - ret0, _ := ret[0].([]network.PublicIPAddress) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// ListAll indicates an expected call of ListAll. -func (mr *MockInterfaceMockRecorder) ListAll(ctx any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListAll", reflect.TypeOf((*MockInterface)(nil).ListAll), ctx) -} diff --git a/pkg/azureclients/subnetclient/azure_subnetclient.go b/pkg/azureclients/subnetclient/azure_subnetclient.go deleted file mode 100644 index 83747c02f4..0000000000 --- a/pkg/azureclients/subnetclient/azure_subnetclient.go +++ /dev/null @@ -1,428 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package subnetclient - -import ( - "context" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/klog/v2" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/metrics" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -var _ Interface = &Client{} - -const vnetResourceType = "Microsoft.Network/virtualNetworks" - -// Client implements Subnet client Interface. -type Client struct { - armClient armclient.Interface - subscriptionID string - cloudName string - - // Rate limiting configures. - rateLimiterReader flowcontrol.RateLimiter - rateLimiterWriter flowcontrol.RateLimiter - - // ARM throttling configures. - RetryAfterReader time.Time - RetryAfterWriter time.Time -} - -// New creates a new Subnet client with ratelimiting. -func New(config *azclients.ClientConfig) *Client { - baseURI := config.ResourceManagerEndpoint - authorizer := config.Authorizer - apiVersion := APIVersion - if strings.EqualFold(config.CloudName, AzureStackCloudName) && !config.DisableAzureStackCloud { - apiVersion = AzureStackCloudAPIVersion - } - armClient := armclient.New(authorizer, *config, baseURI, apiVersion) - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig) - - if azclients.RateLimitEnabled(config.RateLimitConfig) { - klog.V(2).Infof("Azure SubnetsClient (read ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPS, - config.RateLimitConfig.CloudProviderRateLimitBucket) - klog.V(2).Infof("Azure SubnetsClient (write ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPSWrite, - config.RateLimitConfig.CloudProviderRateLimitBucketWrite) - } - - client := &Client{ - armClient: armClient, - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - subscriptionID: config.SubscriptionID, - cloudName: config.CloudName, - } - - return client -} - -// Get gets a Subnet. -func (c *Client) Get(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (network.Subnet, *retry.Error) { - mc := metrics.NewMetricContext("subnets", "get", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return network.Subnet{}, retry.GetRateLimitError(false, "SubnetGet") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("SubnetGet", "client throttled", c.RetryAfterReader) - return network.Subnet{}, rerr - } - - result, rerr := c.getSubnet(ctx, resourceGroupName, virtualNetworkName, subnetName, expand) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// getSubnet gets a Subnet. -func (c *Client) getSubnet(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (network.Subnet, *retry.Error) { - resourceID := armclient.GetChildResourceID( - c.subscriptionID, - resourceGroupName, - vnetResourceType, - virtualNetworkName, - "subnets", - subnetName, - ) - result := network.Subnet{} - - response, rerr := c.armClient.GetResourceWithExpandQuery(ctx, resourceID, expand) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "subnet.get.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "subnet.get.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} - -// List gets a list of Subnets in the VNet. -func (c *Client) List(ctx context.Context, resourceGroupName string, virtualNetworkName string) ([]network.Subnet, *retry.Error) { - mc := metrics.NewMetricContext("subnets", "list", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(false, "SubnetList") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("SubnetList", "client throttled", c.RetryAfterReader) - return nil, rerr - } - - result, rerr := c.listSubnet(ctx, resourceGroupName, virtualNetworkName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// listSubnet gets a list of Subnets in the VNet. -func (c *Client) listSubnet(ctx context.Context, resourceGroupName string, virtualNetworkName string) ([]network.Subnet, *retry.Error) { - resourceID := armclient.GetChildResourcesListID( - c.subscriptionID, - resourceGroupName, - vnetResourceType, - virtualNetworkName, - "subnets") - - result := make([]network.Subnet, 0) - page := &SubnetListResultPage{} - page.fn = c.listNextResults - - resp, rerr := c.armClient.GetResource(ctx, resourceID) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "subnet.list.request", resourceID, rerr.Error()) - return result, rerr - } - - var err error - page.slr, err = c.listResponder(resp) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "subnet.list.respond", resourceID, err) - return result, retry.GetError(resp, err) - } - - for { - result = append(result, page.Values()...) - - // Abort the loop when there's no nextLink in the response. - if ptr.Deref(page.Response().NextLink, "") == "" { - break - } - - if err = page.NextWithContext(ctx); err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "subnet.list.next", resourceID, err) - return result, retry.GetError(page.Response().Response.Response, err) - } - } - - return result, nil -} - -// CreateOrUpdate creates or updates a Subnet. -func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters network.Subnet) *retry.Error { - mc := metrics.NewMetricContext("subnets", "create_or_update", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "SubnetCreateOrUpdate") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("SubnetCreateOrUpdate", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.createOrUpdateSubnet(ctx, resourceGroupName, virtualNetworkName, subnetName, subnetParameters) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// createOrUpdateSubnet creates or updates a Subnet. -func (c *Client) createOrUpdateSubnet(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters network.Subnet) *retry.Error { - resourceID := armclient.GetChildResourceID( - c.subscriptionID, - resourceGroupName, - vnetResourceType, - virtualNetworkName, - "subnets", - subnetName) - - response, rerr := c.armClient.PutResource(ctx, resourceID, subnetParameters) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "subnet.put.request", resourceID, rerr.Error()) - return rerr - } - - if response != nil && response.StatusCode != http.StatusNoContent { - _, rerr = c.createOrUpdateResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "subnet.put.respond", resourceID, rerr.Error()) - return rerr - } - } - - return nil -} - -func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.Subnet, *retry.Error) { - result := &network.Subnet{} - err := autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return result, retry.GetError(resp, err) -} - -// Delete deletes a Subnet by name. -func (c *Client) Delete(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) *retry.Error { - mc := metrics.NewMetricContext("subnets", "delete", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "SubnetDelete") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("SubnetDelete", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.deleteSubnet(ctx, resourceGroupName, virtualNetworkName, subnetName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// deleteSubnet deletes a PublicIPAddress by name. -func (c *Client) deleteSubnet(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) *retry.Error { - resourceID := armclient.GetChildResourceID( - c.subscriptionID, - resourceGroupName, - vnetResourceType, - virtualNetworkName, - "subnets", - subnetName) - - return c.armClient.DeleteResource(ctx, resourceID) -} - -func (c *Client) listResponder(resp *http.Response) (result network.SubnetListResult, err error) { - err = autorest.Respond( - resp, - autorest.ByIgnoring(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return -} - -// subnetListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (c *Client) subnetListResultPreparer(ctx context.Context, lblr network.SubnetListResult) (*http.Request, error) { - if lblr.NextLink == nil || len(ptr.Deref(lblr.NextLink, "")) < 1 { - return nil, nil - } - - decorators := []autorest.PrepareDecorator{ - autorest.WithBaseURL(ptr.Deref(lblr.NextLink, "")), - } - return c.armClient.PrepareGetRequest(ctx, decorators...) -} - -// listNextResults retrieves the next set of results, if any. -func (c *Client) listNextResults(ctx context.Context, lastResults network.SubnetListResult) (result network.SubnetListResult, err error) { - req, err := c.subnetListResultPreparer(ctx, lastResults) - if err != nil { - return result, autorest.NewErrorWithError(err, "subnetclient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - - resp, rerr := c.armClient.Send(ctx, req) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(rerr.Error(), "subnetclient", "listNextResults", resp, "Failure sending next results request") - } - - result, err = c.listResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "subnetclient", "listNextResults", resp, "Failure responding to next results request") - } - - return -} - -// SubnetListResultPage contains a page of Subnet values. -type SubnetListResultPage struct { - fn func(context.Context, network.SubnetListResult) (network.SubnetListResult, error) - slr network.SubnetListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SubnetListResultPage) NextWithContext(ctx context.Context) (err error) { - next, err := page.fn(ctx, page.slr) - if err != nil { - return err - } - page.slr = next - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SubnetListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page SubnetListResultPage) NotDone() bool { - return !page.slr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page SubnetListResultPage) Response() network.SubnetListResult { - return page.slr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page SubnetListResultPage) Values() []network.Subnet { - if page.slr.IsEmpty() { - return nil - } - return *page.slr.Value -} diff --git a/pkg/azureclients/subnetclient/azure_subnetclient_test.go b/pkg/azureclients/subnetclient/azure_subnetclient_test.go deleted file mode 100644 index 757135dd3d..0000000000 --- a/pkg/azureclients/subnetclient/azure_subnetclient_test.go +++ /dev/null @@ -1,681 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package subnetclient - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "testing" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - "github.com/Azure/go-autorest/autorest" - "github.com/stretchr/testify/assert" - - "go.uber.org/mock/gomock" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient/mockarmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - testResourceID = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet/subnets/subnet1" - testResourcePrefix = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet/subnets" -) - -func TestNew(t *testing.T) { - config := &azclients.ClientConfig{ - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - subnetClient := New(config) - assert.Equal(t, "sub", subnetClient.subscriptionID) - assert.NotEmpty(t, subnetClient.rateLimiterReader) - assert.NotEmpty(t, subnetClient.rateLimiterWriter) -} - -func TestNewAzureStack(t *testing.T) { - config := &azclients.ClientConfig{ - CloudName: "AZURESTACKCLOUD", - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - subnetClient := New(config) - assert.Equal(t, "AZURESTACKCLOUD", subnetClient.cloudName) - assert.Equal(t, "sub", subnetClient.subscriptionID) -} - -func TestGet(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - testSubnet := network.Subnet{ - Name: ptr.To("subnet1"), - } - subnet, err := testSubnet.MarshalJSON() - assert.NoError(t, err) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(subnet)), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - expected := network.Subnet{ - Response: autorest.Response{Response: response}, - Name: ptr.To("subnet1"), - } - subnetClient := getTestSubnetClient(armClient) - result, rerr := subnetClient.Get(context.TODO(), "rg", "vnet", "subnet1", "") - assert.Equal(t, expected, result) - assert.Nil(t, rerr) -} - -func TestGetNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - subnetClient := getTestSubnetClient(armClient) - expected := network.Subnet{Response: autorest.Response{}} - result, rerr := subnetClient.Get(context.TODO(), "rg", "vnet", "subnet1", "") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestGetInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - subnetClient := getTestSubnetClient(armClient) - expected := network.Subnet{Response: autorest.Response{}} - result, rerr := subnetClient.Get(context.TODO(), "rg", "vnet", "subnet1", "") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestGetNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - subnetGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "SubnetGet"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - subnetClient := getTestSubnetClientWithNeverRateLimiter(armClient) - expected := network.Subnet{} - result, rerr := subnetClient.Get(context.TODO(), "rg", "vnet", "subnet1", "") - assert.Equal(t, expected, result) - assert.Equal(t, subnetGetErr, rerr) -} - -func TestGetRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - subnetGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "SubnetGet", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - subnetClient := getTestSubnetClientWithRetryAfterReader(armClient) - expected := network.Subnet{} - result, rerr := subnetClient.Get(context.TODO(), "rg", "vnet", "subnet1", "") - assert.Equal(t, expected, result) - assert.Equal(t, subnetGetErr, rerr) -} - -func TestGetThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - subnetClient := getTestSubnetClient(armClient) - result, rerr := subnetClient.Get(context.TODO(), "rg", "vnet", "subnet1", "") - assert.Empty(t, result) - assert.Equal(t, throttleErr, rerr) -} - -func TestList(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - subnetList := []network.Subnet{getTestSubnet("subnet1"), getTestSubnet("subnet2"), getTestSubnet("subnet3")} - responseBody, err := json.Marshal(network.SubnetListResult{Value: &subnetList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - subnetClient := getTestSubnetClient(armClient) - result, rerr := subnetClient.List(context.TODO(), "rg", "vnet") - assert.Nil(t, rerr) - assert.Equal(t, 3, len(result)) -} - -func TestListNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - subnetClient := getTestSubnetClient(armClient) - expected := []network.Subnet{} - result, rerr := subnetClient.List(context.TODO(), "rg", "vnet") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestListInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - subnetClient := getTestSubnetClient(armClient) - expected := []network.Subnet{} - result, rerr := subnetClient.List(context.TODO(), "rg", "vnet") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestListThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - subnetClient := getTestSubnetClient(armClient) - result, rerr := subnetClient.List(context.TODO(), "rg", "vnet") - assert.Empty(t, result) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestListWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - subnetList := []network.Subnet{getTestSubnet("subnet1"), getTestSubnet("subnet2"), getTestSubnet("subnet3")} - responseBody, err := json.Marshal(network.SubnetListResult{Value: &subnetList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - subnetClient := getTestSubnetClient(armClient) - result, rerr := subnetClient.List(context.TODO(), "rg", "vnet") - assert.NotNil(t, rerr) - assert.Equal(t, 0, len(result)) -} - -func TestListWithNextPage(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - subnetList := []network.Subnet{getTestSubnet("subnet1"), getTestSubnet("subnet2"), getTestSubnet("subnet3")} - partialResponse, err := json.Marshal(network.SubnetListResult{Value: &subnetList, NextLink: ptr.To("nextLink")}) - assert.NoError(t, err) - pagedResponse, err := json.Marshal(network.SubnetListResult{Value: &subnetList}) - assert.NoError(t, err) - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(&http.Request{}, nil) - armClient.EXPECT().Send(gomock.Any(), gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(pagedResponse)), - }, nil) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(partialResponse)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(2) - subnetClient := getTestSubnetClient(armClient) - result, rerr := subnetClient.List(context.TODO(), "rg", "vnet") - assert.Nil(t, rerr) - assert.Equal(t, 6, len(result)) -} - -func TestListNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - subnetListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "SubnetList"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - subnetClient := getTestSubnetClientWithNeverRateLimiter(armClient) - result, rerr := subnetClient.List(context.TODO(), "rg", "vnet") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, subnetListErr, rerr) -} - -func TestListRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - subnetListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "SubnetList", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - subnetClient := getTestSubnetClientWithRetryAfterReader(armClient) - result, rerr := subnetClient.List(context.TODO(), "rg", "vnet") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, subnetListErr, rerr) -} - -func TestListNextResultsMultiPages(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - prepareErr error - sendErr *retry.Error - }{ - { - prepareErr: nil, - sendErr: nil, - }, - { - prepareErr: fmt.Errorf("error"), - }, - { - sendErr: &retry.Error{RawError: fmt.Errorf("error")}, - }, - } - - lastResult := network.SubnetListResult{ - NextLink: ptr.To("next"), - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - subnetClient := getTestSubnetClient(armClient) - result, err := subnetClient.listNextResults(context.TODO(), lastResult) - if test.prepareErr != nil || test.sendErr != nil { - assert.Error(t, err) - } else { - assert.NoError(t, err) - } - if test.prepareErr != nil { - assert.Empty(t, result) - } else { - assert.NotEmpty(t, result) - } - } -} - -func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - test := struct { - prepareErr error - sendErr *retry.Error - }{ - prepareErr: nil, - sendErr: nil, - } - - lastResult := network.SubnetListResult{ - NextLink: ptr.To("next"), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewBuffer([]byte(`{"foo":"bar"}`))), - } - expected := network.SubnetListResult{} - expected.Response = autorest.Response{Response: response} - subnetClient := getTestSubnetClient(armClient) - result, err := subnetClient.listNextResults(context.TODO(), lastResult) - assert.Error(t, err) - assert.Equal(t, expected, result) -} - -func TestCreateOrUpdate(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - subnet := getTestSubnet("subnet1") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(subnet.ID, ""), subnet).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - subnetClient := getTestSubnetClient(armClient) - rerr := subnetClient.CreateOrUpdate(context.TODO(), "rg", "vnet", "subnet1", subnet) - assert.Nil(t, rerr) -} - -func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - subnet := getTestSubnet("subnet1") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(subnet.ID, ""), subnet).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - subnetClient := getTestSubnetClient(armClient) - rerr := subnetClient.CreateOrUpdate(context.TODO(), "rg", "vnet", "subnet1", subnet) - assert.NotNil(t, rerr) -} - -func TestCreateOrUpdateNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - subnetCreateOrUpdateErr := retry.GetRateLimitError(true, "SubnetCreateOrUpdate") - - armClient := mockarmclient.NewMockInterface(ctrl) - subnetClient := getTestSubnetClientWithNeverRateLimiter(armClient) - subnet := getTestSubnet("subnet1") - rerr := subnetClient.CreateOrUpdate(context.TODO(), "rg", "vnet", "subnet1", subnet) - assert.NotNil(t, rerr) - assert.Equal(t, subnetCreateOrUpdateErr, rerr) -} - -func TestCreateOrUpdateRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - subnetCreateOrUpdateErr := retry.GetThrottlingError("SubnetCreateOrUpdate", "client throttled", getFutureTime()) - - subnet := getTestSubnet("subnet1") - armClient := mockarmclient.NewMockInterface(ctrl) - subnetClient := getTestSubnetClientWithRetryAfterReader(armClient) - rerr := subnetClient.CreateOrUpdate(context.TODO(), "rg", "vnet", "subnet1", subnet) - assert.NotNil(t, rerr) - assert.Equal(t, subnetCreateOrUpdateErr, rerr) -} - -func TestCreateOrUpdateThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - subnet := getTestSubnet("subnet1") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(subnet.ID, ""), subnet).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - subnetClient := getTestSubnetClient(armClient) - rerr := subnetClient.CreateOrUpdate(context.TODO(), "rg", "vnet", "subnet1", subnet) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestDelete(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - r := getTestSubnet("subnet1") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().DeleteResource(gomock.Any(), ptr.Deref(r.ID, "")).Return(nil).Times(1) - - subnetClient := getTestSubnetClient(armClient) - rerr := subnetClient.Delete(context.TODO(), "rg", "vnet", "subnet1") - assert.Nil(t, rerr) -} - -func TestDeleteNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - subnetDeleteErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "write", "SubnetDelete"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - subnetClient := getTestSubnetClientWithNeverRateLimiter(armClient) - rerr := subnetClient.Delete(context.TODO(), "rg", "vnet", "subnet1") - assert.NotNil(t, rerr) - assert.Equal(t, subnetDeleteErr, rerr) -} - -func TestDeleteRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - subnetDeleteErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "SubnetDelete", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - subnetClient := getTestSubnetClientWithRetryAfterReader(armClient) - rerr := subnetClient.Delete(context.TODO(), "rg", "vnet", "subnet1") - assert.NotNil(t, rerr) - assert.Equal(t, subnetDeleteErr, rerr) -} - -func TestDeleteThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - subnet := getTestSubnet("subnet1") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().DeleteResource(gomock.Any(), ptr.Deref(subnet.ID, "")).Return(throttleErr).Times(1) - - subnetClient := getTestSubnetClient(armClient) - rerr := subnetClient.Delete(context.TODO(), "rg", "vnet", "subnet1") - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func getTestSubnet(name string) network.Subnet { - return network.Subnet{ - ID: ptr.To(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet/subnets/%s", name)), - Name: ptr.To(name), - } -} - -func getTestSubnetClient(armClient armclient.Interface) *Client { - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(&azclients.RateLimitConfig{}) - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestSubnetClientWithNeverRateLimiter(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeNeverRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeNeverRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestSubnetClientWithRetryAfterReader(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeAlwaysRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeAlwaysRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - RetryAfterReader: getFutureTime(), - RetryAfterWriter: getFutureTime(), - } -} - -func getFutureTime() time.Time { - return time.Unix(3000000000, 0) -} diff --git a/pkg/azureclients/subnetclient/doc.go b/pkg/azureclients/subnetclient/doc.go deleted file mode 100644 index 7248d19b19..0000000000 --- a/pkg/azureclients/subnetclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package subnetclient implements the client for Subnet. -package subnetclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/subnetclient" diff --git a/pkg/azureclients/subnetclient/interface.go b/pkg/azureclients/subnetclient/interface.go deleted file mode 100644 index fb6cc85656..0000000000 --- a/pkg/azureclients/subnetclient/interface.go +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package subnetclient - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - // APIVersion is the API version for network. - APIVersion = "2022-07-01" - // AzureStackCloudAPIVersion is the API version for Azure Stack - AzureStackCloudAPIVersion = "2018-11-01" - // AzureStackCloudName is the cloud name of Azure Stack - AzureStackCloudName = "AZURESTACKCLOUD" -) - -// Interface is the client interface for Subnet. -// Don't forget to run "hack/update-mock-clients.sh" command to generate the mock client. -type Interface interface { - // Get gets a Subnet. - Get(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (result network.Subnet, rerr *retry.Error) - - // List gets a list of Subnet in the VNet. - List(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result []network.Subnet, rerr *retry.Error) - - // CreateOrUpdate creates or updates a Subnet. - CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters network.Subnet) *retry.Error - - // Delete deletes a Subnet by name. - Delete(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) *retry.Error -} diff --git a/pkg/azureclients/subnetclient/mocksubnetclient/doc.go b/pkg/azureclients/subnetclient/mocksubnetclient/doc.go deleted file mode 100644 index 89b77d2830..0000000000 --- a/pkg/azureclients/subnetclient/mocksubnetclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package mocksubnetclient implements the mock client for Subnet. -package mocksubnetclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/subnetclient/mocksubnetclient" diff --git a/pkg/azureclients/subnetclient/mocksubnetclient/interface.go b/pkg/azureclients/subnetclient/mocksubnetclient/interface.go deleted file mode 100644 index 22880f9151..0000000000 --- a/pkg/azureclients/subnetclient/mocksubnetclient/interface.go +++ /dev/null @@ -1,117 +0,0 @@ -// /* -// Copyright The Kubernetes Authors. -// -// 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 MockGen. DO NOT EDIT. -// Source: pkg/azureclients/subnetclient/interface.go -// -// Generated by this command: -// -// mockgen -copyright_file=/home/runner/work/cloud-provider-azure/cloud-provider-azure/hack/boilerplate/boilerplate.generatego.txt -source=pkg/azureclients/subnetclient/interface.go -package=mocksubnetclient Interface -// - -// Package mocksubnetclient is a generated GoMock package. -package mocksubnetclient - -import ( - context "context" - reflect "reflect" - - network "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - gomock "go.uber.org/mock/gomock" - retry "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -// MockInterface is a mock of Interface interface. -type MockInterface struct { - ctrl *gomock.Controller - recorder *MockInterfaceMockRecorder -} - -// MockInterfaceMockRecorder is the mock recorder for MockInterface. -type MockInterfaceMockRecorder struct { - mock *MockInterface -} - -// NewMockInterface creates a new mock instance. -func NewMockInterface(ctrl *gomock.Controller) *MockInterface { - mock := &MockInterface{ctrl: ctrl} - mock.recorder = &MockInterfaceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { - return m.recorder -} - -// CreateOrUpdate mocks base method. -func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, virtualNetworkName, subnetName string, subnetParameters network.Subnet) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrUpdate", ctx, resourceGroupName, virtualNetworkName, subnetName, subnetParameters) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// CreateOrUpdate indicates an expected call of CreateOrUpdate. -func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, virtualNetworkName, subnetName, subnetParameters any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdate", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, virtualNetworkName, subnetName, subnetParameters) -} - -// Delete mocks base method. -func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, virtualNetworkName, subnetName string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Delete", ctx, resourceGroupName, virtualNetworkName, subnetName) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// Delete indicates an expected call of Delete. -func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, virtualNetworkName, subnetName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, virtualNetworkName, subnetName) -} - -// Get mocks base method. -func (m *MockInterface) Get(ctx context.Context, resourceGroupName, virtualNetworkName, subnetName, expand string) (network.Subnet, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", ctx, resourceGroupName, virtualNetworkName, subnetName, expand) - ret0, _ := ret[0].(network.Subnet) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, virtualNetworkName, subnetName, expand any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, virtualNetworkName, subnetName, expand) -} - -// List mocks base method. -func (m *MockInterface) List(ctx context.Context, resourceGroupName, virtualNetworkName string) ([]network.Subnet, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "List", ctx, resourceGroupName, virtualNetworkName) - ret0, _ := ret[0].([]network.Subnet) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// List indicates an expected call of List. -func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName, virtualNetworkName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName, virtualNetworkName) -} diff --git a/pkg/azureclients/vmasclient/azure_vmasclient.go b/pkg/azureclients/vmasclient/azure_vmasclient.go deleted file mode 100644 index 5c126c7f88..0000000000 --- a/pkg/azureclients/vmasclient/azure_vmasclient.go +++ /dev/null @@ -1,307 +0,0 @@ -/* -Copyright 2021 The Kubernetes Authors. - -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. -*/ - -package vmasclient - -import ( - "context" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/klog/v2" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/metrics" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -var _ Interface = &Client{} - -const vmasResourceType = "Microsoft.Compute/availabilitySets" - -// Client implements VMAS client Interface. -type Client struct { - armClient armclient.Interface - subscriptionID string - cloudName string - - // Rate limiting configures. - rateLimiterReader flowcontrol.RateLimiter - rateLimiterWriter flowcontrol.RateLimiter - - // ARM throttling configures. - RetryAfterReader time.Time - RetryAfterWriter time.Time -} - -// New creates a new VMAS client with ratelimiting. -func New(config *azclients.ClientConfig) *Client { - baseURI := config.ResourceManagerEndpoint - authorizer := config.Authorizer - apiVersion := APIVersion - if strings.EqualFold(config.CloudName, AzureStackCloudName) && !config.DisableAzureStackCloud { - apiVersion = AzureStackCloudAPIVersion - } - armClient := armclient.New(authorizer, *config, baseURI, apiVersion) - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig) - - if azclients.RateLimitEnabled(config.RateLimitConfig) { - klog.V(2).Infof("Azure AvailabilitySetsClient (read ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPS, - config.RateLimitConfig.CloudProviderRateLimitBucket) - klog.V(2).Infof("Azure AvailabilitySetsClient (write ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPSWrite, - config.RateLimitConfig.CloudProviderRateLimitBucketWrite) - } - - client := &Client{ - armClient: armClient, - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - subscriptionID: config.SubscriptionID, - cloudName: config.CloudName, - } - - return client -} - -// Get gets a AvailabilitySet. -func (c *Client) Get(ctx context.Context, resourceGroupName string, vmasName string) (compute.AvailabilitySet, *retry.Error) { - mc := metrics.NewMetricContext("vmas", "get", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return compute.AvailabilitySet{}, retry.GetRateLimitError(false, "VMASGet") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMASGet", "client throttled", c.RetryAfterReader) - return compute.AvailabilitySet{}, rerr - } - - result, rerr := c.getVMAS(ctx, resourceGroupName, vmasName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// getVMAS gets a AvailabilitySet. -func (c *Client) getVMAS(ctx context.Context, resourceGroupName string, vmasName string) (compute.AvailabilitySet, *retry.Error) { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - vmasResourceType, - vmasName, - ) - result := compute.AvailabilitySet{} - - response, rerr := c.armClient.GetResource(ctx, resourceID) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmas.get.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmas.get.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} - -// List gets a list of AvailabilitySets in the resource group. -func (c *Client) List(ctx context.Context, resourceGroupName string) ([]compute.AvailabilitySet, *retry.Error) { - mc := metrics.NewMetricContext("vmas", "list", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(false, "VMASList") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMASList", "client throttled", c.RetryAfterReader) - return nil, rerr - } - - result, rerr := c.listVMAS(ctx, resourceGroupName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// listVMAS gets a list of AvailabilitySets in the resource group. -func (c *Client) listVMAS(ctx context.Context, resourceGroupName string) ([]compute.AvailabilitySet, *retry.Error) { - resourceID := armclient.GetResourceListID(c.subscriptionID, resourceGroupName, vmasResourceType) - result := make([]compute.AvailabilitySet, 0) - page := &AvailabilitySetListResultPage{} - page.fn = c.listNextResults - - resp, rerr := c.armClient.GetResource(ctx, resourceID) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmas.list.request", resourceID, rerr.Error()) - return result, rerr - } - - var err error - page.vmaslr, err = c.listResponder(resp) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmas.list.respond", resourceID, err) - return result, retry.GetError(resp, err) - } - - for { - result = append(result, page.Values()...) - - // Abort the loop when there's no nextLink in the response. - if ptr.Deref(page.Response().NextLink, "") == "" { - break - } - - if err = page.NextWithContext(ctx); err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmas.list.next", resourceID, err) - return result, retry.GetError(page.Response().Response.Response, err) - } - } - - return result, nil -} - -func (c *Client) listResponder(resp *http.Response) (result compute.AvailabilitySetListResult, err error) { - err = autorest.Respond( - resp, - autorest.ByIgnoring(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return -} - -// availabilitySetListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (c *Client) availabilitySetListResultPreparer(ctx context.Context, vmaslr compute.AvailabilitySetListResult) (*http.Request, error) { - if vmaslr.NextLink == nil || len(ptr.Deref(vmaslr.NextLink, "")) < 1 { - return nil, nil - } - - decorators := []autorest.PrepareDecorator{ - autorest.WithBaseURL(ptr.Deref(vmaslr.NextLink, "")), - } - return c.armClient.PrepareGetRequest(ctx, decorators...) -} - -// listNextResults retrieves the next set of results, if any. -func (c *Client) listNextResults(ctx context.Context, lastResults compute.AvailabilitySetListResult) (result compute.AvailabilitySetListResult, err error) { - req, err := c.availabilitySetListResultPreparer(ctx, lastResults) - if err != nil { - return result, autorest.NewErrorWithError(err, "vmasclient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - - resp, rerr := c.armClient.Send(ctx, req) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(rerr.Error(), "vmasclient", "listNextResults", resp, "Failure sending next results request") - } - - result, err = c.listResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "vmasclient", "listNextResults", resp, "Failure responding to next results request") - } - - return -} - -// AvailabilitySetListResultPage contains a page of AvailabilitySet values. -type AvailabilitySetListResultPage struct { - fn func(context.Context, compute.AvailabilitySetListResult) (compute.AvailabilitySetListResult, error) - vmaslr compute.AvailabilitySetListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AvailabilitySetListResultPage) NextWithContext(ctx context.Context) (err error) { - next, err := page.fn(ctx, page.vmaslr) - if err != nil { - return err - } - page.vmaslr = next - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AvailabilitySetListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AvailabilitySetListResultPage) NotDone() bool { - return !page.vmaslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AvailabilitySetListResultPage) Response() compute.AvailabilitySetListResult { - return page.vmaslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AvailabilitySetListResultPage) Values() []compute.AvailabilitySet { - if page.vmaslr.IsEmpty() { - return nil - } - return *page.vmaslr.Value -} diff --git a/pkg/azureclients/vmasclient/azure_vmasclient_test.go b/pkg/azureclients/vmasclient/azure_vmasclient_test.go deleted file mode 100644 index 0b8ac6caa9..0000000000 --- a/pkg/azureclients/vmasclient/azure_vmasclient_test.go +++ /dev/null @@ -1,544 +0,0 @@ -/* -Copyright 2021 The Kubernetes Authors. - -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. -*/ - -package vmasclient - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "testing" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest" - "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient/mockarmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - testResourceID = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/availabilitySets/vmas1" - testResourcePrefix = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/availabilitySets" -) - -func TestNew(t *testing.T) { - config := &azclients.ClientConfig{ - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - vmasClient := New(config) - assert.Equal(t, "sub", vmasClient.subscriptionID) - assert.NotEmpty(t, vmasClient.rateLimiterReader) - assert.NotEmpty(t, vmasClient.rateLimiterWriter) -} - -func TestNewAzureStack(t *testing.T) { - config := &azclients.ClientConfig{ - CloudName: "AZURESTACKCLOUD", - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - vmasClient := New(config) - assert.Equal(t, "AZURESTACKCLOUD", vmasClient.cloudName) - assert.Equal(t, "sub", vmasClient.subscriptionID) -} - -func TestGet(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - expected := compute.AvailabilitySet{Response: autorest.Response{Response: response}} - vmasClient := getTestVMASClient(armClient) - result, rerr := vmasClient.Get(context.TODO(), "rg", "vmas1") - assert.Equal(t, expected, result) - assert.Nil(t, rerr) -} - -func TestGetNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmasGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "VMASGet"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmasClient := getTestVMASClientWithNeverRateLimiter(armClient) - expected := compute.AvailabilitySet{} - result, rerr := vmasClient.Get(context.TODO(), "rg", "vmas1") - assert.Equal(t, expected, result) - assert.Equal(t, vmasGetErr, rerr) -} - -func TestGetRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmasGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMASGet", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmasClient := getTestVMASClientWithRetryAfterReader(armClient) - expected := compute.AvailabilitySet{} - result, rerr := vmasClient.Get(context.TODO(), "rg", "vmas1") - assert.Equal(t, expected, result) - assert.Equal(t, vmasGetErr, rerr) -} - -func TestGetNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmasClient := getTestVMASClient(armClient) - expectedVMAS := compute.AvailabilitySet{Response: autorest.Response{}} - result, rerr := vmasClient.Get(context.TODO(), "rg", "vmas1") - assert.Equal(t, expectedVMAS, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestGetInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmasClient := getTestVMASClient(armClient) - expectedVMAS := compute.AvailabilitySet{Response: autorest.Response{}} - result, rerr := vmasClient.Get(context.TODO(), "rg", "vmas1") - assert.Equal(t, expectedVMAS, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestGetThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmasClient := getTestVMASClient(armClient) - result, rerr := vmasClient.Get(context.TODO(), "rg", "vmas1") - assert.Empty(t, result) - assert.Equal(t, throttleErr, rerr) -} - -func TestList(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmasList := []compute.AvailabilitySet{getTestVMAS("vmas1"), getTestVMAS("vmas2"), getTestVMAS("vmas3")} - responseBody, err := json.Marshal(compute.AvailabilitySetListResult{Value: &vmasList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmasClient := getTestVMASClient(armClient) - result, rerr := vmasClient.List(context.TODO(), "rg") - assert.Nil(t, rerr) - assert.Equal(t, 3, len(result)) -} - -func TestListNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmasClient := getTestVMASClient(armClient) - expected := []compute.AvailabilitySet{} - result, rerr := vmasClient.List(context.TODO(), "rg") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestListInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmasClient := getTestVMASClient(armClient) - expected := []compute.AvailabilitySet{} - result, rerr := vmasClient.List(context.TODO(), "rg") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestListThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmasClient := getTestVMASClient(armClient) - result, rerr := vmasClient.List(context.TODO(), "rg") - assert.Empty(t, result) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestListWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmasList := []compute.AvailabilitySet{getTestVMAS("vmas1"), getTestVMAS("vmas2"), getTestVMAS("vmas3")} - responseBody, err := json.Marshal(compute.AvailabilitySetListResult{Value: &vmasList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmasClient := getTestVMASClient(armClient) - result, rerr := vmasClient.List(context.TODO(), "rg") - assert.NotNil(t, rerr) - assert.Equal(t, 0, len(result)) -} - -func TestListWithNextPage(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmasList := []compute.AvailabilitySet{getTestVMAS("vmas1"), getTestVMAS("vmas2"), getTestVMAS("vmas3")} - partialResponse, err := json.Marshal(compute.AvailabilitySetListResult{Value: &vmasList, NextLink: ptr.To("nextLink")}) - assert.NoError(t, err) - pagedResponse, err := json.Marshal(compute.AvailabilitySetListResult{Value: &vmasList}) - assert.NoError(t, err) - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(&http.Request{}, nil) - armClient.EXPECT().Send(gomock.Any(), gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(pagedResponse)), - }, nil) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(partialResponse)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(2) - vmasClient := getTestVMASClient(armClient) - result, rerr := vmasClient.List(context.TODO(), "rg") - assert.Nil(t, rerr) - assert.Equal(t, 6, len(result)) -} - -func TestListNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmasListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "VMASList"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmasClient := getTestVMASClientWithNeverRateLimiter(armClient) - result, rerr := vmasClient.List(context.TODO(), "rg") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, vmasListErr, rerr) -} - -func TestListRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmasListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMASList", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmasClient := getTestVMASClientWithRetryAfterReader(armClient) - result, rerr := vmasClient.List(context.TODO(), "rg") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, vmasListErr, rerr) -} - -func TestListNextResultsMultiPages(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - name string - prepareErr error - sendErr *retry.Error - expectedErrMsg string - }{ - { - name: "testlistNextResultsSuccessful", - prepareErr: nil, - sendErr: nil, - }, - { - name: "testPrepareGetRequestError", - prepareErr: fmt.Errorf("error"), - expectedErrMsg: "Failure preparing next results request", - }, - { - name: "testSendError", - sendErr: &retry.Error{RawError: fmt.Errorf("error")}, - expectedErrMsg: "Failure sending next results request", - }, - } - - lastResult := compute.AvailabilitySetListResult{ - NextLink: ptr.To("next"), - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - vmasClient := getTestVMASClient(armClient) - result, err := vmasClient.listNextResults(context.TODO(), lastResult) - if err != nil { - detailedErr := &autorest.DetailedError{} - assert.True(t, errors.As(err, detailedErr)) - assert.Equal(t, detailedErr.Message, test.expectedErrMsg) - } else { - assert.NoError(t, err) - } - - if test.prepareErr != nil { - assert.Empty(t, result) - } else { - assert.NotEmpty(t, result) - } - } -} - -func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - name string - prepareErr error - sendErr *retry.Error - }{ - { - name: "testListResponderError", - prepareErr: nil, - sendErr: nil, - }, - { - name: "testSendError", - sendErr: &retry.Error{RawError: fmt.Errorf("error")}, - }, - } - - lastResult := compute.AvailabilitySetListResult{ - NextLink: ptr.To("next"), - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewBuffer([]byte(`{"foo":"bar"}`))), - } - expected := compute.AvailabilitySetListResult{} - expected.Response = autorest.Response{Response: response} - vmasClient := getTestVMASClient(armClient) - result, err := vmasClient.listNextResults(context.TODO(), lastResult) - assert.Error(t, err) - if test.sendErr != nil { - assert.NotEqual(t, expected, result) - } else { - assert.Equal(t, expected, result) - } - } -} - -func getTestVMAS(name string) compute.AvailabilitySet { - return compute.AvailabilitySet{ - ID: ptr.To("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/availabilitySets/vmas1"), - Name: ptr.To(name), - Location: ptr.To("eastus"), - Sku: &compute.Sku{ - Name: ptr.To("Standard"), - Capacity: ptr.To(int64(3)), - }, - } -} - -func getTestVMASClient(armClient armclient.Interface) *Client { - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(&azclients.RateLimitConfig{}) - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestVMASClientWithNeverRateLimiter(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeNeverRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeNeverRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestVMASClientWithRetryAfterReader(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeAlwaysRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeAlwaysRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - RetryAfterReader: getFutureTime(), - RetryAfterWriter: getFutureTime(), - } -} - -func getFutureTime() time.Time { - return time.Unix(3000000000, 0) -} diff --git a/pkg/azureclients/vmasclient/doc.go b/pkg/azureclients/vmasclient/doc.go deleted file mode 100644 index 7f9dee7ed5..0000000000 --- a/pkg/azureclients/vmasclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2021 The Kubernetes Authors. - -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. -*/ - -// Package vmasclient implements the client for VMAS. -package vmasclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmasclient" diff --git a/pkg/azureclients/vmasclient/interface.go b/pkg/azureclients/vmasclient/interface.go deleted file mode 100644 index 0206a204f9..0000000000 --- a/pkg/azureclients/vmasclient/interface.go +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright 2021 The Kubernetes Authors. - -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. -*/ - -package vmasclient - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - // APIVersion is the API version for VMAS. - APIVersion = "2022-03-01" - // AzureStackCloudAPIVersion is the API version for Azure Stack - AzureStackCloudAPIVersion = "2019-07-01" - // AzureStackCloudName is the cloud name of Azure Stack - AzureStackCloudName = "AZURESTACKCLOUD" -) - -// Interface is the client interface for AvailabilitySet. -// Don't forget to run "hack/update-mock-clients.sh" command to generate the mock client. -type Interface interface { - // Get gets a VirtualMachineScaleSet. - Get(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result compute.AvailabilitySet, rerr *retry.Error) - - // List gets a list of VirtualMachineScaleSets in the resource group. - List(ctx context.Context, resourceGroupName string) (result []compute.AvailabilitySet, rerr *retry.Error) -} diff --git a/pkg/azureclients/vmasclient/mockvmasclient/doc.go b/pkg/azureclients/vmasclient/mockvmasclient/doc.go deleted file mode 100644 index 838085902f..0000000000 --- a/pkg/azureclients/vmasclient/mockvmasclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2021 The Kubernetes Authors. - -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. -*/ - -// Package mockvmasclient implements the mock client for VMAS. -package mockvmasclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmasclient/mockvmssclient" diff --git a/pkg/azureclients/vmasclient/mockvmasclient/interface.go b/pkg/azureclients/vmasclient/mockvmasclient/interface.go deleted file mode 100644 index f58c571f1e..0000000000 --- a/pkg/azureclients/vmasclient/mockvmasclient/interface.go +++ /dev/null @@ -1,89 +0,0 @@ -// /* -// Copyright The Kubernetes Authors. -// -// 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 MockGen. DO NOT EDIT. -// Source: pkg/azureclients/vmasclient/interface.go -// -// Generated by this command: -// -// mockgen -copyright_file=/home/runner/work/cloud-provider-azure/cloud-provider-azure/hack/boilerplate/boilerplate.generatego.txt -source=pkg/azureclients/vmasclient/interface.go -package=mockvmasclient Interface -// - -// Package mockvmasclient is a generated GoMock package. -package mockvmasclient - -import ( - context "context" - reflect "reflect" - - compute "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - gomock "go.uber.org/mock/gomock" - retry "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -// MockInterface is a mock of Interface interface. -type MockInterface struct { - ctrl *gomock.Controller - recorder *MockInterfaceMockRecorder -} - -// MockInterfaceMockRecorder is the mock recorder for MockInterface. -type MockInterfaceMockRecorder struct { - mock *MockInterface -} - -// NewMockInterface creates a new mock instance. -func NewMockInterface(ctrl *gomock.Controller) *MockInterface { - mock := &MockInterface{ctrl: ctrl} - mock.recorder = &MockInterfaceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { - return m.recorder -} - -// Get mocks base method. -func (m *MockInterface) Get(ctx context.Context, resourceGroupName, VMScaleSetName string) (compute.AvailabilitySet, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", ctx, resourceGroupName, VMScaleSetName) - ret0, _ := ret[0].(compute.AvailabilitySet) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, VMScaleSetName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, VMScaleSetName) -} - -// List mocks base method. -func (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]compute.AvailabilitySet, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "List", ctx, resourceGroupName) - ret0, _ := ret[0].([]compute.AvailabilitySet) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// List indicates an expected call of List. -func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName) -} diff --git a/pkg/azureclients/vmclient/azure_vmclient.go b/pkg/azureclients/vmclient/azure_vmclient.go deleted file mode 100644 index a3508259f7..0000000000 --- a/pkg/azureclients/vmclient/azure_vmclient.go +++ /dev/null @@ -1,681 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package vmclient - -import ( - "context" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/klog/v2" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/metrics" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -var _ Interface = &Client{} - -const vmResourceType = "Microsoft.Compute/virtualMachines" - -// Client implements VirtualMachine client Interface. -type Client struct { - armClient armclient.Interface - subscriptionID string - cloudName string - - // Rate limiting configures. - rateLimiterReader flowcontrol.RateLimiter - rateLimiterWriter flowcontrol.RateLimiter - - // ARM throttling configures. - RetryAfterReader time.Time - RetryAfterWriter time.Time -} - -// New creates a new VirtualMachine client with ratelimiting. -func New(config *azclients.ClientConfig) *Client { - baseURI := config.ResourceManagerEndpoint - authorizer := config.Authorizer - apiVersion := APIVersion - if strings.EqualFold(config.CloudName, AzureStackCloudName) && !config.DisableAzureStackCloud { - apiVersion = AzureStackCloudAPIVersion - } - armClient := armclient.New(authorizer, *config, baseURI, apiVersion) - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig) - - if azclients.RateLimitEnabled(config.RateLimitConfig) { - klog.V(2).Infof("Azure VirtualMachine client (read ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPS, - config.RateLimitConfig.CloudProviderRateLimitBucket) - klog.V(2).Infof("Azure VirtualMachine client (write ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPSWrite, - config.RateLimitConfig.CloudProviderRateLimitBucketWrite) - } - - client := &Client{ - armClient: armClient, - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - subscriptionID: config.SubscriptionID, - cloudName: config.CloudName, - } - - return client -} - -// Get gets a VirtualMachine. -func (c *Client) Get(ctx context.Context, resourceGroupName string, VMName string, expand compute.InstanceViewTypes) (compute.VirtualMachine, *retry.Error) { - mc := metrics.NewMetricContext("vm", "get", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return compute.VirtualMachine{}, retry.GetRateLimitError(false, "VMGet") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMGet", "client throttled", c.RetryAfterReader) - return compute.VirtualMachine{}, rerr - } - - result, rerr := c.getVM(ctx, resourceGroupName, VMName, expand) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// getVM gets a VirtualMachine. -func (c *Client) getVM(ctx context.Context, resourceGroupName string, VMName string, expand compute.InstanceViewTypes) (compute.VirtualMachine, *retry.Error) { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - vmResourceType, - VMName, - ) - result := compute.VirtualMachine{} - - response, rerr := c.armClient.GetResourceWithExpandQuery(ctx, resourceID, string(expand)) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vm.get.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vm.get.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} - -// List gets a list of VirtualMachine in the resourceGroupName. -func (c *Client) List(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachine, *retry.Error) { - return c.list(ctx, resourceGroupName, false) -} - -// ListWithInstanceView gets a list of VirtualMachine in the resourceGroupName with InstanceView. -func (c *Client) ListWithInstanceView(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachine, *retry.Error) { - return c.list(ctx, resourceGroupName, true) -} - -func (c *Client) list(ctx context.Context, resourceGroupName string, withInstanceView bool) ([]compute.VirtualMachine, *retry.Error) { - mc := metrics.NewMetricContext("vm", "list", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(false, "VMList") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMList", "client throttled", c.RetryAfterReader) - return nil, rerr - } - - result, rerr := c.listVM(ctx, resourceGroupName, withInstanceView) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// listVM gets a list of VirtualMachines in the resourceGroupName. -func (c *Client) listVM(ctx context.Context, resourceGroupName string, withInstanceView bool) ([]compute.VirtualMachine, *retry.Error) { - resourceID := armclient.GetResourceListID(c.subscriptionID, resourceGroupName, vmResourceType) - - result := make([]compute.VirtualMachine, 0) - page := &VirtualMachineListResultPage{} - page.fn = c.listNextResults - - var resp *http.Response - var rerr *retry.Error - if withInstanceView { - queries := make(map[string]interface{}) - queries["$expand"] = autorest.Encode("query", "instanceView") - resp, rerr = c.armClient.GetResourceWithQueries(ctx, resourceID, queries) - } else { - resp, rerr = c.armClient.GetResource(ctx, resourceID) - } - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vm.list.request", resourceID, rerr.Error()) - return result, rerr - } - - var err error - page.vmlr, err = c.listResponder(resp) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vm.list.respond", resourceID, err) - return result, retry.GetError(resp, err) - } - - for { - result = append(result, page.Values()...) - - // Abort the loop when there's no nextLink in the response. - if ptr.Deref(page.Response().NextLink, "") == "" { - break - } - - if err = page.NextWithContext(ctx); err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vm.list.next", resourceID, err) - return result, retry.GetError(page.Response().Response.Response, err) - } - } - - return result, nil -} - -// ListVmssFlexVMsWithoutInstanceView gets a list of VirtualMachine in the VMSS Flex without InstanceView. -func (c *Client) ListVmssFlexVMsWithoutInstanceView(ctx context.Context, vmssFlexID string) ([]compute.VirtualMachine, *retry.Error) { - mc := metrics.NewMetricContext("vm", "list", "", c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(false, "VMList") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMList", "client throttled", c.RetryAfterReader) - return nil, rerr - } - - result, rerr := c.listVmssFlexVMs(ctx, vmssFlexID, false) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// ListVmssFlexVMsWithOnlyInstanceView gets a list of VirtualMachine in the VMSS Flex with only InstanceView. -func (c *Client) ListVmssFlexVMsWithOnlyInstanceView(ctx context.Context, vmssFlexID string) ([]compute.VirtualMachine, *retry.Error) { - mc := metrics.NewMetricContext("vm", "list", "", c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(false, "VMList") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMList", "client throttled", c.RetryAfterReader) - return nil, rerr - } - - result, rerr := c.listVmssFlexVMs(ctx, vmssFlexID, true) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// listVmssFlexVMs gets a list of VirtualMachines in the VMSS Flex. -func (c *Client) listVmssFlexVMs(ctx context.Context, vmssFlexID string, statusOnly bool) ([]compute.VirtualMachine, *retry.Error) { - resourceID := armclient.GetProviderResourceID(c.subscriptionID, vmResourceType) - - result := make([]compute.VirtualMachine, 0) - page := &VirtualMachineListResultPage{} - page.fn = c.listNextResults - - queries := make(map[string]interface{}) - queries["$filter"] = "'virtualMachineScaleSet/id' eq '" + vmssFlexID + "'" - if statusOnly { - queries["statusOnly"] = true - } - resp, rerr := c.armClient.GetResourceWithQueries(ctx, resourceID, queries) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vm.list.request", resourceID, rerr.Error()) - return result, rerr - } - - var err error - page.vmlr, err = c.listResponder(resp) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vm.list.respond", resourceID, err) - return result, retry.GetError(resp, err) - } - - for { - result = append(result, page.Values()...) - - // Abort the loop when there's no nextLink in the response. - if ptr.Deref(page.Response().NextLink, "") == "" { - break - } - - if err = page.NextWithContext(ctx); err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vm.list.next", resourceID, err) - return result, retry.GetError(page.Response().Response.Response, err) - } - } - - return result, nil -} - -// Update updates a VirtualMachine. -func (c *Client) Update(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachineUpdate, source string) (*compute.VirtualMachine, *retry.Error) { - mc := metrics.NewMetricContext("vm", "update", resourceGroupName, c.subscriptionID, source) - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(true, "VMUpdate") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMUpdate", "client throttled", c.RetryAfterWriter) - return nil, rerr - } - - result, rerr := c.updateVM(ctx, resourceGroupName, VMName, parameters, source) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - return result, rerr - } - return result, rerr -} - -// UpdateAsync updates a VirtualMachine asynchronously -func (c *Client) UpdateAsync(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachineUpdate, source string) (*azure.Future, *retry.Error) { - mc := metrics.NewMetricContext("vm", "updateasync", resourceGroupName, c.subscriptionID, source) - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(true, "VMUpdateAsync") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMUpdateAsync", "client throttled", c.RetryAfterWriter) - return nil, rerr - } - - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - vmResourceType, - VMName, - ) - - future, rerr := c.armClient.PatchResourceAsync(ctx, resourceID, parameters) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return nil, rerr - } - - return future, nil -} - -// WaitForUpdateResult waits for the response of the update request -func (c *Client) WaitForUpdateResult(ctx context.Context, future *azure.Future, resourceGroupName, source string) (*compute.VirtualMachine, *retry.Error) { - mc := metrics.NewMetricContext("vm", "wait_for_update_result", resourceGroupName, c.subscriptionID, source) - response, err := c.armClient.WaitForAsyncOperationResult(ctx, future, "VMWaitForUpdateResult") - mc.Observe(retry.NewErrorOrNil(false, err)) - defer c.armClient.CloseResponse(ctx, response) - - if err != nil { - if response != nil { - klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', response code %d", err.Error(), response.StatusCode) - } else { - klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', no response", err.Error()) - } - return nil, retry.GetError(response, err) - } - if response != nil && response.StatusCode != http.StatusNoContent { - result, rerr := c.updateResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in WaitForAsyncOperationResult updateResponder: '%s'", rerr.Error()) - } - - return result, rerr - } - - result := &compute.VirtualMachine{} - result.Response = autorest.Response{Response: response} - return result, nil -} - -// updateVM updates a VirtualMachine. -func (c *Client) updateVM(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachineUpdate, _ string) (*compute.VirtualMachine, *retry.Error) { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - vmResourceType, - VMName, - ) - - response, rerr := c.armClient.PatchResource(ctx, resourceID, parameters) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vm.put.request", resourceID, rerr.Error()) - return nil, rerr - } - - if response != nil && response.StatusCode != http.StatusNoContent { - result, rerr := c.updateResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vm.put.respond", resourceID, rerr.Error()) - } - return result, rerr - } - - result := &compute.VirtualMachine{} - result.Response = autorest.Response{Response: response} - return result, nil -} - -func (c *Client) updateResponder(resp *http.Response) (*compute.VirtualMachine, *retry.Error) { - result := &compute.VirtualMachine{} - err := autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return result, retry.GetError(resp, err) -} - -func (c *Client) listResponder(resp *http.Response) (result compute.VirtualMachineListResult, err error) { - err = autorest.Respond( - resp, - autorest.ByIgnoring(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing(), - ) - result.Response = autorest.Response{Response: resp} - return -} - -// vmListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (c *Client) vmListResultPreparer(ctx context.Context, vmlr compute.VirtualMachineListResult) (*http.Request, error) { - if vmlr.NextLink == nil || len(ptr.Deref(vmlr.NextLink, "")) < 1 { - return nil, nil - } - - decorators := []autorest.PrepareDecorator{ - autorest.WithBaseURL(ptr.Deref(vmlr.NextLink, "")), - } - return c.armClient.PrepareGetRequest(ctx, decorators...) -} - -// listNextResults retrieves the next set of results, if any. -func (c *Client) listNextResults(ctx context.Context, lastResults compute.VirtualMachineListResult) (result compute.VirtualMachineListResult, err error) { - req, err := c.vmListResultPreparer(ctx, lastResults) - if err != nil { - return result, autorest.NewErrorWithError(err, "vmclient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - - resp, rerr := c.armClient.Send(ctx, req) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(rerr.Error(), "vmclient", "listNextResults", resp, "Failure sending next results request") - } - - result, err = c.listResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "vmclient", "listNextResults", resp, "Failure responding to next results request") - } - - return -} - -// VirtualMachineListResultPage contains a page of VirtualMachine values. -type VirtualMachineListResultPage struct { - fn func(context.Context, compute.VirtualMachineListResult) (compute.VirtualMachineListResult, error) - vmlr compute.VirtualMachineListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualMachineListResultPage) NextWithContext(ctx context.Context) (err error) { - next, err := page.fn(ctx, page.vmlr) - if err != nil { - return err - } - page.vmlr = next - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualMachineListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualMachineListResultPage) NotDone() bool { - return !page.vmlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualMachineListResultPage) Response() compute.VirtualMachineListResult { - return page.vmlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualMachineListResultPage) Values() []compute.VirtualMachine { - if page.vmlr.IsEmpty() { - return nil - } - return *page.vmlr.Value -} - -// CreateOrUpdate creates or updates a VirtualMachine. -func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachine, source string) *retry.Error { - mc := metrics.NewMetricContext("vm", "create_or_update", resourceGroupName, c.subscriptionID, source) - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "VMCreateOrUpdate") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMCreateOrUpdate", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.createOrUpdateVM(ctx, resourceGroupName, VMName, parameters, source) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// createOrUpdateVM creates or updates a VirtualMachine. -func (c *Client) createOrUpdateVM(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachine, _ string) *retry.Error { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - vmResourceType, - VMName, - ) - - response, rerr := c.armClient.PutResource(ctx, resourceID, parameters) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vm.put.request", resourceID, rerr.Error()) - return rerr - } - - if response != nil && response.StatusCode != http.StatusNoContent { - _, rerr = c.createOrUpdateResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vm.put.respond", resourceID, rerr.Error()) - return rerr - } - } - - return nil -} - -func (c *Client) createOrUpdateResponder(resp *http.Response) (*compute.VirtualMachine, *retry.Error) { - result := &compute.VirtualMachine{} - err := autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return result, retry.GetError(resp, err) -} - -// Delete deletes a VirtualMachine. -func (c *Client) Delete(ctx context.Context, resourceGroupName string, VMName string) *retry.Error { - mc := metrics.NewMetricContext("vm", "delete", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "VMDelete") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMDelete", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.deleteVM(ctx, resourceGroupName, VMName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// deleteVM deletes a VirtualMachine. -func (c *Client) deleteVM(ctx context.Context, resourceGroupName string, VMName string) *retry.Error { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - vmResourceType, - VMName, - ) - - return c.armClient.DeleteResource(ctx, resourceID) -} diff --git a/pkg/azureclients/vmclient/azure_vmclient_test.go b/pkg/azureclients/vmclient/azure_vmclient_test.go deleted file mode 100644 index 106e0ed14d..0000000000 --- a/pkg/azureclients/vmclient/azure_vmclient_test.go +++ /dev/null @@ -1,1244 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package vmclient - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "testing" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/stretchr/testify/assert" - - "go.uber.org/mock/gomock" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient/mockarmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - testResourceID = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm1" - testResourcePrefix = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines" - testSubscriptionLevelResourcePrefix = "/subscriptions/subscriptionID/providers/Microsoft.Compute/virtualMachines" -) - -func TestNew(t *testing.T) { - config := &azclients.ClientConfig{ - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - vmClient := New(config) - assert.Equal(t, "sub", vmClient.subscriptionID) - assert.NotEmpty(t, vmClient.rateLimiterReader) - assert.NotEmpty(t, vmClient.rateLimiterWriter) -} - -func TestNewAzureStack(t *testing.T) { - config := &azclients.ClientConfig{ - CloudName: "AZURESTACKCLOUD", - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - vmClient := New(config) - assert.Equal(t, "AZURESTACKCLOUD", vmClient.cloudName) - assert.Equal(t, "sub", vmClient.subscriptionID) -} - -func TestGet(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "InstanceView").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - expected := compute.VirtualMachine{Response: autorest.Response{Response: response}} - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.Get(context.TODO(), "rg", "vm1", "InstanceView") - assert.Equal(t, expected, result) - assert.Nil(t, rerr) -} - -func TestGetNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "VMGet"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithNeverRateLimiter(armClient) - expected := compute.VirtualMachine{} - result, rerr := vmClient.Get(context.TODO(), "rg", "vm1", "InstanceView") - assert.Equal(t, expected, result) - assert.Equal(t, vmGetErr, rerr) -} - -func TestGetRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMGet", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithRetryAfterReader(armClient) - expected := compute.VirtualMachine{} - result, rerr := vmClient.Get(context.TODO(), "rg", "vm1", "InstanceView") - assert.Equal(t, expected, result) - assert.Equal(t, vmGetErr, rerr) -} - -func TestGetNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "InstanceView").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - expectedVM := compute.VirtualMachine{Response: autorest.Response{}} - result, rerr := vmClient.Get(context.TODO(), "rg", "vm1", "InstanceView") - assert.Equal(t, expectedVM, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestGetInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "InstanceView").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - expectedVM := compute.VirtualMachine{Response: autorest.Response{}} - result, rerr := vmClient.Get(context.TODO(), "rg", "vm1", "InstanceView") - assert.Equal(t, expectedVM, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestGetThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "InstanceView").Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.Get(context.TODO(), "rg", "vm1", "InstanceView") - assert.Empty(t, result) - assert.Equal(t, throttleErr, rerr) -} - -func TestList(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmList := []compute.VirtualMachine{getTestVM("vm1"), getTestVM("vm1"), getTestVM("vm1")} - responseBody, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.List(context.TODO(), "rg") - assert.Nil(t, rerr) - assert.Equal(t, 3, len(result)) -} - -func TestListWithInstanceView(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmList := []compute.VirtualMachine{getTestVMWithInstanceView("vm1"), getTestVMWithInstanceView("vm2")} - responseBody, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList}) - assert.NoError(t, err) - - queryparams := map[string]interface{}{ - "$expand": "instanceView", - } - armClient.EXPECT().GetResourceWithQueries(gomock.Any(), testResourcePrefix, queryparams).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.ListWithInstanceView(context.TODO(), "rg") - assert.Nil(t, rerr) - assert.Equal(t, 2, len(result)) -} - -func TestListNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - expected := []compute.VirtualMachine{} - result, rerr := vmClient.List(context.TODO(), "rg") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestListInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - expected := []compute.VirtualMachine{} - result, rerr := vmClient.List(context.TODO(), "rg") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestListThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.List(context.TODO(), "rg") - assert.Empty(t, result) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestListWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmList := []compute.VirtualMachine{getTestVM("vm1"), getTestVM("vm2"), getTestVM("vm3")} - responseBody, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.List(context.TODO(), "rg") - assert.NotNil(t, rerr) - assert.Equal(t, 0, len(result)) -} - -func TestListWithNextPage(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmList := []compute.VirtualMachine{getTestVM("vm1"), getTestVM("vm2"), getTestVM("vm3")} - partialResponse, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList, NextLink: ptr.To("nextLink")}) - assert.NoError(t, err) - pagedResponse, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList}) - assert.NoError(t, err) - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(&http.Request{}, nil) - armClient.EXPECT().Send(gomock.Any(), gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(pagedResponse)), - }, nil) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(partialResponse)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(2) - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.List(context.TODO(), "rg") - assert.Nil(t, rerr) - assert.Equal(t, 6, len(result)) -} - -func TestListNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "VMList"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithNeverRateLimiter(armClient) - result, rerr := vmClient.List(context.TODO(), "rg") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, vmListErr, rerr) -} - -func TestListRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMList", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithRetryAfterReader(armClient) - result, rerr := vmClient.List(context.TODO(), "rg") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, vmListErr, rerr) -} - -func TestListNextResultsMultiPages(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - name string - prepareErr error - sendErr *retry.Error - expectedErrMsg string - }{ - { - name: "testlistNextResultsSuccessful", - prepareErr: nil, - sendErr: nil, - }, - { - name: "testPrepareGetRequestError", - prepareErr: fmt.Errorf("error"), - expectedErrMsg: "Failure preparing next results request", - }, - { - name: "testSendError", - sendErr: &retry.Error{RawError: fmt.Errorf("error")}, - expectedErrMsg: "Failure sending next results request", - }, - } - - lastResult := compute.VirtualMachineListResult{ - NextLink: ptr.To("next"), - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - vmssClient := getTestVMClient(armClient) - result, err := vmssClient.listNextResults(context.TODO(), lastResult) - if err != nil { - detailedErr := &autorest.DetailedError{} - assert.True(t, errors.As(err, detailedErr)) - assert.Equal(t, detailedErr.Message, test.expectedErrMsg) - } else { - assert.NoError(t, err) - } - - if test.prepareErr != nil { - assert.Empty(t, result) - } else { - assert.NotEmpty(t, result) - } - } -} - -func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - name string - prepareErr error - sendErr *retry.Error - }{ - { - name: "testListResponderError", - prepareErr: nil, - sendErr: nil, - }, - { - name: "testSendError", - sendErr: &retry.Error{RawError: fmt.Errorf("error")}, - }, - } - - lastResult := compute.VirtualMachineListResult{ - NextLink: ptr.To("next"), - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewBuffer([]byte(`{"foo":"bar"}`))), - } - expected := compute.VirtualMachineListResult{} - expected.Response = autorest.Response{Response: response} - vmssClient := getTestVMClient(armClient) - result, err := vmssClient.listNextResults(context.TODO(), lastResult) - assert.Error(t, err) - if test.sendErr != nil { - assert.NotEqual(t, expected, result) - } else { - assert.Equal(t, expected, result) - } - } -} - -func TestListVmssFlexVMsWithoutInstanceView(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmList := []compute.VirtualMachine{getTestVM("vm1"), getTestVM("vm1"), getTestVM("vm1")} - responseBody, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList}) - assert.NoError(t, err) - armClient.EXPECT().GetResourceWithQueries(gomock.Any(), testSubscriptionLevelResourcePrefix, gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.ListVmssFlexVMsWithoutInstanceView(context.TODO(), "vmssFlexID") - assert.Nil(t, rerr) - assert.Equal(t, 3, len(result)) -} - -func TestListVmssFlexVMsWithoutInstanceViewNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithQueries(gomock.Any(), testSubscriptionLevelResourcePrefix, gomock.Any()).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - expected := []compute.VirtualMachine{} - result, rerr := vmClient.ListVmssFlexVMsWithoutInstanceView(context.TODO(), "vmssFlexID") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestListVmssFlexVMsWithoutInstanceViewNInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithQueries(gomock.Any(), testSubscriptionLevelResourcePrefix, gomock.Any()).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - expected := []compute.VirtualMachine{} - result, rerr := vmClient.ListVmssFlexVMsWithoutInstanceView(context.TODO(), "vmssFlexID") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestListVmssFlexVMsWithoutInstanceViewThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient.EXPECT().GetResourceWithQueries(gomock.Any(), testSubscriptionLevelResourcePrefix, gomock.Any()).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.ListVmssFlexVMsWithoutInstanceView(context.TODO(), "vmssFlexID") - assert.Empty(t, result) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestListVmssFlexVMsWithoutInstanceViewWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmList := []compute.VirtualMachine{getTestVM("vm1"), getTestVM("vm2"), getTestVM("vm3")} - responseBody, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList}) - assert.NoError(t, err) - armClient.EXPECT().GetResourceWithQueries(gomock.Any(), testSubscriptionLevelResourcePrefix, gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.ListVmssFlexVMsWithoutInstanceView(context.TODO(), "vmssFlexID") - assert.NotNil(t, rerr) - assert.Equal(t, 0, len(result)) -} - -func TestListVmssFlexVMsWithoutInstanceViewWithNextPage(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmList := []compute.VirtualMachine{getTestVM("vm1"), getTestVM("vm2"), getTestVM("vm3")} - partialResponse, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList, NextLink: ptr.To("nextLink")}) - assert.NoError(t, err) - pagedResponse, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList}) - assert.NoError(t, err) - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(&http.Request{}, nil) - armClient.EXPECT().Send(gomock.Any(), gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(pagedResponse)), - }, nil) - armClient.EXPECT().GetResourceWithQueries(gomock.Any(), testSubscriptionLevelResourcePrefix, gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(partialResponse)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(2) - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.ListVmssFlexVMsWithoutInstanceView(context.TODO(), "vmssFlexID") - assert.Nil(t, rerr) - assert.Equal(t, 6, len(result)) -} - -func TestListVmssFlexVMsWithoutInstanceViewNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "VMList"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithNeverRateLimiter(armClient) - result, rerr := vmClient.ListVmssFlexVMsWithoutInstanceView(context.TODO(), "vmssFlexID") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, vmListErr, rerr) -} - -func TestListVmssFlexVMsWithoutInstanceViewRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMList", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithRetryAfterReader(armClient) - result, rerr := vmClient.ListVmssFlexVMsWithoutInstanceView(context.TODO(), "vmssFlexID") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, vmListErr, rerr) -} - -func TestListVmssFlexVMsWithOnlyInstanceView(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmList := []compute.VirtualMachine{getTestVM("vm1"), getTestVM("vm1"), getTestVM("vm1")} - responseBody, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList}) - assert.NoError(t, err) - armClient.EXPECT().GetResourceWithQueries(gomock.Any(), testSubscriptionLevelResourcePrefix, gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.ListVmssFlexVMsWithOnlyInstanceView(context.TODO(), "vmssFlexID") - assert.Nil(t, rerr) - assert.Equal(t, 3, len(result)) -} - -func TestListVmssFlexVMsWithOnlyInstanceViewNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithQueries(gomock.Any(), testSubscriptionLevelResourcePrefix, gomock.Any()).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - expected := []compute.VirtualMachine{} - result, rerr := vmClient.ListVmssFlexVMsWithOnlyInstanceView(context.TODO(), "vmssFlexID") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestListVmssFlexVMsWithOnlyInstanceViewNInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithQueries(gomock.Any(), testSubscriptionLevelResourcePrefix, gomock.Any()).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - expected := []compute.VirtualMachine{} - result, rerr := vmClient.ListVmssFlexVMsWithOnlyInstanceView(context.TODO(), "vmssFlexID") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestListVmssFlexVMsWithOnlyInstanceViewThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient.EXPECT().GetResourceWithQueries(gomock.Any(), testSubscriptionLevelResourcePrefix, gomock.Any()).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.ListVmssFlexVMsWithOnlyInstanceView(context.TODO(), "vmssFlexID") - assert.Empty(t, result) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestListVmssFlexVMsWithOnlyInstanceViewWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmList := []compute.VirtualMachine{getTestVM("vm1"), getTestVM("vm2"), getTestVM("vm3")} - responseBody, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList}) - assert.NoError(t, err) - armClient.EXPECT().GetResourceWithQueries(gomock.Any(), testSubscriptionLevelResourcePrefix, gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.ListVmssFlexVMsWithOnlyInstanceView(context.TODO(), "vmssFlexID") - assert.NotNil(t, rerr) - assert.Equal(t, 0, len(result)) -} - -func TestListVmssFlexVMsWithOnlyInstanceViewWithNextPage(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmList := []compute.VirtualMachine{getTestVM("vm1"), getTestVM("vm2"), getTestVM("vm3")} - partialResponse, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList, NextLink: ptr.To("nextLink")}) - assert.NoError(t, err) - pagedResponse, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList}) - assert.NoError(t, err) - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(&http.Request{}, nil) - armClient.EXPECT().Send(gomock.Any(), gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(pagedResponse)), - }, nil) - armClient.EXPECT().GetResourceWithQueries(gomock.Any(), testSubscriptionLevelResourcePrefix, gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(partialResponse)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(2) - vmClient := getTestVMClient(armClient) - result, rerr := vmClient.ListVmssFlexVMsWithOnlyInstanceView(context.TODO(), "vmssFlexID") - assert.Nil(t, rerr) - assert.Equal(t, 6, len(result)) -} - -func TestListVmssFlexVMsWithOnlyInstanceViewNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "VMList"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithNeverRateLimiter(armClient) - result, rerr := vmClient.ListVmssFlexVMsWithOnlyInstanceView(context.TODO(), "vmssFlexID") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, vmListErr, rerr) -} - -func TestListVmssFlexVMsWithOnlyInstanceViewRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMList", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithRetryAfterReader(armClient) - result, rerr := vmClient.ListVmssFlexVMsWithOnlyInstanceView(context.TODO(), "vmssFlexID") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, vmListErr, rerr) -} - -func TestUpdate(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - testVM := compute.VirtualMachineUpdate{} - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PatchResource(gomock.Any(), testResourceID, testVM).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - _, rerr := vmClient.Update(context.TODO(), "rg", "vm1", testVM, "test") - assert.Nil(t, rerr) -} - -func TestUpdateAsync(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - testVM := compute.VirtualMachineUpdate{} - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PatchResourceAsync(gomock.Any(), testResourceID, testVM).Times(1) - - vmClient := getTestVMClient(armClient) - future, rerr := vmClient.UpdateAsync(context.TODO(), "rg", "vm1", testVM, "test") - assert.Nil(t, future) - assert.Nil(t, rerr) -} - -func TestWaitForUpdateResult(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - preemptErr := fmt.Errorf("operation execution has been preempted by a more recent operation") - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - - tests := []struct { - name string - response *http.Response - responseErr error - expectedResult *retry.Error - }{ - { - name: "Success", - response: response, - responseErr: nil, - expectedResult: nil, - }, - { - name: "Success with nil response", - response: nil, - responseErr: nil, - expectedResult: nil, - }, - { - name: "Failed", - response: response, - responseErr: preemptErr, - expectedResult: retry.GetError(response, preemptErr), - }, - { - name: "Failed with nil response", - response: nil, - responseErr: preemptErr, - expectedResult: retry.GetError(nil, preemptErr), - }, - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().WaitForAsyncOperationResult(gomock.Any(), gomock.Any(), "VMWaitForUpdateResult").Return(test.response, test.responseErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - _, err := vmClient.WaitForUpdateResult(context.TODO(), &azure.Future{}, "rg", "test") - assert.Equal(t, err, test.expectedResult) - } -} - -func TestUpdateWithUpdateResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - testVM := compute.VirtualMachineUpdate{} - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PatchResource(gomock.Any(), testResourceID, testVM).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - _, rerr := vmClient.Update(context.TODO(), "rg", "vm1", testVM, "test") - assert.NotNil(t, rerr) -} - -func TestUpdateNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmUpdateErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "write", "VMUpdate"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithNeverRateLimiter(armClient) - testVM := compute.VirtualMachineUpdate{} - _, rerr := vmClient.Update(context.TODO(), "rg", "vm1", testVM, "test") - assert.NotNil(t, rerr) - assert.Equal(t, vmUpdateErr, rerr) -} - -func TestUpdateRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmUpdateErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMUpdate", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - testVM := compute.VirtualMachineUpdate{} - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithRetryAfterReader(armClient) - _, rerr := vmClient.Update(context.TODO(), "rg", "vm1", testVM, "test") - assert.NotNil(t, rerr) - assert.Equal(t, vmUpdateErr, rerr) -} - -func TestUpdateThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - testVM := compute.VirtualMachineUpdate{} - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PatchResource(gomock.Any(), testResourceID, testVM).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - _, rerr := vmClient.Update(context.TODO(), "rg", "vm1", testVM, "test") - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestCreateOrUpdate(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - testVM := getTestVM("vm1") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(testVM.ID, ""), testVM).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - rerr := vmClient.CreateOrUpdate(context.TODO(), "rg", "vm1", testVM, "test") - assert.Nil(t, rerr) -} - -func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - testVM := getTestVM("vm1") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(testVM.ID, ""), testVM).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - rerr := vmClient.CreateOrUpdate(context.TODO(), "rg", "vm1", testVM, "test") - assert.NotNil(t, rerr) -} - -func TestCreateOrUpdateNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmCreateOrUpdateErr := retry.GetRateLimitError(true, "VMCreateOrUpdate") - - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithNeverRateLimiter(armClient) - testVM := getTestVM("vm1") - rerr := vmClient.CreateOrUpdate(context.TODO(), "rg", "vm1", testVM, "test") - assert.NotNil(t, rerr) - assert.Equal(t, vmCreateOrUpdateErr, rerr) -} - -func TestCreateOrUpdateRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmCreateOrUpdateErr := retry.GetThrottlingError("VMCreateOrUpdate", "client throttled", getFutureTime()) - - testVM := getTestVM("vm1") - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithRetryAfterReader(armClient) - rerr := vmClient.CreateOrUpdate(context.TODO(), "rg", "vm1", testVM, "test") - assert.NotNil(t, rerr) - assert.Equal(t, vmCreateOrUpdateErr, rerr) -} - -func TestCreateOrUpdateThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - testVM := getTestVM("vm1") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(testVM.ID, ""), testVM).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmClient := getTestVMClient(armClient) - rerr := vmClient.CreateOrUpdate(context.TODO(), "rg", "vm1", testVM, "test") - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestDelete(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - r := getTestVM("vm1") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().DeleteResource(gomock.Any(), ptr.Deref(r.ID, "")).Return(nil).Times(1) - - client := getTestVMClient(armClient) - rerr := client.Delete(context.TODO(), "rg", "vm1") - assert.Nil(t, rerr) -} - -func TestDeleteNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmDeleteErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "write", "VMDelete"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithNeverRateLimiter(armClient) - rerr := vmClient.Delete(context.TODO(), "rg", "vm1") - assert.NotNil(t, rerr) - assert.Equal(t, vmDeleteErr, rerr) -} - -func TestDeleteRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmDeleteErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMDelete", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMClientWithRetryAfterReader(armClient) - rerr := vmClient.Delete(context.TODO(), "rg", "vm1") - assert.NotNil(t, rerr) - assert.Equal(t, vmDeleteErr, rerr) -} - -func TestDeleteThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - testVM := getTestVM("vm1") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().DeleteResource(gomock.Any(), ptr.Deref(testVM.ID, "")).Return(throttleErr).Times(1) - - vmClient := getTestVMClient(armClient) - rerr := vmClient.Delete(context.TODO(), "rg", "vm1") - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func getTestVM(vmName string) compute.VirtualMachine { - resourceID := fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/%s", vmName) - return compute.VirtualMachine{ - ID: ptr.To(resourceID), - Name: ptr.To(vmName), - Location: ptr.To("eastus"), - } -} - -func getTestVMWithInstanceView(vmName string) compute.VirtualMachine { - resourceID := fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/%s", vmName) - vm := compute.VirtualMachine{ - ID: ptr.To(resourceID), - Name: ptr.To(vmName), - Location: ptr.To("eastus"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ - InstanceView: &compute.VirtualMachineInstanceView{ - Statuses: &[]compute.InstanceViewStatus{ - { - Code: ptr.To("PowerState/running"), - }, - }, - }, - }, - } - return vm -} - -func getTestVMClient(armClient armclient.Interface) *Client { - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(&azclients.RateLimitConfig{}) - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestVMClientWithNeverRateLimiter(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeNeverRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeNeverRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestVMClientWithRetryAfterReader(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeAlwaysRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeAlwaysRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - RetryAfterReader: getFutureTime(), - RetryAfterWriter: getFutureTime(), - } -} - -func getFutureTime() time.Time { - return time.Unix(3000000000, 0) -} diff --git a/pkg/azureclients/vmclient/doc.go b/pkg/azureclients/vmclient/doc.go deleted file mode 100644 index 23a0987513..0000000000 --- a/pkg/azureclients/vmclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package vmclient implements the client for VirtualMachines. -package vmclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient" diff --git a/pkg/azureclients/vmclient/interface.go b/pkg/azureclients/vmclient/interface.go deleted file mode 100644 index 1fb6dae9c0..0000000000 --- a/pkg/azureclients/vmclient/interface.go +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package vmclient - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/azure" - - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - // APIVersion is the API version for VirtualMachine. - APIVersion = "2022-03-01" - // AzureStackCloudAPIVersion is the API version for Azure Stack - AzureStackCloudAPIVersion = "2017-12-01" - // AzureStackCloudName is the cloud name of Azure Stack - AzureStackCloudName = "AZURESTACKCLOUD" -) - -// Interface is the client interface for VirtualMachines. -// Don't forget to run "hack/update-mock-clients.sh" command to generate the mock client. -type Interface interface { - // Get gets a VirtualMachine. - Get(ctx context.Context, resourceGroupName string, VMName string, expand compute.InstanceViewTypes) (compute.VirtualMachine, *retry.Error) - - // List gets a list of VirtualMachines in the resourceGroupName. - List(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachine, *retry.Error) - - // ListWithInstanceView gets a list of VirtualMachines in the resourceGroupName with InstanceView. - ListWithInstanceView(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachine, *retry.Error) - - // ListVmssFlexVMsWithoutInstanceView gets a list of VirtualMachine in the VMSS Flex without InstanceView. - ListVmssFlexVMsWithoutInstanceView(ctx context.Context, vmssFlexID string) ([]compute.VirtualMachine, *retry.Error) - - // ListVmssFlexVMsWithOnlyInstanceView gets a list of VirtualMachine in the VMSS Flex with only InstanceView. - ListVmssFlexVMsWithOnlyInstanceView(ctx context.Context, vmssFlexID string) ([]compute.VirtualMachine, *retry.Error) - - // CreateOrUpdate creates or updates a VirtualMachine. - CreateOrUpdate(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachine, source string) *retry.Error - - // Update updates a VirtualMachine. - Update(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachineUpdate, source string) (*compute.VirtualMachine, *retry.Error) - - // UpdateAsync updates a VirtualMachine asynchronously - UpdateAsync(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachineUpdate, source string) (*azure.Future, *retry.Error) - - // WaitForUpdateResult waits for the response of the update request - WaitForUpdateResult(ctx context.Context, future *azure.Future, resourceGroupName, source string) (*compute.VirtualMachine, *retry.Error) - - // Delete deletes a VirtualMachine. - Delete(ctx context.Context, resourceGroupName string, VMName string) *retry.Error -} diff --git a/pkg/azureclients/vmclient/mockvmclient/doc.go b/pkg/azureclients/vmclient/mockvmclient/doc.go deleted file mode 100644 index 58659d2911..0000000000 --- a/pkg/azureclients/vmclient/mockvmclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package mockvmclient implements the mock client for VirtualMachines. -package mockvmclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" diff --git a/pkg/azureclients/vmclient/mockvmclient/interface.go b/pkg/azureclients/vmclient/mockvmclient/interface.go deleted file mode 100644 index e86e26e6ab..0000000000 --- a/pkg/azureclients/vmclient/mockvmclient/interface.go +++ /dev/null @@ -1,208 +0,0 @@ -// /* -// Copyright The Kubernetes Authors. -// -// 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 MockGen. DO NOT EDIT. -// Source: pkg/azureclients/vmclient/interface.go -// -// Generated by this command: -// -// mockgen -copyright_file=/home/runner/work/cloud-provider-azure/cloud-provider-azure/hack/boilerplate/boilerplate.generatego.txt -source=pkg/azureclients/vmclient/interface.go -package=mockvmclient Interface -// - -// Package mockvmclient is a generated GoMock package. -package mockvmclient - -import ( - context "context" - reflect "reflect" - - compute "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - azure "github.com/Azure/go-autorest/autorest/azure" - gomock "go.uber.org/mock/gomock" - retry "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -// MockInterface is a mock of Interface interface. -type MockInterface struct { - ctrl *gomock.Controller - recorder *MockInterfaceMockRecorder -} - -// MockInterfaceMockRecorder is the mock recorder for MockInterface. -type MockInterfaceMockRecorder struct { - mock *MockInterface -} - -// NewMockInterface creates a new mock instance. -func NewMockInterface(ctrl *gomock.Controller) *MockInterface { - mock := &MockInterface{ctrl: ctrl} - mock.recorder = &MockInterfaceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { - return m.recorder -} - -// CreateOrUpdate mocks base method. -func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, VMName string, parameters compute.VirtualMachine, source string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrUpdate", ctx, resourceGroupName, VMName, parameters, source) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// CreateOrUpdate indicates an expected call of CreateOrUpdate. -func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, VMName, parameters, source any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdate", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, VMName, parameters, source) -} - -// Delete mocks base method. -func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, VMName string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Delete", ctx, resourceGroupName, VMName) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// Delete indicates an expected call of Delete. -func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, VMName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, VMName) -} - -// Get mocks base method. -func (m *MockInterface) Get(ctx context.Context, resourceGroupName, VMName string, expand compute.InstanceViewTypes) (compute.VirtualMachine, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", ctx, resourceGroupName, VMName, expand) - ret0, _ := ret[0].(compute.VirtualMachine) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, VMName, expand any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, VMName, expand) -} - -// List mocks base method. -func (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachine, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "List", ctx, resourceGroupName) - ret0, _ := ret[0].([]compute.VirtualMachine) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// List indicates an expected call of List. -func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName) -} - -// ListVmssFlexVMsWithOnlyInstanceView mocks base method. -func (m *MockInterface) ListVmssFlexVMsWithOnlyInstanceView(ctx context.Context, vmssFlexID string) ([]compute.VirtualMachine, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListVmssFlexVMsWithOnlyInstanceView", ctx, vmssFlexID) - ret0, _ := ret[0].([]compute.VirtualMachine) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// ListVmssFlexVMsWithOnlyInstanceView indicates an expected call of ListVmssFlexVMsWithOnlyInstanceView. -func (mr *MockInterfaceMockRecorder) ListVmssFlexVMsWithOnlyInstanceView(ctx, vmssFlexID any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListVmssFlexVMsWithOnlyInstanceView", reflect.TypeOf((*MockInterface)(nil).ListVmssFlexVMsWithOnlyInstanceView), ctx, vmssFlexID) -} - -// ListVmssFlexVMsWithoutInstanceView mocks base method. -func (m *MockInterface) ListVmssFlexVMsWithoutInstanceView(ctx context.Context, vmssFlexID string) ([]compute.VirtualMachine, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListVmssFlexVMsWithoutInstanceView", ctx, vmssFlexID) - ret0, _ := ret[0].([]compute.VirtualMachine) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// ListVmssFlexVMsWithoutInstanceView indicates an expected call of ListVmssFlexVMsWithoutInstanceView. -func (mr *MockInterfaceMockRecorder) ListVmssFlexVMsWithoutInstanceView(ctx, vmssFlexID any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListVmssFlexVMsWithoutInstanceView", reflect.TypeOf((*MockInterface)(nil).ListVmssFlexVMsWithoutInstanceView), ctx, vmssFlexID) -} - -// ListWithInstanceView mocks base method. -func (m *MockInterface) ListWithInstanceView(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachine, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListWithInstanceView", ctx, resourceGroupName) - ret0, _ := ret[0].([]compute.VirtualMachine) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// ListWithInstanceView indicates an expected call of ListWithInstanceView. -func (mr *MockInterfaceMockRecorder) ListWithInstanceView(ctx, resourceGroupName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWithInstanceView", reflect.TypeOf((*MockInterface)(nil).ListWithInstanceView), ctx, resourceGroupName) -} - -// Update mocks base method. -func (m *MockInterface) Update(ctx context.Context, resourceGroupName, VMName string, parameters compute.VirtualMachineUpdate, source string) (*compute.VirtualMachine, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Update", ctx, resourceGroupName, VMName, parameters, source) - ret0, _ := ret[0].(*compute.VirtualMachine) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// Update indicates an expected call of Update. -func (mr *MockInterfaceMockRecorder) Update(ctx, resourceGroupName, VMName, parameters, source any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockInterface)(nil).Update), ctx, resourceGroupName, VMName, parameters, source) -} - -// UpdateAsync mocks base method. -func (m *MockInterface) UpdateAsync(ctx context.Context, resourceGroupName, VMName string, parameters compute.VirtualMachineUpdate, source string) (*azure.Future, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateAsync", ctx, resourceGroupName, VMName, parameters, source) - ret0, _ := ret[0].(*azure.Future) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// UpdateAsync indicates an expected call of UpdateAsync. -func (mr *MockInterfaceMockRecorder) UpdateAsync(ctx, resourceGroupName, VMName, parameters, source any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateAsync", reflect.TypeOf((*MockInterface)(nil).UpdateAsync), ctx, resourceGroupName, VMName, parameters, source) -} - -// WaitForUpdateResult mocks base method. -func (m *MockInterface) WaitForUpdateResult(ctx context.Context, future *azure.Future, resourceGroupName, source string) (*compute.VirtualMachine, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WaitForUpdateResult", ctx, future, resourceGroupName, source) - ret0, _ := ret[0].(*compute.VirtualMachine) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// WaitForUpdateResult indicates an expected call of WaitForUpdateResult. -func (mr *MockInterfaceMockRecorder) WaitForUpdateResult(ctx, future, resourceGroupName, source any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitForUpdateResult", reflect.TypeOf((*MockInterface)(nil).WaitForUpdateResult), ctx, future, resourceGroupName, source) -} diff --git a/pkg/azureclients/vmsizeclient/azure_vmsizeclient.go b/pkg/azureclients/vmsizeclient/azure_vmsizeclient.go deleted file mode 100644 index bf9510985e..0000000000 --- a/pkg/azureclients/vmsizeclient/azure_vmsizeclient.go +++ /dev/null @@ -1,144 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package vmsizeclient - -import ( - "context" - "fmt" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/klog/v2" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/metrics" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -var _ Interface = &Client{} - -// Client implements VirtualMachineSize client Interface. -type Client struct { - armClient armclient.Interface - subscriptionID string - cloudName string - - // Rate limiting configures. - rateLimiterReader flowcontrol.RateLimiter - rateLimiterWriter flowcontrol.RateLimiter - - // ARM throttling configures. - RetryAfterReader time.Time - RetryAfterWriter time.Time -} - -// New creates a new VirtualMachineSize client with ratelimiting. -func New(config *azclients.ClientConfig) *Client { - baseURI := config.ResourceManagerEndpoint - authorizer := config.Authorizer - apiVersion := APIVersion - if strings.EqualFold(config.CloudName, AzureStackCloudName) && !config.DisableAzureStackCloud { - apiVersion = AzureStackCloudAPIVersion - } - armClient := armclient.New(authorizer, *config, baseURI, apiVersion) - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig) - - if azclients.RateLimitEnabled(config.RateLimitConfig) { - klog.V(2).Infof("Azure VirtualMachineSizesClient (read ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPS, - config.RateLimitConfig.CloudProviderRateLimitBucket) - klog.V(2).Infof("Azure VirtualMachineSizesClient (write ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPSWrite, - config.RateLimitConfig.CloudProviderRateLimitBucketWrite) - } - - client := &Client{ - armClient: armClient, - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - subscriptionID: config.SubscriptionID, - cloudName: config.CloudName, - } - - return client -} - -// List gets compute.VirtualMachineSizeListResult. -func (c *Client) List(ctx context.Context, location string) (compute.VirtualMachineSizeListResult, *retry.Error) { - mc := metrics.NewMetricContext("vmsizes", "list", "", c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return compute.VirtualMachineSizeListResult{}, retry.GetRateLimitError(false, "VMSizesList") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSizesList", "client throttled", c.RetryAfterReader) - return compute.VirtualMachineSizeListResult{}, rerr - } - - result, rerr := c.listVirtualMachineSizes(ctx, location) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// listVirtualMachineSizes gets compute.VirtualMachineSizeListResult. -func (c *Client) listVirtualMachineSizes(ctx context.Context, location string) (compute.VirtualMachineSizeListResult, *retry.Error) { - resourceID := fmt.Sprintf("/subscriptions/%s/providers/Microsoft.Compute/locations/%s/vmSizes", - autorest.Encode("path", c.subscriptionID), - autorest.Encode("path", location), - ) - - result := compute.VirtualMachineSizeListResult{} - response, rerr := c.armClient.GetResource(ctx, resourceID) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmsize.list.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmsize.list.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} diff --git a/pkg/azureclients/vmsizeclient/azure_vmsizeclient_test.go b/pkg/azureclients/vmsizeclient/azure_vmsizeclient_test.go deleted file mode 100644 index a5abe8d1bb..0000000000 --- a/pkg/azureclients/vmsizeclient/azure_vmsizeclient_test.go +++ /dev/null @@ -1,253 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package vmsizeclient - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "testing" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest" - "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient/mockarmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - testResourceID = "/subscriptions/subscriptionID/providers/Microsoft.Compute/locations/eastus/vmSizes" -) - -func TestNew(t *testing.T) { - config := &azclients.ClientConfig{ - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - vmsizeClient := New(config) - assert.Equal(t, "sub", vmsizeClient.subscriptionID) - assert.NotEmpty(t, vmsizeClient.rateLimiterReader) - assert.NotEmpty(t, vmsizeClient.rateLimiterWriter) -} - -func TestNewAzureStack(t *testing.T) { - config := &azclients.ClientConfig{ - CloudName: "AZURESTACKCLOUD", - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - vmsizeClient := New(config) - assert.Equal(t, "AZURESTACKCLOUD", vmsizeClient.cloudName) - assert.Equal(t, "sub", vmsizeClient.subscriptionID) -} - -func TestList(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmsizeList := []compute.VirtualMachineSize{getTestVMSize("Standard_D2s_v3"), getTestVMSize("Standard_D4s_v3"), getTestVMSize("Standard_D8s_v3")} - responseBody, err := json.Marshal(compute.VirtualMachineSizeListResult{Value: &vmsizeList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmsizeClient := getTestVMSizeClient(armClient) - result, rerr := vmsizeClient.List(context.TODO(), "eastus") - assert.Nil(t, rerr) - assert.Equal(t, 3, len(*result.Value)) -} - -func TestListNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmsizeClient := getTestVMSizeClient(armClient) - expected := compute.VirtualMachineSizeListResult{Response: autorest.Response{}} - result, rerr := vmsizeClient.List(context.TODO(), "eastus") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestListInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmsizeClient := getTestVMSizeClient(armClient) - expected := compute.VirtualMachineSizeListResult{Response: autorest.Response{}} - result, rerr := vmsizeClient.List(context.TODO(), "eastus") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestListThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmsizeClient := getTestVMSizeClient(armClient) - expected := compute.VirtualMachineSizeListResult{Response: autorest.Response{}} - result, rerr := vmsizeClient.List(context.TODO(), "eastus") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestListNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmsizeListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "VMSizesList"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - expected := compute.VirtualMachineSizeListResult{Response: autorest.Response{}} - vmsizeClient := getTestVMSizeClientWithNeverRateLimiter(armClient) - result, rerr := vmsizeClient.List(context.TODO(), "eastus") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, vmsizeListErr, rerr) -} - -func TestListRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmsizeListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMSizesList", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - expected := compute.VirtualMachineSizeListResult{Response: autorest.Response{}} - vmsizeClient := getTestVMSizeClientWithRetryAfterReader(armClient) - result, rerr := vmsizeClient.List(context.TODO(), "eastus") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, vmsizeListErr, rerr) -} - -func getTestVMSizeClient(armClient armclient.Interface) *Client { - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(&azclients.RateLimitConfig{}) - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestVMSize(name string) compute.VirtualMachineSize { - return compute.VirtualMachineSize{ - Name: ptr.To(name), - } -} - -func getTestVMSizeClientWithNeverRateLimiter(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeNeverRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeNeverRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestVMSizeClientWithRetryAfterReader(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeAlwaysRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeAlwaysRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - RetryAfterReader: getFutureTime(), - RetryAfterWriter: getFutureTime(), - } -} - -func getFutureTime() time.Time { - return time.Unix(3000000000, 0) -} diff --git a/pkg/azureclients/vmsizeclient/doc.go b/pkg/azureclients/vmsizeclient/doc.go deleted file mode 100644 index 9d7ea23769..0000000000 --- a/pkg/azureclients/vmsizeclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package vmsizeclient implements the client for VirtualMachineSizes. -package vmsizeclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmsizeclient" diff --git a/pkg/azureclients/vmsizeclient/interface.go b/pkg/azureclients/vmsizeclient/interface.go deleted file mode 100644 index 16f920713c..0000000000 --- a/pkg/azureclients/vmsizeclient/interface.go +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package vmsizeclient - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - // APIVersion is the API version for compute. - APIVersion = "2022-03-01" - // AzureStackCloudAPIVersion is the API version for Azure Stack - AzureStackCloudAPIVersion = "2017-12-01" - // AzureStackCloudName is the cloud name of Azure Stack - AzureStackCloudName = "AZURESTACKCLOUD" -) - -// Interface is the client interface for VirtualMachineSizes. -// Don't forget to run "hack/update-mock-clients.sh" command to generate the mock client. -type Interface interface { - // List gets compute.VirtualMachineSizeListResult. - List(ctx context.Context, location string) (result compute.VirtualMachineSizeListResult, rerr *retry.Error) -} diff --git a/pkg/azureclients/vmsizeclient/mockvmsizeclient/doc.go b/pkg/azureclients/vmsizeclient/mockvmsizeclient/doc.go deleted file mode 100644 index 90faf53917..0000000000 --- a/pkg/azureclients/vmsizeclient/mockvmsizeclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package mockvmsizeclient implements the mock client for VirtualMachineSizes. -package mockvmsizeclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/virtualmachinesizeclient/mockvmsizeclient" diff --git a/pkg/azureclients/vmsizeclient/mockvmsizeclient/interface.go b/pkg/azureclients/vmsizeclient/mockvmsizeclient/interface.go deleted file mode 100644 index bc3f88d313..0000000000 --- a/pkg/azureclients/vmsizeclient/mockvmsizeclient/interface.go +++ /dev/null @@ -1,74 +0,0 @@ -// /* -// Copyright The Kubernetes Authors. -// -// 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 MockGen. DO NOT EDIT. -// Source: pkg/azureclients/vmsizeclient/interface.go -// -// Generated by this command: -// -// mockgen -copyright_file=/home/runner/work/cloud-provider-azure/cloud-provider-azure/hack/boilerplate/boilerplate.generatego.txt -source=pkg/azureclients/vmsizeclient/interface.go -package=mockvmsizeclient Interface -// - -// Package mockvmsizeclient is a generated GoMock package. -package mockvmsizeclient - -import ( - context "context" - reflect "reflect" - - compute "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - gomock "go.uber.org/mock/gomock" - retry "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -// MockInterface is a mock of Interface interface. -type MockInterface struct { - ctrl *gomock.Controller - recorder *MockInterfaceMockRecorder -} - -// MockInterfaceMockRecorder is the mock recorder for MockInterface. -type MockInterfaceMockRecorder struct { - mock *MockInterface -} - -// NewMockInterface creates a new mock instance. -func NewMockInterface(ctrl *gomock.Controller) *MockInterface { - mock := &MockInterface{ctrl: ctrl} - mock.recorder = &MockInterfaceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { - return m.recorder -} - -// List mocks base method. -func (m *MockInterface) List(ctx context.Context, location string) (compute.VirtualMachineSizeListResult, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "List", ctx, location) - ret0, _ := ret[0].(compute.VirtualMachineSizeListResult) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// List indicates an expected call of List. -func (mr *MockInterfaceMockRecorder) List(ctx, location any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockInterface)(nil).List), ctx, location) -} diff --git a/pkg/azureclients/vmssclient/azure_vmssclient.go b/pkg/azureclients/vmssclient/azure_vmssclient.go deleted file mode 100644 index d58707929c..0000000000 --- a/pkg/azureclients/vmssclient/azure_vmssclient.go +++ /dev/null @@ -1,663 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package vmssclient - -import ( - "context" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/klog/v2" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/metrics" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -var _ Interface = &Client{} - -const vmssResourceType = "Microsoft.Compute/virtualMachineScaleSets" - -// Client implements VMSS client Interface. -type Client struct { - armClient armclient.Interface - subscriptionID string - cloudName string - - // Rate limiting configures. - rateLimiterReader flowcontrol.RateLimiter - rateLimiterWriter flowcontrol.RateLimiter - - // ARM throttling configures. - RetryAfterReader time.Time - RetryAfterWriter time.Time -} - -// New creates a new VMSS client with ratelimiting. -func New(config *azclients.ClientConfig) *Client { - baseURI := config.ResourceManagerEndpoint - authorizer := config.Authorizer - apiVersion := APIVersion - if strings.EqualFold(config.CloudName, AzureStackCloudName) && !config.DisableAzureStackCloud { - apiVersion = AzureStackCloudAPIVersion - } - armClient := armclient.New(authorizer, *config, baseURI, apiVersion) - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig) - - if azclients.RateLimitEnabled(config.RateLimitConfig) { - klog.V(2).Infof("Azure VirtualMachineScaleSetClient (read ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPS, - config.RateLimitConfig.CloudProviderRateLimitBucket) - klog.V(2).Infof("Azure VirtualMachineScaleSetClient (write ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPSWrite, - config.RateLimitConfig.CloudProviderRateLimitBucketWrite) - } - - client := &Client{ - armClient: armClient, - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - subscriptionID: config.SubscriptionID, - cloudName: config.CloudName, - } - - return client -} - -// Get gets a VirtualMachineScaleSet. -func (c *Client) Get(ctx context.Context, resourceGroupName string, VMScaleSetName string) (compute.VirtualMachineScaleSet, *retry.Error) { - mc := metrics.NewMetricContext("vmss", "get", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return compute.VirtualMachineScaleSet{}, retry.GetRateLimitError(false, "VMSSGet") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSGet", "client throttled", c.RetryAfterReader) - return compute.VirtualMachineScaleSet{}, rerr - } - - result, rerr := c.getVMSS(ctx, resourceGroupName, VMScaleSetName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// getVMSS gets a VirtualMachineScaleSet. -func (c *Client) getVMSS(ctx context.Context, resourceGroupName string, VMScaleSetName string) (compute.VirtualMachineScaleSet, *retry.Error) { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - vmssResourceType, - VMScaleSetName, - ) - result := compute.VirtualMachineScaleSet{} - - response, rerr := c.armClient.GetResource(ctx, resourceID) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.get.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.get.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} - -// List gets a list of VirtualMachineScaleSets in the resource group. -func (c *Client) List(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachineScaleSet, *retry.Error) { - mc := metrics.NewMetricContext("vmss", "list", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(false, "VMSSList") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSList", "client throttled", c.RetryAfterReader) - return nil, rerr - } - - result, rerr := c.listVMSS(ctx, resourceGroupName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// listVMSS gets a list of VirtualMachineScaleSets in the resource group. -func (c *Client) listVMSS(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachineScaleSet, *retry.Error) { - resourceID := armclient.GetResourceListID( - c.subscriptionID, - resourceGroupName, - vmssResourceType, - ) - result := make([]compute.VirtualMachineScaleSet, 0) - page := &VirtualMachineScaleSetListResultPage{} - page.fn = c.listNextResults - - resp, rerr := c.armClient.GetResource(ctx, resourceID) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.list.request", resourceID, rerr.Error()) - return result, rerr - } - - var err error - page.vmsslr, err = c.listResponder(resp) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.list.respond", resourceID, err) - return result, retry.GetError(resp, err) - } - - for { - result = append(result, page.Values()...) - - // Abort the loop when there's no nextLink in the response. - if ptr.Deref(page.Response().NextLink, "") == "" { - break - } - - if err = page.NextWithContext(ctx); err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.list.next", resourceID, err) - return result, retry.GetError(page.Response().Response.Response, err) - } - } - - return result, nil -} - -// CreateOrUpdate creates or updates a VirtualMachineScaleSet. -func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) *retry.Error { - mc := metrics.NewMetricContext("vmss", "create_or_update", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "VMSSCreateOrUpdate") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSCreateOrUpdate", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.createOrUpdateVMSS(ctx, resourceGroupName, VMScaleSetName, parameters) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// CreateOrUpdateAsync sends the request to arm client and DO NOT wait for the response -func (c *Client) CreateOrUpdateAsync(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) (*azure.Future, *retry.Error) { - mc := metrics.NewMetricContext("vmss", "create_or_update_async", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(true, "VMSSCreateOrUpdateAsync") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSCreateOrUpdateAsync", "client throttled", c.RetryAfterWriter) - return nil, rerr - } - - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - vmssResourceType, - VMScaleSetName, - ) - - future, rerr := c.armClient.PutResourceAsync(ctx, resourceID, parameters) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return nil, rerr - } - - return future, nil -} - -// WaitForCreateOrUpdateResult waits for the response of the create or update request -func (c *Client) WaitForCreateOrUpdateResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) { - return c.WaitForAsyncOperationResult(ctx, future, resourceGroupName, "wait_for_create_or_update_result", "VMSSWaitForCreateOrUpdateResult") -} - -// WaitForDeleteInstancesResult waits for the response of the delete instance request -func (c *Client) WaitForDeleteInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) { - return c.WaitForAsyncOperationResult(ctx, future, resourceGroupName, "wait_for_delete_instances_result", "VMSSWaitForDeleteInstancesResult") -} - -// WaitForDeallocateInstancesResult waits for the response of the delete instance request -func (c *Client) WaitForDeallocateInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) { - return c.WaitForAsyncOperationResult(ctx, future, resourceGroupName, "wait_for_deallocate_instances_result", "VMSSWaitForDeallocateInstancesResult") -} - -// WaitForStartInstancesResult waits for the response of the delete instance request -func (c *Client) WaitForStartInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) { - return c.WaitForAsyncOperationResult(ctx, future, resourceGroupName, "wait_for_start_instances_result", "VMSSWaitForStartInstancesResult") -} - -// WaitForAsyncOperationResult waits for the response of the request -func (c *Client) WaitForAsyncOperationResult(ctx context.Context, future *azure.Future, resourceGroupName, request, asycOpName string) (*http.Response, error) { - mc := metrics.NewMetricContext("vmss", request, resourceGroupName, c.subscriptionID, "") - res, err := c.armClient.WaitForAsyncOperationResult(ctx, future, asycOpName) - mc.Observe(retry.NewErrorOrNil(false, err)) - return res, err -} - -// createOrUpdateVMSS creates or updates a VirtualMachineScaleSet. -func (c *Client) createOrUpdateVMSS(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) *retry.Error { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - vmssResourceType, - VMScaleSetName, - ) - response, rerr := c.armClient.PutResource(ctx, resourceID, parameters) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.put.request", resourceID, rerr.Error()) - return rerr - } - - if response != nil && response.StatusCode != http.StatusNoContent { - _, rerr = c.createOrUpdateResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.put.respond", resourceID, rerr.Error()) - return rerr - } - } - - return nil -} - -func (c *Client) createOrUpdateResponder(resp *http.Response) (*compute.VirtualMachineScaleSet, *retry.Error) { - result := &compute.VirtualMachineScaleSet{} - err := autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return result, retry.GetError(resp, err) -} - -func (c *Client) listResponder(resp *http.Response) (result compute.VirtualMachineScaleSetListResult, err error) { - err = autorest.Respond( - resp, - autorest.ByIgnoring(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return -} - -// virtualMachineScaleSetListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (c *Client) virtualMachineScaleSetListResultPreparer(ctx context.Context, vmsslr compute.VirtualMachineScaleSetListResult) (*http.Request, error) { - if vmsslr.NextLink == nil || len(ptr.Deref(vmsslr.NextLink, "")) < 1 { - return nil, nil - } - - decorators := []autorest.PrepareDecorator{ - autorest.WithBaseURL(ptr.Deref(vmsslr.NextLink, "")), - } - return c.armClient.PrepareGetRequest(ctx, decorators...) -} - -// listNextResults retrieves the next set of results, if any. -func (c *Client) listNextResults(ctx context.Context, lastResults compute.VirtualMachineScaleSetListResult) (result compute.VirtualMachineScaleSetListResult, err error) { - req, err := c.virtualMachineScaleSetListResultPreparer(ctx, lastResults) - if err != nil { - return result, autorest.NewErrorWithError(err, "vmssclient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - - resp, rerr := c.armClient.Send(ctx, req) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(rerr.Error(), "vmssclient", "listNextResults", resp, "Failure sending next results request") - } - - result, err = c.listResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "vmssclient", "listNextResults", resp, "Failure responding to next results request") - } - - return -} - -// VirtualMachineScaleSetListResultPage contains a page of VirtualMachineScaleSet values. -type VirtualMachineScaleSetListResultPage struct { - fn func(context.Context, compute.VirtualMachineScaleSetListResult) (compute.VirtualMachineScaleSetListResult, error) - vmsslr compute.VirtualMachineScaleSetListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualMachineScaleSetListResultPage) NextWithContext(ctx context.Context) (err error) { - next, err := page.fn(ctx, page.vmsslr) - if err != nil { - return err - } - page.vmsslr = next - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualMachineScaleSetListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualMachineScaleSetListResultPage) NotDone() bool { - return !page.vmsslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualMachineScaleSetListResultPage) Response() compute.VirtualMachineScaleSetListResult { - return page.vmsslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualMachineScaleSetListResultPage) Values() []compute.VirtualMachineScaleSet { - if page.vmsslr.IsEmpty() { - return nil - } - return *page.vmsslr.Value -} - -// DeleteInstances deletes the instances for a VirtualMachineScaleSet. -func (c *Client) DeleteInstances(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) *retry.Error { - mc := metrics.NewMetricContext("vmss", "delete_instances", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "VMSSDeleteInstances") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSDeleteInstances", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.deleteVMSSInstances(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// DeleteInstancesAsync sends the delete request to ARM client and DOES NOT wait on the future -func (c *Client) DeleteInstancesAsync(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs, forceDelete bool) (*azure.Future, *retry.Error) { - mc := metrics.NewMetricContext("vmss", "delete_instances_async", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(true, "VMSSDeleteInstancesAsync") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSDeleteInstancesAsync", "client throttled", c.RetryAfterWriter) - return nil, rerr - } - - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - vmssResourceType, - vmScaleSetName, - ) - - var queryParameters map[string]interface{} - if forceDelete { - queryParameters = map[string]interface{}{ - "forceDeletion": true, - } - } - response, rerr := c.armClient.PostResource(ctx, resourceID, "delete", vmInstanceIDs, queryParameters) - defer c.armClient.CloseResponse(ctx, response) - - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.deletevms.request", resourceID, rerr.Error()) - return nil, rerr - } - - err := autorest.Respond(response, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.deletevms.respond", resourceID, err) - return nil, retry.GetError(response, err) - } - - future, err := azure.NewFutureFromResponse(response) - rerr = retry.NewErrorOrNil(false, err) - mc.Observe(rerr) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.deletevms.future", resourceID, err) - return nil, rerr - } - - return &future, nil -} - -// DeallocateInstancesAsync sends the deallocate request to ARM client and DOES NOT wait on the future -func (c *Client) DeallocateInstancesAsync(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error) { - mc := metrics.NewMetricContext("vmss", "deallocate_instances_async", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(true, "VMSSDeallocateInstancesAsync") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSDeallocateInstancesAsync", "client throttled", c.RetryAfterWriter) - return nil, rerr - } - - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - vmssResourceType, - vmScaleSetName, - ) - - response, rerr := c.armClient.PostResource(ctx, resourceID, "deallocate", vmInstanceIDs, map[string]interface{}{}) - defer c.armClient.CloseResponse(ctx, response) - - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.deallocatevms.request", resourceID, rerr.Error()) - return nil, rerr - } - - err := autorest.Respond(response, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.deallocatevms.respond", resourceID, err) - return nil, retry.GetError(response, err) - } - - future, err := azure.NewFutureFromResponse(response) - rerr = retry.NewErrorOrNil(false, err) - mc.Observe(rerr) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.deallocatevms.future", resourceID, err) - return nil, rerr - } - - return &future, nil -} - -// StartInstancesAsync sends the start request to ARM client and DOES NOT wait on the future -func (c *Client) StartInstancesAsync(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error) { - mc := metrics.NewMetricContext("vmss", "start_instances_async", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(true, "VMSSStartInstancesAsync") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSStartInstancesAsync", "client throttled", c.RetryAfterWriter) - return nil, rerr - } - - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - vmssResourceType, - vmScaleSetName, - ) - - response, rerr := c.armClient.PostResource(ctx, resourceID, "start", vmInstanceIDs, map[string]interface{}{}) - defer c.armClient.CloseResponse(ctx, response) - - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.startvms.request", resourceID, rerr.Error()) - return nil, rerr - } - - err := autorest.Respond(response, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.startvms.respond", resourceID, err) - return nil, retry.GetError(response, err) - } - - future, err := azure.NewFutureFromResponse(response) - rerr = retry.NewErrorOrNil(false, err) - mc.Observe(rerr) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.startvms.future", resourceID, err) - return nil, rerr - } - - return &future, nil -} - -// deleteVMSSInstances deletes the instances for a VirtualMachineScaleSet. -func (c *Client) deleteVMSSInstances(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) *retry.Error { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - vmssResourceType, - vmScaleSetName, - ) - response, rerr := c.armClient.PostResource(ctx, resourceID, "delete", vmInstanceIDs, map[string]interface{}{}) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.deletevms.request", resourceID, rerr.Error()) - return rerr - } - - err := autorest.Respond(response, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.deletevms.respond", resourceID, rerr.Error()) - return retry.GetError(response, err) - } - - future, err := azure.NewFutureFromResponse(response) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.deletevms.future", resourceID, rerr.Error()) - return retry.NewError(false, err) - } - - if err := c.armClient.WaitForAsyncOperationCompletion(ctx, &future, "vmssclient.DeleteInstances"); err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmss.deletevms.wait", resourceID, rerr.Error()) - return retry.NewError(false, err) - } - - return nil -} diff --git a/pkg/azureclients/vmssclient/azure_vmssclient_test.go b/pkg/azureclients/vmssclient/azure_vmssclient_test.go deleted file mode 100644 index 5129645033..0000000000 --- a/pkg/azureclients/vmssclient/azure_vmssclient_test.go +++ /dev/null @@ -1,885 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package vmssclient - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "testing" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/stretchr/testify/assert" - - "go.uber.org/mock/gomock" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient/mockarmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - testResourceID = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss1" - testResourcePrefix = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets" -) - -func TestNew(t *testing.T) { - config := &azclients.ClientConfig{ - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - vmssClient := New(config) - assert.Equal(t, "sub", vmssClient.subscriptionID) - assert.NotEmpty(t, vmssClient.rateLimiterReader) - assert.NotEmpty(t, vmssClient.rateLimiterWriter) -} - -func TestNewAzureStack(t *testing.T) { - config := &azclients.ClientConfig{ - CloudName: "AZURESTACKCLOUD", - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - vmssClient := New(config) - assert.Equal(t, "AZURESTACKCLOUD", vmssClient.cloudName) - assert.Equal(t, "sub", vmssClient.subscriptionID) -} - -func TestGet(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - expected := compute.VirtualMachineScaleSet{Response: autorest.Response{Response: response}} - vmssClient := getTestVMSSClient(armClient) - result, rerr := vmssClient.Get(context.TODO(), "rg", "vmss1") - assert.Equal(t, expected, result) - assert.Nil(t, rerr) -} - -func TestGetNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "VMSSGet"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssClient := getTestVMSSClientWithNeverRateLimiter(armClient) - expected := compute.VirtualMachineScaleSet{} - result, rerr := vmssClient.Get(context.TODO(), "rg", "vmss1") - assert.Equal(t, expected, result) - assert.Equal(t, vmssGetErr, rerr) -} - -func TestGetRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMSSGet", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssClient := getTestVMSSClientWithRetryAfterReader(armClient) - expected := compute.VirtualMachineScaleSet{} - result, rerr := vmssClient.Get(context.TODO(), "rg", "vmss1") - assert.Equal(t, expected, result) - assert.Equal(t, vmssGetErr, rerr) -} - -func TestGetNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSClient(armClient) - expectedVMSS := compute.VirtualMachineScaleSet{Response: autorest.Response{}} - result, rerr := vmssClient.Get(context.TODO(), "rg", "vmss1") - assert.Equal(t, expectedVMSS, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestGetInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSClient(armClient) - expectedVMSS := compute.VirtualMachineScaleSet{Response: autorest.Response{}} - result, rerr := vmssClient.Get(context.TODO(), "rg", "vmss1") - assert.Equal(t, expectedVMSS, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestGetThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourceID).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSClient(armClient) - result, rerr := vmssClient.Get(context.TODO(), "rg", "vmss1") - assert.Empty(t, result) - assert.Equal(t, throttleErr, rerr) -} - -func TestList(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssList := []compute.VirtualMachineScaleSet{getTestVMSS("vmss1"), getTestVMSS("vmss2"), getTestVMSS("vmss3")} - responseBody, err := json.Marshal(compute.VirtualMachineScaleSetListResult{Value: &vmssList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSClient(armClient) - result, rerr := vmssClient.List(context.TODO(), "rg") - assert.Nil(t, rerr) - assert.Equal(t, 3, len(result)) -} - -func TestListNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSClient(armClient) - expected := []compute.VirtualMachineScaleSet{} - result, rerr := vmssClient.List(context.TODO(), "rg") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestListInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSClient(armClient) - expected := []compute.VirtualMachineScaleSet{} - result, rerr := vmssClient.List(context.TODO(), "rg") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestListThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmssClient := getTestVMSSClient(armClient) - result, rerr := vmssClient.List(context.TODO(), "rg") - assert.Empty(t, result) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestListWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssList := []compute.VirtualMachineScaleSet{getTestVMSS("vmss1"), getTestVMSS("vmss2"), getTestVMSS("vmss3")} - responseBody, err := json.Marshal(compute.VirtualMachineScaleSetListResult{Value: &vmssList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmssClient := getTestVMSSClient(armClient) - result, rerr := vmssClient.List(context.TODO(), "rg") - assert.NotNil(t, rerr) - assert.Equal(t, 0, len(result)) -} - -func TestListWithNextPage(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssList := []compute.VirtualMachineScaleSet{getTestVMSS("vmss1"), getTestVMSS("vmss2"), getTestVMSS("vmss3")} - partialResponse, err := json.Marshal(compute.VirtualMachineScaleSetListResult{Value: &vmssList, NextLink: ptr.To("nextLink")}) - assert.NoError(t, err) - pagedResponse, err := json.Marshal(compute.VirtualMachineScaleSetListResult{Value: &vmssList}) - assert.NoError(t, err) - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(&http.Request{}, nil) - armClient.EXPECT().Send(gomock.Any(), gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(pagedResponse)), - }, nil) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(partialResponse)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(2) - vmssClient := getTestVMSSClient(armClient) - result, rerr := vmssClient.List(context.TODO(), "rg") - assert.Nil(t, rerr) - assert.Equal(t, 6, len(result)) -} - -func TestListNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "VMSSList"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssClient := getTestVMSSClientWithNeverRateLimiter(armClient) - result, rerr := vmssClient.List(context.TODO(), "rg") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, vmssListErr, rerr) -} - -func TestListRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMSSList", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssClient := getTestVMSSClientWithRetryAfterReader(armClient) - result, rerr := vmssClient.List(context.TODO(), "rg") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, vmssListErr, rerr) -} - -func TestListNextResultsMultiPages(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - name string - prepareErr error - sendErr *retry.Error - expectedErrMsg string - }{ - { - name: "testlistNextResultsSuccessful", - prepareErr: nil, - sendErr: nil, - }, - { - name: "testPrepareGetRequestError", - prepareErr: fmt.Errorf("error"), - expectedErrMsg: "Failure preparing next results request", - }, - { - name: "testSendError", - sendErr: &retry.Error{RawError: fmt.Errorf("error")}, - expectedErrMsg: "Failure sending next results request", - }, - } - - lastResult := compute.VirtualMachineScaleSetListResult{ - NextLink: ptr.To("next"), - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - vmssClient := getTestVMSSClient(armClient) - result, err := vmssClient.listNextResults(context.TODO(), lastResult) - if err != nil { - detailedErr := &autorest.DetailedError{} - assert.True(t, errors.As(err, detailedErr)) - assert.Equal(t, detailedErr.Message, test.expectedErrMsg) - } else { - assert.NoError(t, err) - } - - if test.prepareErr != nil { - assert.Empty(t, result) - } else { - assert.NotEmpty(t, result) - } - } -} - -func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - name string - prepareErr error - sendErr *retry.Error - }{ - { - name: "testListResponderError", - prepareErr: nil, - sendErr: nil, - }, - { - name: "testSendError", - sendErr: &retry.Error{RawError: fmt.Errorf("error")}, - }, - } - - lastResult := compute.VirtualMachineScaleSetListResult{ - NextLink: ptr.To("next"), - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewBuffer([]byte(`{"foo":"bar"}`))), - } - expected := compute.VirtualMachineScaleSetListResult{} - expected.Response = autorest.Response{Response: response} - vmssClient := getTestVMSSClient(armClient) - result, err := vmssClient.listNextResults(context.TODO(), lastResult) - assert.Error(t, err) - if test.sendErr != nil { - assert.NotEqual(t, expected, result) - } else { - assert.Equal(t, expected, result) - } - } -} - -func TestCreateOrUpdate(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmss := getTestVMSS("vmss1") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(vmss.ID, ""), vmss).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSClient(armClient) - rerr := vmssClient.CreateOrUpdate(context.TODO(), "rg", "vmss1", vmss) - assert.Nil(t, rerr) -} - -func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - vmss := getTestVMSS("vmss1") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(vmss.ID, ""), vmss).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSClient(armClient) - rerr := vmssClient.CreateOrUpdate(context.TODO(), "rg", "vmss1", vmss) - assert.NotNil(t, rerr) -} - -func TestCreateOrUpdateNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssCreateOrUpdateErr := retry.GetRateLimitError(true, "VMSSCreateOrUpdate") - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssClient := getTestVMSSClientWithNeverRateLimiter(armClient) - vmss := getTestVMSS("vmss1") - rerr := vmssClient.CreateOrUpdate(context.TODO(), "rg", "vmss1", vmss) - assert.NotNil(t, rerr) - assert.Equal(t, vmssCreateOrUpdateErr, rerr) -} - -func TestCreateOrUpdateRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssCreateOrUpdateErr := retry.GetThrottlingError("VMSSCreateOrUpdate", "client throttled", getFutureTime()) - - vmss := getTestVMSS("vmss1") - armClient := mockarmclient.NewMockInterface(ctrl) - vmssClient := getTestVMSSClientWithRetryAfterReader(armClient) - rerr := vmssClient.CreateOrUpdate(context.TODO(), "rg", "vmss1", vmss) - assert.NotNil(t, rerr) - assert.Equal(t, vmssCreateOrUpdateErr, rerr) -} - -func TestCreateOrUpdateThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - vmss := getTestVMSS("vmss1") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(vmss.ID, ""), vmss).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSClient(armClient) - rerr := vmssClient.CreateOrUpdate(context.TODO(), "rg", "vmss1", vmss) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestCreateOrUpdateAsync(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmss := getTestVMSS("vmss1") - armClient := mockarmclient.NewMockInterface(ctrl) - future := &azure.Future{} - - armClient.EXPECT().PutResourceAsync(gomock.Any(), ptr.Deref(vmss.ID, ""), vmss).Return(future, nil).Times(1) - vmssClient := getTestVMSSClient(armClient) - _, rerr := vmssClient.CreateOrUpdateAsync(context.TODO(), "rg", "vmss1", vmss) - assert.Nil(t, rerr) - - retryErr := &retry.Error{RawError: fmt.Errorf("error")} - armClient.EXPECT().PutResourceAsync(gomock.Any(), ptr.Deref(vmss.ID, ""), vmss).Return(future, retryErr).Times(1) - _, rerr = vmssClient.CreateOrUpdateAsync(context.TODO(), "rg", "vmss1", vmss) - assert.Equal(t, retryErr, rerr) -} - -func TestCreateOrUpdateAsyncNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssCreateOrUpdateAsyncErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "write", "VMSSCreateOrUpdateAsync"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssClient := getTestVMSSClientWithNeverRateLimiter(armClient) - vmss := getTestVMSS("vmss1") - _, rerr := vmssClient.CreateOrUpdateAsync(context.TODO(), "rg", "vmss1", vmss) - assert.NotNil(t, rerr) - assert.Equal(t, vmssCreateOrUpdateAsyncErr, rerr) -} - -func TestCreateOrUpdateAsyncRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssCreateOrUpdateAsyncErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMSSCreateOrUpdateAsync", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - vmss := getTestVMSS("vmss1") - armClient := mockarmclient.NewMockInterface(ctrl) - vmssClient := getTestVMSSClientWithRetryAfterReader(armClient) - _, rerr := vmssClient.CreateOrUpdateAsync(context.TODO(), "rg", "vmss1", vmss) - assert.NotNil(t, rerr) - assert.Equal(t, vmssCreateOrUpdateAsyncErr, rerr) -} - -func TestCreateOrUpdateAsyncThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - vmss := getTestVMSS("vmss1") - future := &azure.Future{} - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PutResourceAsync(gomock.Any(), ptr.Deref(vmss.ID, ""), vmss).Return(future, throttleErr).Times(1) - - vmssClient := getTestVMSSClient(armClient) - _, rerr := vmssClient.CreateOrUpdateAsync(context.TODO(), "rg", "vmss1", vmss) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestWaitForAsyncOperationResult(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - - armClient.EXPECT().WaitForAsyncOperationResult(gomock.Any(), &azure.Future{}, "VMSSWaitForAsyncOperationResult").Return(response, nil) - vmssClient := getTestVMSSClient(armClient) - _, err := vmssClient.WaitForAsyncOperationResult(context.TODO(), &azure.Future{}, "rgName", "req", "VMSSWaitForAsyncOperationResult") - assert.NoError(t, err) -} - -func TestDeleteInstances(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - r := getTestVMSS("vmss1") - vmInstanceIDs := compute.VirtualMachineScaleSetVMInstanceRequiredIDs{ - InstanceIds: &[]string{"0", "1", "2"}, - } - response := &http.Response{ - StatusCode: http.StatusOK, - Request: &http.Request{Method: "POST"}, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PostResource(gomock.Any(), ptr.Deref(r.ID, ""), "delete", vmInstanceIDs, map[string]interface{}{}).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - armClient.EXPECT().WaitForAsyncOperationCompletion(gomock.Any(), gomock.Any(), "vmssclient.DeleteInstances").Return(nil).Times(1) - - client := getTestVMSSClient(armClient) - rerr := client.DeleteInstances(context.TODO(), "rg", "vmss1", vmInstanceIDs) - assert.Nil(t, rerr) -} - -func TestDeleteInstancesNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmInstanceIDs := compute.VirtualMachineScaleSetVMInstanceRequiredIDs{ - InstanceIds: &[]string{"0", "1", "2"}, - } - vmssDeleteInstancesErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "write", "VMSSDeleteInstances"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssClient := getTestVMSSClientWithNeverRateLimiter(armClient) - rerr := vmssClient.DeleteInstances(context.TODO(), "rg", "vmss1", vmInstanceIDs) - assert.NotNil(t, rerr) - assert.Equal(t, vmssDeleteInstancesErr, rerr) -} - -func TestDeleteInstancesRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmInstanceIDs := compute.VirtualMachineScaleSetVMInstanceRequiredIDs{ - InstanceIds: &[]string{"0", "1", "2"}, - } - vmssDeleteInstancesErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMSSDeleteInstances", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssClient := getTestVMSSClientWithRetryAfterReader(armClient) - rerr := vmssClient.DeleteInstances(context.TODO(), "rg", "vmss1", vmInstanceIDs) - assert.NotNil(t, rerr) - assert.Equal(t, vmssDeleteInstancesErr, rerr) -} - -func TestDeleteInstancesThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmss := getTestVMSS("vmss1") - vmInstanceIDs := compute.VirtualMachineScaleSetVMInstanceRequiredIDs{ - InstanceIds: &[]string{"0", "1", "2"}, - } - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PostResource(gomock.Any(), ptr.Deref(vmss.ID, ""), "delete", vmInstanceIDs, map[string]interface{}{}).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSClient(armClient) - rerr := vmssClient.DeleteInstances(context.TODO(), "rg", "vmss1", vmInstanceIDs) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestDeleteInstancesWaitError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmss := getTestVMSS("vmss1") - vmInstanceIDs := compute.VirtualMachineScaleSetVMInstanceRequiredIDs{ - InstanceIds: &[]string{"0", "1", "2"}, - } - response := &http.Response{ - StatusCode: http.StatusOK, - Request: &http.Request{Method: "POST"}, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - err := fmt.Errorf("%s", string("Wait error")) - vmssDeleteInstancesErr := &retry.Error{ - RawError: err, - Retriable: false, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PostResource(gomock.Any(), ptr.Deref(vmss.ID, ""), "delete", vmInstanceIDs, map[string]interface{}{}).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - armClient.EXPECT().WaitForAsyncOperationCompletion(gomock.Any(), gomock.Any(), "vmssclient.DeleteInstances").Return(err).Times(1) - - vmssClient := getTestVMSSClient(armClient) - rerr := vmssClient.DeleteInstances(context.TODO(), "rg", "vmss1", vmInstanceIDs) - assert.NotNil(t, rerr) - assert.Equal(t, vmssDeleteInstancesErr, rerr) -} - -func TestDeleteInstancesAsync(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmss := getTestVMSS("vmss1") - vmInstanceIDs := compute.VirtualMachineScaleSetVMInstanceRequiredIDs{ - InstanceIds: &[]string{"0", "1", "2"}, - } - response := &http.Response{ - StatusCode: http.StatusOK, - Request: &http.Request{Method: "POST"}, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PostResource(gomock.Any(), ptr.Deref(vmss.ID, ""), "delete", vmInstanceIDs, gomock.Any()).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSClient(armClient) - future, rerr := vmssClient.DeleteInstancesAsync(context.TODO(), "rg", "vmss1", vmInstanceIDs, false) - assert.Nil(t, rerr) - assert.Equal(t, future.Status(), "Succeeded") - - // with force delete - armClient.EXPECT().PostResource(gomock.Any(), ptr.Deref(vmss.ID, ""), "delete", vmInstanceIDs, map[string]interface{}{"forceDeletion": true}).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - future, rerr = vmssClient.DeleteInstancesAsync(context.TODO(), "rg", "vmss1", vmInstanceIDs, true) - assert.Nil(t, rerr) - assert.Equal(t, future.Status(), "Succeeded") - - // on error - retryErr := &retry.Error{RawError: fmt.Errorf("error")} - armClient.EXPECT().PostResource(gomock.Any(), ptr.Deref(vmss.ID, ""), "delete", vmInstanceIDs, gomock.Any()).Return(&http.Response{StatusCode: http.StatusBadRequest}, retryErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - _, rerr = vmssClient.DeleteInstancesAsync(context.TODO(), "rg", "vmss1", vmInstanceIDs, false) - assert.Equal(t, retryErr, rerr) -} - -func getTestVMSS(name string) compute.VirtualMachineScaleSet { - return compute.VirtualMachineScaleSet{ - ID: ptr.To("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss1"), - Name: ptr.To(name), - Location: ptr.To("eastus"), - Sku: &compute.Sku{ - Name: ptr.To("Standard"), - Capacity: ptr.To(int64(3)), - }, - } -} - -func getTestVMSSClient(armClient armclient.Interface) *Client { - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(&azclients.RateLimitConfig{}) - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestVMSSClientWithNeverRateLimiter(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeNeverRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeNeverRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestVMSSClientWithRetryAfterReader(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeAlwaysRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeAlwaysRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - RetryAfterReader: getFutureTime(), - RetryAfterWriter: getFutureTime(), - } -} - -func getFutureTime() time.Time { - return time.Unix(3000000000, 0) -} diff --git a/pkg/azureclients/vmssclient/doc.go b/pkg/azureclients/vmssclient/doc.go deleted file mode 100644 index cb5fa8dcde..0000000000 --- a/pkg/azureclients/vmssclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package vmssclient implements the client for VMSS. -package vmssclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient" diff --git a/pkg/azureclients/vmssclient/interface.go b/pkg/azureclients/vmssclient/interface.go deleted file mode 100644 index 10c9d04703..0000000000 --- a/pkg/azureclients/vmssclient/interface.go +++ /dev/null @@ -1,79 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package vmssclient - -import ( - "context" - "net/http" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/azure" - - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - // APIVersion is the API version for VMSS. - APIVersion = "2022-03-01" - // AzureStackCloudAPIVersion is the API version for Azure Stack - AzureStackCloudAPIVersion = "2019-07-01" - // AzureStackCloudName is the cloud name of Azure Stack - AzureStackCloudName = "AZURESTACKCLOUD" -) - -// Interface is the client interface for VirtualMachineScaleSet. -// Don't forget to run "hack/update-mock-clients.sh" command to generate the mock client. -type Interface interface { - // Get gets a VirtualMachineScaleSet. - Get(ctx context.Context, resourceGroupName string, VMScaleSetName string) (result compute.VirtualMachineScaleSet, rerr *retry.Error) - - // List gets a list of VirtualMachineScaleSets in the resource group. - List(ctx context.Context, resourceGroupName string) (result []compute.VirtualMachineScaleSet, rerr *retry.Error) - - // CreateOrUpdate creates or updates a VirtualMachineScaleSet. - CreateOrUpdate(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) *retry.Error - - // CreateOrUpdateSync sends the request to arm client and DO NOT wait for the response - CreateOrUpdateAsync(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) (*azure.Future, *retry.Error) - - // WaitForAsyncOperationResult waits for the response of the request - WaitForAsyncOperationResult(ctx context.Context, future *azure.Future, resourceGroupName, request, asyncOpName string) (*http.Response, error) - - // DeleteInstances deletes the instances for a VirtualMachineScaleSet. - DeleteInstances(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) *retry.Error - - // DeleteInstancesAsync sends the delete request to the ARM client and DOES NOT wait on the future - DeleteInstancesAsync(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs, forceDelete bool) (*azure.Future, *retry.Error) - - // WaitForCreateOrUpdateResult waits for the response of the create or update request - WaitForCreateOrUpdateResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) - - // WaitForDeleteInstancesResult waits for the response of the delete instances request - WaitForDeleteInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) - - // DeallocateInstances sends the deallocate request to the ARM client and DOES NOT wait on the future - DeallocateInstancesAsync(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error) - - // WaitForDeallocateInstancesResult waits for the response of the deallocate instances request - WaitForDeallocateInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) - - // StartInstancesAsync starts the instances for a VirtualMachineScaleSet. - StartInstancesAsync(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error) - - // WaitForStartInstancesResult waits for the response of the start instances request - WaitForStartInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) -} diff --git a/pkg/azureclients/vmssclient/mockvmssclient/doc.go b/pkg/azureclients/vmssclient/mockvmssclient/doc.go deleted file mode 100644 index 2eb7c212e8..0000000000 --- a/pkg/azureclients/vmssclient/mockvmssclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package mockvmssclient implements the mock client for VMSS. -package mockvmssclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" diff --git a/pkg/azureclients/vmssclient/mockvmssclient/interface.go b/pkg/azureclients/vmssclient/mockvmssclient/interface.go deleted file mode 100644 index f3d166012a..0000000000 --- a/pkg/azureclients/vmssclient/mockvmssclient/interface.go +++ /dev/null @@ -1,254 +0,0 @@ -// /* -// Copyright The Kubernetes Authors. -// -// 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 MockGen. DO NOT EDIT. -// Source: pkg/azureclients/vmssclient/interface.go -// -// Generated by this command: -// -// mockgen -copyright_file=/home/runner/work/cloud-provider-azure/cloud-provider-azure/hack/boilerplate/boilerplate.generatego.txt -source=pkg/azureclients/vmssclient/interface.go -package=mockvmssclient Interface -// - -// Package mockvmssclient is a generated GoMock package. -package mockvmssclient - -import ( - context "context" - http "net/http" - reflect "reflect" - - compute "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - azure "github.com/Azure/go-autorest/autorest/azure" - gomock "go.uber.org/mock/gomock" - retry "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -// MockInterface is a mock of Interface interface. -type MockInterface struct { - ctrl *gomock.Controller - recorder *MockInterfaceMockRecorder -} - -// MockInterfaceMockRecorder is the mock recorder for MockInterface. -type MockInterfaceMockRecorder struct { - mock *MockInterface -} - -// NewMockInterface creates a new mock instance. -func NewMockInterface(ctrl *gomock.Controller) *MockInterface { - mock := &MockInterface{ctrl: ctrl} - mock.recorder = &MockInterfaceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { - return m.recorder -} - -// CreateOrUpdate mocks base method. -func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrUpdate", ctx, resourceGroupName, VMScaleSetName, parameters) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// CreateOrUpdate indicates an expected call of CreateOrUpdate. -func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, VMScaleSetName, parameters any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdate", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, VMScaleSetName, parameters) -} - -// CreateOrUpdateAsync mocks base method. -func (m *MockInterface) CreateOrUpdateAsync(ctx context.Context, resourceGroupName, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) (*azure.Future, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrUpdateAsync", ctx, resourceGroupName, VMScaleSetName, parameters) - ret0, _ := ret[0].(*azure.Future) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// CreateOrUpdateAsync indicates an expected call of CreateOrUpdateAsync. -func (mr *MockInterfaceMockRecorder) CreateOrUpdateAsync(ctx, resourceGroupName, VMScaleSetName, parameters any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdateAsync", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdateAsync), ctx, resourceGroupName, VMScaleSetName, parameters) -} - -// DeallocateInstancesAsync mocks base method. -func (m *MockInterface) DeallocateInstancesAsync(ctx context.Context, resourceGroupName, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeallocateInstancesAsync", ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs) - ret0, _ := ret[0].(*azure.Future) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// DeallocateInstancesAsync indicates an expected call of DeallocateInstancesAsync. -func (mr *MockInterfaceMockRecorder) DeallocateInstancesAsync(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeallocateInstancesAsync", reflect.TypeOf((*MockInterface)(nil).DeallocateInstancesAsync), ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs) -} - -// DeleteInstances mocks base method. -func (m *MockInterface) DeleteInstances(ctx context.Context, resourceGroupName, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteInstances", ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// DeleteInstances indicates an expected call of DeleteInstances. -func (mr *MockInterfaceMockRecorder) DeleteInstances(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteInstances", reflect.TypeOf((*MockInterface)(nil).DeleteInstances), ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs) -} - -// DeleteInstancesAsync mocks base method. -func (m *MockInterface) DeleteInstancesAsync(ctx context.Context, resourceGroupName, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs, forceDelete bool) (*azure.Future, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteInstancesAsync", ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs, forceDelete) - ret0, _ := ret[0].(*azure.Future) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// DeleteInstancesAsync indicates an expected call of DeleteInstancesAsync. -func (mr *MockInterfaceMockRecorder) DeleteInstancesAsync(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs, forceDelete any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteInstancesAsync", reflect.TypeOf((*MockInterface)(nil).DeleteInstancesAsync), ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs, forceDelete) -} - -// Get mocks base method. -func (m *MockInterface) Get(ctx context.Context, resourceGroupName, VMScaleSetName string) (compute.VirtualMachineScaleSet, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", ctx, resourceGroupName, VMScaleSetName) - ret0, _ := ret[0].(compute.VirtualMachineScaleSet) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, VMScaleSetName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, VMScaleSetName) -} - -// List mocks base method. -func (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachineScaleSet, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "List", ctx, resourceGroupName) - ret0, _ := ret[0].([]compute.VirtualMachineScaleSet) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// List indicates an expected call of List. -func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName) -} - -// StartInstancesAsync mocks base method. -func (m *MockInterface) StartInstancesAsync(ctx context.Context, resourceGroupName, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "StartInstancesAsync", ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs) - ret0, _ := ret[0].(*azure.Future) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// StartInstancesAsync indicates an expected call of StartInstancesAsync. -func (mr *MockInterfaceMockRecorder) StartInstancesAsync(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StartInstancesAsync", reflect.TypeOf((*MockInterface)(nil).StartInstancesAsync), ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs) -} - -// WaitForAsyncOperationResult mocks base method. -func (m *MockInterface) WaitForAsyncOperationResult(ctx context.Context, future *azure.Future, resourceGroupName, request, asyncOpName string) (*http.Response, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WaitForAsyncOperationResult", ctx, future, resourceGroupName, request, asyncOpName) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WaitForAsyncOperationResult indicates an expected call of WaitForAsyncOperationResult. -func (mr *MockInterfaceMockRecorder) WaitForAsyncOperationResult(ctx, future, resourceGroupName, request, asyncOpName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitForAsyncOperationResult", reflect.TypeOf((*MockInterface)(nil).WaitForAsyncOperationResult), ctx, future, resourceGroupName, request, asyncOpName) -} - -// WaitForCreateOrUpdateResult mocks base method. -func (m *MockInterface) WaitForCreateOrUpdateResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WaitForCreateOrUpdateResult", ctx, future, resourceGroupName) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WaitForCreateOrUpdateResult indicates an expected call of WaitForCreateOrUpdateResult. -func (mr *MockInterfaceMockRecorder) WaitForCreateOrUpdateResult(ctx, future, resourceGroupName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitForCreateOrUpdateResult", reflect.TypeOf((*MockInterface)(nil).WaitForCreateOrUpdateResult), ctx, future, resourceGroupName) -} - -// WaitForDeallocateInstancesResult mocks base method. -func (m *MockInterface) WaitForDeallocateInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WaitForDeallocateInstancesResult", ctx, future, resourceGroupName) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WaitForDeallocateInstancesResult indicates an expected call of WaitForDeallocateInstancesResult. -func (mr *MockInterfaceMockRecorder) WaitForDeallocateInstancesResult(ctx, future, resourceGroupName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitForDeallocateInstancesResult", reflect.TypeOf((*MockInterface)(nil).WaitForDeallocateInstancesResult), ctx, future, resourceGroupName) -} - -// WaitForDeleteInstancesResult mocks base method. -func (m *MockInterface) WaitForDeleteInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WaitForDeleteInstancesResult", ctx, future, resourceGroupName) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WaitForDeleteInstancesResult indicates an expected call of WaitForDeleteInstancesResult. -func (mr *MockInterfaceMockRecorder) WaitForDeleteInstancesResult(ctx, future, resourceGroupName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitForDeleteInstancesResult", reflect.TypeOf((*MockInterface)(nil).WaitForDeleteInstancesResult), ctx, future, resourceGroupName) -} - -// WaitForStartInstancesResult mocks base method. -func (m *MockInterface) WaitForStartInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WaitForStartInstancesResult", ctx, future, resourceGroupName) - ret0, _ := ret[0].(*http.Response) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WaitForStartInstancesResult indicates an expected call of WaitForStartInstancesResult. -func (mr *MockInterfaceMockRecorder) WaitForStartInstancesResult(ctx, future, resourceGroupName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitForStartInstancesResult", reflect.TypeOf((*MockInterface)(nil).WaitForStartInstancesResult), ctx, future, resourceGroupName) -} diff --git a/pkg/azureclients/vmssvmclient/azure_vmssvmclient.go b/pkg/azureclients/vmssvmclient/azure_vmssvmclient.go deleted file mode 100644 index cdc6a169d4..0000000000 --- a/pkg/azureclients/vmssvmclient/azure_vmssvmclient.go +++ /dev/null @@ -1,604 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package vmssvmclient - -import ( - "context" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/client-go/util/flowcontrol" - "k8s.io/klog/v2" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/metrics" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -var _ Interface = &Client{} - -const ( - vmssResourceType = "Microsoft.Compute/virtualMachineScaleSets" - vmResourceType = "virtualMachines" -) - -// Client implements VMSS client Interface. -type Client struct { - armClient armclient.Interface - subscriptionID string - cloudName string - - // Rate limiting configures. - rateLimiterReader flowcontrol.RateLimiter - rateLimiterWriter flowcontrol.RateLimiter - - // ARM throttling configures. - RetryAfterReader time.Time - RetryAfterWriter time.Time -} - -// New creates a new vmssVM client with ratelimiting. -func New(config *azclients.ClientConfig) *Client { - baseURI := config.ResourceManagerEndpoint - authorizer := config.Authorizer - apiVersion := APIVersion - if strings.EqualFold(config.CloudName, AzureStackCloudName) && !config.DisableAzureStackCloud { - apiVersion = AzureStackCloudAPIVersion - } - armClient := armclient.New(authorizer, *config, baseURI, apiVersion) - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig) - - if azclients.RateLimitEnabled(config.RateLimitConfig) { - klog.V(2).Infof("Azure vmssVM client (read ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPS, - config.RateLimitConfig.CloudProviderRateLimitBucket) - klog.V(2).Infof("Azure vmssVM client (write ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPSWrite, - config.RateLimitConfig.CloudProviderRateLimitBucketWrite) - } - - client := &Client{ - armClient: armClient, - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - subscriptionID: config.SubscriptionID, - cloudName: config.CloudName, - } - - return client -} - -// Get gets a VirtualMachineScaleSetVM. -func (c *Client) Get(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, expand compute.InstanceViewTypes) (compute.VirtualMachineScaleSetVM, *retry.Error) { - mc := metrics.NewMetricContext("vmssvm", "get", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return compute.VirtualMachineScaleSetVM{}, retry.GetRateLimitError(false, "VMSSVMGet") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSVMGet", "client throttled", c.RetryAfterReader) - return compute.VirtualMachineScaleSetVM{}, rerr - } - - result, rerr := c.getVMSSVM(ctx, resourceGroupName, VMScaleSetName, instanceID, expand) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// getVMSSVM gets a VirtualMachineScaleSetVM. -func (c *Client) getVMSSVM(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, expand compute.InstanceViewTypes) (compute.VirtualMachineScaleSetVM, *retry.Error) { - resourceID := armclient.GetChildResourceID( - c.subscriptionID, - resourceGroupName, - vmssResourceType, - VMScaleSetName, - vmResourceType, - instanceID, - ) - result := compute.VirtualMachineScaleSetVM{} - - response, rerr := c.armClient.GetResourceWithExpandQuery(ctx, resourceID, string(expand)) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmssvm.get.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmssvm.get.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} - -// List gets a list of VirtualMachineScaleSetVMs in the virtualMachineScaleSet. -func (c *Client) List(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, expand string) ([]compute.VirtualMachineScaleSetVM, *retry.Error) { - mc := metrics.NewMetricContext("vmssvm", "list", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(false, "VMSSVMList") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSVMList", "client throttled", c.RetryAfterReader) - return nil, rerr - } - - result, rerr := c.listVMSSVM(ctx, resourceGroupName, virtualMachineScaleSetName, expand) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// listVMSSVM gets a list of VirtualMachineScaleSetVMs in the virtualMachineScaleSet. -func (c *Client) listVMSSVM(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, expand string) ([]compute.VirtualMachineScaleSetVM, *retry.Error) { - resourceID := armclient.GetChildResourcesListID( - c.subscriptionID, - resourceGroupName, - vmssResourceType, - virtualMachineScaleSetName, - vmResourceType, - ) - - result := make([]compute.VirtualMachineScaleSetVM, 0) - page := &VirtualMachineScaleSetVMListResultPage{} - page.fn = c.listNextResults - - resp, rerr := c.armClient.GetResourceWithExpandQuery(ctx, resourceID, expand) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmssvm.list.request", resourceID, rerr.Error()) - return result, rerr - } - - var err error - page.vmssvlr, err = c.listResponder(resp) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmssvm.list.respond", resourceID, err) - return result, retry.GetError(resp, err) - } - - for { - result = append(result, page.Values()...) - - // Abort the loop when there's no nextLink in the response. - if ptr.Deref(page.Response().NextLink, "") == "" { - break - } - - if err = page.NextWithContext(ctx); err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmssvm.list.next", resourceID, err) - return result, retry.GetError(page.Response().Response.Response, err) - } - } - - return result, nil -} - -// Update updates a VirtualMachineScaleSetVM. -func (c *Client) Update(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters compute.VirtualMachineScaleSetVM, source string) (*compute.VirtualMachineScaleSetVM, *retry.Error) { - mc := metrics.NewMetricContext("vmssvm", "update", resourceGroupName, c.subscriptionID, source) - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(true, "VMSSVMUpdate") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSVMUpdate", "client throttled", c.RetryAfterWriter) - return nil, rerr - } - - result, rerr := c.updateVMSSVM(ctx, resourceGroupName, VMScaleSetName, instanceID, parameters) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - } - - return result, rerr -} - -// UpdateAsync updates a VirtualMachineScaleSetVM asynchronously -func (c *Client) UpdateAsync(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters compute.VirtualMachineScaleSetVM, source string) (*azure.Future, *retry.Error) { - mc := metrics.NewMetricContext("vmssvm", "updateasync", resourceGroupName, c.subscriptionID, source) - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(true, "VMSSVMUpdateAsync") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSVMUpdateAsync", "client throttled", c.RetryAfterWriter) - return nil, rerr - } - - resourceID := armclient.GetChildResourceID( - c.subscriptionID, - resourceGroupName, - vmssResourceType, - VMScaleSetName, - vmResourceType, - instanceID, - ) - - future, rerr := c.armClient.PutResourceAsync(ctx, resourceID, parameters) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return nil, rerr - } - - return future, nil -} - -// WaitForUpdateResult waits for the response of the update request -func (c *Client) WaitForUpdateResult(ctx context.Context, future *azure.Future, resourceGroupName, source string) (*compute.VirtualMachineScaleSetVM, *retry.Error) { - mc := metrics.NewMetricContext("vmss", "wait_for_update_result", resourceGroupName, c.subscriptionID, source) - response, err := c.armClient.WaitForAsyncOperationResult(ctx, future, "VMSSWaitForUpdateResult") - mc.Observe(retry.NewErrorOrNil(false, err)) - defer c.armClient.CloseResponse(ctx, response) - - if err != nil { - if response != nil { - klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', response code %d", err.Error(), response.StatusCode) - } else { - klog.V(5).Infof("Received error in WaitForAsyncOperationResult: '%s', no response", err.Error()) - } - return nil, retry.GetError(response, err) - } - - if response != nil && response.StatusCode != http.StatusNoContent { - result, rerr := c.updateResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in WaitForAsyncOperationResult updateResponder: '%s'", rerr.Error()) - } - - return result, rerr - } - - result := &compute.VirtualMachineScaleSetVM{} - result.Response = autorest.Response{Response: response} - return result, nil -} - -// updateVMSSVM updates a VirtualMachineScaleSetVM. -func (c *Client) updateVMSSVM(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters compute.VirtualMachineScaleSetVM) (*compute.VirtualMachineScaleSetVM, *retry.Error) { - resourceID := armclient.GetChildResourceID( - c.subscriptionID, - resourceGroupName, - vmssResourceType, - VMScaleSetName, - vmResourceType, - instanceID, - ) - - response, rerr := c.armClient.PutResource(ctx, resourceID, parameters) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmssvm.put.request", resourceID, rerr.Error()) - return nil, rerr - } - - if response != nil && response.StatusCode != http.StatusNoContent { - result, rerr := c.updateResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmssvm.put.respond", resourceID, rerr.Error()) - } - return result, rerr - } - - result := &compute.VirtualMachineScaleSetVM{} - result.Response = autorest.Response{Response: response} - return result, nil -} - -func (c *Client) updateResponder(resp *http.Response) (*compute.VirtualMachineScaleSetVM, *retry.Error) { - result := &compute.VirtualMachineScaleSetVM{} - err := autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return result, retry.GetError(resp, err) -} - -func (c *Client) listResponder(resp *http.Response) (result compute.VirtualMachineScaleSetVMListResult, err error) { - err = autorest.Respond( - resp, - autorest.ByIgnoring(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return -} - -// virtualMachineScaleSetListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (c *Client) virtualMachineScaleSetVMListResultPreparer(ctx context.Context, vmssvmlr compute.VirtualMachineScaleSetVMListResult) (*http.Request, error) { - if vmssvmlr.NextLink == nil || len(ptr.Deref(vmssvmlr.NextLink, "")) < 1 { - return nil, nil - } - - decorators := []autorest.PrepareDecorator{ - autorest.WithBaseURL(ptr.Deref(vmssvmlr.NextLink, "")), - } - return c.armClient.PrepareGetRequest(ctx, decorators...) -} - -// listNextResults retrieves the next set of results, if any. -func (c *Client) listNextResults(ctx context.Context, lastResults compute.VirtualMachineScaleSetVMListResult) (result compute.VirtualMachineScaleSetVMListResult, err error) { - req, err := c.virtualMachineScaleSetVMListResultPreparer(ctx, lastResults) - if err != nil { - return result, autorest.NewErrorWithError(err, "vmssvmclient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - - resp, rerr := c.armClient.Send(ctx, req) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(rerr.Error(), "vmssvmclient", "listNextResults", resp, "Failure sending next results request") - } - - result, err = c.listResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "vmssvmclient", "listNextResults", resp, "Failure responding to next results request") - } - - return -} - -// VirtualMachineScaleSetVMListResultPage contains a page of VirtualMachineScaleSetVM values. -type VirtualMachineScaleSetVMListResultPage struct { - fn func(context.Context, compute.VirtualMachineScaleSetVMListResult) (compute.VirtualMachineScaleSetVMListResult, error) - vmssvlr compute.VirtualMachineScaleSetVMListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualMachineScaleSetVMListResultPage) NextWithContext(ctx context.Context) (err error) { - next, err := page.fn(ctx, page.vmssvlr) - if err != nil { - return err - } - page.vmssvlr = next - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualMachineScaleSetVMListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualMachineScaleSetVMListResultPage) NotDone() bool { - return !page.vmssvlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualMachineScaleSetVMListResultPage) Response() compute.VirtualMachineScaleSetVMListResult { - return page.vmssvlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualMachineScaleSetVMListResultPage) Values() []compute.VirtualMachineScaleSetVM { - if page.vmssvlr.IsEmpty() { - return nil - } - return *page.vmssvlr.Value -} - -// UpdateVMs updates a list of VirtualMachineScaleSetVM from map[instanceID]compute.VirtualMachineScaleSetVM. -// If the batch size > 0, it will send sync requests concurrently in batches, or it will send sync requests in sequence. -// No matter what the batch size is, it will process the async requests concurrently in one single batch. -func (c *Client) UpdateVMs(ctx context.Context, resourceGroupName string, VMScaleSetName string, instances map[string]compute.VirtualMachineScaleSetVM, source string, batchSize int) *retry.Error { - mc := metrics.NewMetricContext("vmssvm", "update_vms", resourceGroupName, c.subscriptionID, source) - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "VMSSVMUpdateVMs") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("VMSSVMUpdateVMs", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.updateVMSSVMs(ctx, resourceGroupName, VMScaleSetName, instances, batchSize) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// updateVMSSVMs updates a list of VirtualMachineScaleSetVM from map[instanceID]compute.VirtualMachineScaleSetVM. -func (c *Client) updateVMSSVMs(ctx context.Context, resourceGroupName string, VMScaleSetName string, instances map[string]compute.VirtualMachineScaleSetVM, batchSize int) *retry.Error { - resources := make(map[string]interface{}) - for instanceID, parameter := range instances { - resourceID := armclient.GetChildResourceID( - c.subscriptionID, - resourceGroupName, - vmssResourceType, - VMScaleSetName, - vmResourceType, - instanceID, - ) - resources[resourceID] = parameter - } - - responses := c.armClient.PutResourcesInBatches(ctx, resources, batchSize) - errors, retryIDs := c.parseResp(ctx, responses, true) - if len(retryIDs) > 0 { - retryResources := make(map[string]interface{}) - for _, id := range retryIDs { - retryResources[id] = resources[id] - } - resps := c.armClient.PutResourcesInBatches(ctx, retryResources, batchSize) - errs, _ := c.parseResp(ctx, resps, false) - errors = append(errors, errs...) - } - - // Aggregate errors. - if len(errors) > 0 { - rerr := &retry.Error{} - errs := make([]error, 0) - for _, err := range errors { - if !err.Retriable && strings.Contains(err.Error().Error(), consts.ConcurrentRequestConflictMessage) { - err.Retriable = true - err.RetryAfter = time.Now().Add(5 * time.Second) - } - - if err.IsThrottled() && err.RetryAfter.After(rerr.RetryAfter) { - rerr.RetryAfter = err.RetryAfter - } - errs = append(errs, err.Error()) - } - rerr.RawError = utilerrors.Flatten(utilerrors.NewAggregate(errs)) - return rerr - } - - return nil -} - -func (c *Client) parseResp( - ctx context.Context, - responses map[string]*armclient.PutResourcesResponse, - shouldRetry bool, -) ([]*retry.Error, []string) { - var ( - errors []*retry.Error - retryIDs []string - ) - for resourceID, resp := range responses { - if resp == nil { - continue - } - - defer c.armClient.CloseResponse(ctx, resp.Response) - if resp.Error != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmssvm.put.request", resourceID, resp.Error.Error()) - - errMsg := resp.Error.Error().Error() - if strings.Contains(errMsg, consts.VmssVMNotActiveErrorMessage) { - klog.V(2).Infof("VMSS VM %s is not active, skip updating it.", resourceID) - continue - } - if strings.Contains(errMsg, consts.ParentResourceNotFoundMessageCode) { - klog.V(2).Infof("The parent resource of VMSS VM %s is not found, skip updating it.", resourceID) - continue - } - if strings.Contains(errMsg, consts.CannotUpdateVMBeingDeletedMessagePrefix) && - strings.Contains(errMsg, consts.CannotUpdateVMBeingDeletedMessageSuffix) { - klog.V(2).Infof("The VM %s is being deleted, skip updating it.", resourceID) - continue - } - - if retry.IsSuccessHTTPResponse(resp.Response) && - strings.Contains( - strings.ToLower(errMsg), - strings.ToLower(consts.OperationPreemptedErrorMessage), - ) { - if shouldRetry { - klog.V(2).Infof("The operation on VM %s is preempted, will retry.", resourceID) - retryIDs = append(retryIDs, resourceID) - continue - } - klog.V(2).Infof("The operation on VM %s is preempted, will not retry.", resourceID) - } - - errors = append(errors, resp.Error) - continue - } - - if resp.Response != nil && resp.Response.StatusCode != http.StatusNoContent { - _, rerr := c.updateResponder(resp.Response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "vmssvm.put.respond", resourceID, rerr.Error()) - errors = append(errors, rerr) - } - } - } - return errors, retryIDs -} diff --git a/pkg/azureclients/vmssvmclient/azure_vmssvmclient_test.go b/pkg/azureclients/vmssvmclient/azure_vmssvmclient_test.go deleted file mode 100644 index 269ed208b5..0000000000 --- a/pkg/azureclients/vmssvmclient/azure_vmssvmclient_test.go +++ /dev/null @@ -1,984 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package vmssvmclient - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "testing" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/stretchr/testify/assert" - - "go.uber.org/mock/gomock" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient/mockarmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - testResourceID = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss1/virtualMachines/0" - testResourcePrefix = "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss1/virtualMachines" -) - -func TestNew(t *testing.T) { - config := &azclients.ClientConfig{ - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - vmssvmClient := New(config) - assert.Equal(t, "sub", vmssvmClient.subscriptionID) - assert.NotEmpty(t, vmssvmClient.rateLimiterReader) - assert.NotEmpty(t, vmssvmClient.rateLimiterWriter) -} - -func TestNewAzureStack(t *testing.T) { - config := &azclients.ClientConfig{ - CloudName: "AZURESTACKCLOUD", - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - vmssvmClient := New(config) - assert.Equal(t, "AZURESTACKCLOUD", vmssvmClient.cloudName) - assert.Equal(t, "sub", vmssvmClient.subscriptionID) -} - -func TestGet(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "InstanceView").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - expected := compute.VirtualMachineScaleSetVM{Response: autorest.Response{Response: response}} - vmssvmClient := getTestVMSSVMClient(armClient) - result, rerr := vmssvmClient.Get(context.TODO(), "rg", "vmss1", "0", "InstanceView") - assert.Equal(t, expected, result) - assert.Nil(t, rerr) -} - -func TestGetNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssvmGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "VMSSVMGet"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssvmClient := getTestVMSSVMClientWithNeverRateLimiter(armClient) - expected := compute.VirtualMachineScaleSetVM{} - result, rerr := vmssvmClient.Get(context.TODO(), "rg", "vmss1", "0", "InstanceView") - assert.Equal(t, expected, result) - assert.Equal(t, vmssvmGetErr, rerr) -} - -func TestGetRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssvmGetErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMSSVMGet", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssvmClient := getTestVMSSVMClientWithRetryAfterReader(armClient) - expected := compute.VirtualMachineScaleSetVM{} - result, rerr := vmssvmClient.Get(context.TODO(), "rg", "vmss1", "0", "InstanceView") - assert.Equal(t, expected, result) - assert.Equal(t, vmssvmGetErr, rerr) -} - -func TestGetNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "InstanceView").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSVMClient(armClient) - expectedVM := compute.VirtualMachineScaleSetVM{Response: autorest.Response{}} - result, rerr := vmssClient.Get(context.TODO(), "rg", "vmss1", "0", "InstanceView") - assert.Equal(t, expectedVM, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestGetInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss1/virtualMachines/1" - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), resourceID, "InstanceView").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSVMClient(armClient) - expectedVM := compute.VirtualMachineScaleSetVM{Response: autorest.Response{}} - result, rerr := vmssClient.Get(context.TODO(), "rg", "vmss1", "1", "InstanceView") - assert.Equal(t, expectedVM, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestGetThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "InstanceView").Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssvmClient := getTestVMSSVMClient(armClient) - result, rerr := vmssvmClient.Get(context.TODO(), "rg", "vmss1", "0", "InstanceView") - assert.Empty(t, result) - assert.Equal(t, throttleErr, rerr) -} - -func TestList(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssList := []compute.VirtualMachineScaleSetVM{getTestVMSSVM("vmss1", "1"), getTestVMSSVM("vmss1", "2"), getTestVMSSVM("vmss1", "3")} - responseBody, err := json.Marshal(compute.VirtualMachineScaleSetVMListResult{Value: &vmssList}) - assert.NoError(t, err) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourcePrefix, "InstanceView").Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSVMClient(armClient) - result, rerr := vmssClient.List(context.TODO(), "rg", "vmss1", "InstanceView") - assert.Nil(t, rerr) - assert.Equal(t, 3, len(result)) -} - -func TestListNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourcePrefix, "InstanceView").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssvmClient := getTestVMSSVMClient(armClient) - expected := []compute.VirtualMachineScaleSetVM{} - result, rerr := vmssvmClient.List(context.TODO(), "rg", "vmss1", "InstanceView") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestListInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourcePrefix, "InstanceView").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssvmClient := getTestVMSSVMClient(armClient) - expected := []compute.VirtualMachineScaleSetVM{} - result, rerr := vmssvmClient.List(context.TODO(), "rg", "vmss1", "InstanceView") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestListThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourcePrefix, "InstanceView").Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmssvmClient := getTestVMSSVMClient(armClient) - result, rerr := vmssvmClient.List(context.TODO(), "rg", "vmss1", "InstanceView") - assert.Empty(t, result) - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) -} - -func TestListWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssvmList := []compute.VirtualMachineScaleSetVM{getTestVMSSVM("vmss1", "1"), getTestVMSSVM("vmss1", "2"), getTestVMSSVM("vmss1", "3")} - responseBody, err := json.Marshal(compute.VirtualMachineScaleSetVMListResult{Value: &vmssvmList}) - assert.NoError(t, err) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourcePrefix, "InstanceView").Return( - &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - vmssvmClient := getTestVMSSVMClient(armClient) - result, rerr := vmssvmClient.List(context.TODO(), "rg", "vmss1", "InstanceView") - assert.NotNil(t, rerr) - assert.Equal(t, 0, len(result)) -} - -func TestListWithNextPage(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssvmList := []compute.VirtualMachineScaleSetVM{getTestVMSSVM("vmss1", "1"), getTestVMSSVM("vmss1", "2"), getTestVMSSVM("vmss1", "3")} - partialResponse, err := json.Marshal(compute.VirtualMachineScaleSetVMListResult{Value: &vmssvmList, NextLink: ptr.To("nextLink")}) - assert.NoError(t, err) - pagedResponse, err := json.Marshal(compute.VirtualMachineScaleSetVMListResult{Value: &vmssvmList}) - assert.NoError(t, err) - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(&http.Request{}, nil) - armClient.EXPECT().Send(gomock.Any(), gomock.Any()).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(pagedResponse)), - }, nil) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourcePrefix, "InstanceView").Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(partialResponse)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(2) - vmssvmClient := getTestVMSSVMClient(armClient) - result, rerr := vmssvmClient.List(context.TODO(), "rg", "vmss1", "InstanceView") - assert.Nil(t, rerr) - assert.Equal(t, 6, len(result)) -} - -func TestListNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssvmListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "read", "VMSSVMList"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssvmClient := getTestVMSSVMClientWithNeverRateLimiter(armClient) - result, rerr := vmssvmClient.List(context.TODO(), "rg", "vmss1", "InstanceView") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, vmssvmListErr, rerr) -} - -func TestListRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssvmListErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMSSVMList", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssvmClient := getTestVMSSVMClientWithRetryAfterReader(armClient) - result, rerr := vmssvmClient.List(context.TODO(), "rg", "vmss1", "InstanceView") - assert.Equal(t, 0, len(result)) - assert.NotNil(t, rerr) - assert.Equal(t, vmssvmListErr, rerr) -} - -func TestListNextResultsMultiPages(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - name string - prepareErr error - sendErr *retry.Error - expectedErrMsg string - }{ - { - name: "testlistNextResultsSuccessful", - prepareErr: nil, - sendErr: nil, - }, - { - name: "testPrepareGetRequestError", - prepareErr: fmt.Errorf("error"), - expectedErrMsg: "Failure preparing next results request", - }, - { - name: "testSendError", - sendErr: &retry.Error{RawError: fmt.Errorf("error")}, - expectedErrMsg: "Failure sending next results request", - }, - } - - lastResult := compute.VirtualMachineScaleSetVMListResult{ - NextLink: ptr.To("next"), - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - vmssClient := getTestVMSSVMClient(armClient) - result, err := vmssClient.listNextResults(context.TODO(), lastResult) - if err != nil { - detailedErr := &autorest.DetailedError{} - assert.True(t, errors.As(err, detailedErr)) - assert.Equal(t, detailedErr.Message, test.expectedErrMsg) - } else { - assert.NoError(t, err) - } - - if test.prepareErr != nil { - assert.Empty(t, result) - } else { - assert.NotEmpty(t, result) - } - } -} - -func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - name string - prepareErr error - sendErr *retry.Error - }{ - { - name: "testListResponderError", - prepareErr: nil, - sendErr: nil, - }, - { - name: "testSendError", - sendErr: &retry.Error{RawError: fmt.Errorf("error")}, - }, - } - - lastResult := compute.VirtualMachineScaleSetVMListResult{ - NextLink: ptr.To("next"), - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewBuffer([]byte(`{"foo":"bar"}`))), - } - expected := compute.VirtualMachineScaleSetVMListResult{} - expected.Response = autorest.Response{Response: response} - vmssClient := getTestVMSSVMClient(armClient) - result, err := vmssClient.listNextResults(context.TODO(), lastResult) - assert.Error(t, err) - if test.sendErr != nil { - assert.NotEqual(t, expected, result) - } else { - assert.Equal(t, expected, result) - } - } -} - -func TestUpdate(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssVM := getTestVMSSVM("vmss1", "0") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(vmssVM.ID, ""), vmssVM).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - expected := &compute.VirtualMachineScaleSetVM{} - expected.Response = autorest.Response{Response: response} - - vmssClient := getTestVMSSVMClient(armClient) - result, rerr := vmssClient.Update(context.TODO(), "rg", "vmss1", "0", vmssVM, "test") - assert.Nil(t, rerr) - assert.Equal(t, expected, result) -} - -func TestUpdateAsync(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssVM := getTestVMSSVM("vmss1", "0") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PutResourceAsync(gomock.Any(), ptr.Deref(vmssVM.ID, ""), vmssVM).Return(nil, nil).Times(1) - - vmssClient := getTestVMSSVMClient(armClient) - future, rerr := vmssClient.UpdateAsync(context.TODO(), "rg", "vmss1", "0", vmssVM, "test") - assert.Nil(t, rerr) - assert.Nil(t, future) -} - -func TestWaitForUpdateResult(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - preemptErr := fmt.Errorf("operation execution has been preempted by a more recent operation") - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - - tests := []struct { - name string - response *http.Response - responseErr error - expectedResult *retry.Error - }{ - { - name: "Success", - response: response, - responseErr: nil, - expectedResult: nil, - }, - { - name: "Success with nil response", - response: nil, - responseErr: nil, - expectedResult: nil, - }, - { - name: "Failed", - response: response, - responseErr: preemptErr, - expectedResult: retry.GetError(response, preemptErr), - }, - { - name: "Failed with nil response", - response: nil, - responseErr: preemptErr, - expectedResult: retry.GetError(nil, preemptErr), - }, - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().WaitForAsyncOperationResult(gomock.Any(), gomock.Any(), "VMSSWaitForUpdateResult").Return(test.response, test.responseErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssClient := getTestVMSSVMClient(armClient) - response, err := vmssClient.WaitForUpdateResult(context.TODO(), &azure.Future{}, "rg", "test") - assert.Equal(t, err, test.expectedResult) - var output *compute.VirtualMachineScaleSetVM - if err == nil { - output = &compute.VirtualMachineScaleSetVM{} - output.Response = autorest.Response{Response: test.response} - } - assert.Equal(t, response, output) - } -} - -func TestUpdateWithUpdateResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssVM := getTestVMSSVM("vmss1", "0") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(vmssVM.ID, ""), vmssVM).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - expected := &compute.VirtualMachineScaleSetVM{} - expected.Response = autorest.Response{Response: response} - - vmssvmClient := getTestVMSSVMClient(armClient) - result, rerr := vmssvmClient.Update(context.TODO(), "rg", "vmss1", "0", vmssVM, "test") - assert.NotNil(t, rerr) - assert.Equal(t, expected, result) -} - -func TestUpdateNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssvmUpdateErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "write", "VMSSVMUpdate"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssvmClient := getTestVMSSVMClientWithNeverRateLimiter(armClient) - vmssVM := getTestVMSSVM("vmss1", "0") - var expected *compute.VirtualMachineScaleSetVM - result, rerr := vmssvmClient.Update(context.TODO(), "rg", "vmss1", "0", vmssVM, "test") - assert.NotNil(t, rerr) - assert.Equal(t, vmssvmUpdateErr, rerr) - assert.Equal(t, expected, result) -} - -func TestUpdateRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssvmUpdateErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMSSVMUpdate", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - vmssVM := getTestVMSSVM("vmss1", "0") - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMSSVMClientWithRetryAfterReader(armClient) - var expected *compute.VirtualMachineScaleSetVM - result, rerr := vmClient.Update(context.TODO(), "rg", "vmss1", "0", vmssVM, "test") - assert.NotNil(t, rerr) - assert.Equal(t, vmssvmUpdateErr, rerr) - assert.Equal(t, expected, result) -} - -func TestUpdateThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - - vmssVM := getTestVMSSVM("vmss1", "0") - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(vmssVM.ID, ""), vmssVM).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssvmClient := getTestVMSSVMClient(armClient) - var expected *compute.VirtualMachineScaleSetVM - result, rerr := vmssvmClient.Update(context.TODO(), "rg", "vmss1", "0", vmssVM, "test") - assert.NotNil(t, rerr) - assert.Equal(t, throttleErr, rerr) - assert.Equal(t, expected, result) -} - -func TestUpdateVMs(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssVM1 := getTestVMSSVM("vmss1", "1") - vmssVM2 := getTestVMSSVM("vmss1", "2") - instances := map[string]compute.VirtualMachineScaleSetVM{ - "1": vmssVM1, - "2": vmssVM2, - } - testvmssVMs := map[string]interface{}{ - ptr.Deref(vmssVM1.ID, ""): vmssVM1, - ptr.Deref(vmssVM2.ID, ""): vmssVM2, - } - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - responses := map[string]*armclient.PutResourcesResponse{ - ptr.Deref(vmssVM1.ID, ""): { - Response: response, - }, - ptr.Deref(vmssVM2.ID, ""): { - Response: response, - }, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PutResourcesInBatches(gomock.Any(), testvmssVMs, 0).Return(responses).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(2) - - vmssvmClient := getTestVMSSVMClient(armClient) - rerr := vmssvmClient.UpdateVMs(context.TODO(), "rg", "vmss1", instances, "test", 0) - assert.Nil(t, rerr) -} - -func TestUpdateVMsWithUpdateVMsResponderError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssVM := getTestVMSSVM("vmss1", "1") - instances := map[string]compute.VirtualMachineScaleSetVM{ - "1": vmssVM, - } - testvmssVMs := map[string]interface{}{ - ptr.Deref(vmssVM.ID, ""): vmssVM, - } - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - responses := map[string]*armclient.PutResourcesResponse{ - ptr.Deref(vmssVM.ID, ""): { - Response: response, - }, - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PutResourcesInBatches(gomock.Any(), testvmssVMs, 0).Return(responses).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssvmClient := getTestVMSSVMClient(armClient) - rerr := vmssvmClient.UpdateVMs(context.TODO(), "rg", "vmss1", instances, "test", 0) - assert.NotNil(t, rerr) -} - -func TestUpdateVMsPreemptedRetry(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssVM1 := getTestVMSSVM("vmss1", "1") - vmssVM2 := getTestVMSSVM("vmss1", "2") - instances := map[string]compute.VirtualMachineScaleSetVM{ - "1": vmssVM1, - "2": vmssVM2, - } - testvmssVMs1 := map[string]interface{}{ - ptr.Deref(vmssVM1.ID, ""): vmssVM1, - ptr.Deref(vmssVM2.ID, ""): vmssVM2, - } - testvmssVMs2 := map[string]interface{}{ - ptr.Deref(vmssVM2.ID, ""): vmssVM2, - } - resp1 := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - resp2 := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - preemptErr := retry.NewError(false, errors.New(consts.OperationPreemptedErrorMessage)) - resps1 := map[string]*armclient.PutResourcesResponse{ - ptr.Deref(vmssVM1.ID, ""): {Response: resp1}, - ptr.Deref(vmssVM2.ID, ""): {Response: resp2, Error: preemptErr}, - } - resps2 := map[string]*armclient.PutResourcesResponse{ - ptr.Deref(vmssVM2.ID, ""): {Response: resp2, Error: preemptErr}, - } - armClient := mockarmclient.NewMockInterface(ctrl) - firstPut := armClient.EXPECT().PutResourcesInBatches(gomock.Any(), testvmssVMs1, 0).Return(resps1) - armClient.EXPECT().PutResourcesInBatches(gomock.Any(), testvmssVMs2, 0).Return(resps2).After(firstPut) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(3) - - vmssvmClient := getTestVMSSVMClient(armClient) - rerr := vmssvmClient.UpdateVMs(context.TODO(), "rg", "vmss1", instances, "test", 0) - assert.NotNil(t, rerr) - assert.Contains(t, rerr.RawError.Error(), consts.OperationPreemptedErrorMessage) - - resps1 = map[string]*armclient.PutResourcesResponse{ - ptr.Deref(vmssVM2.ID, ""): {Response: resp2, Error: preemptErr}, - } - resps2 = map[string]*armclient.PutResourcesResponse{ - ptr.Deref(vmssVM2.ID, ""): {Response: resp2}, - } - firstPut = armClient.EXPECT().PutResourcesInBatches(gomock.Any(), testvmssVMs1, 0).Return(resps1) - armClient.EXPECT().PutResourcesInBatches(gomock.Any(), testvmssVMs2, 0).Return(resps2).After(firstPut) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(2) - - vmssvmClient = getTestVMSSVMClient(armClient) - rerr = vmssvmClient.UpdateVMs(context.TODO(), "rg", "vmss1", instances, "test", 0) - assert.Nil(t, rerr) -} - -func TestUpdateVMsNeverRateLimiter(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - instances := map[string]compute.VirtualMachineScaleSetVM{} - vmssvmUpdateVMsErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", "write", "VMSSVMUpdateVMs"), - Retriable: true, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmssvmClient := getTestVMSSVMClientWithNeverRateLimiter(armClient) - rerr := vmssvmClient.UpdateVMs(context.TODO(), "rg", "vmss1", instances, "test", 0) - assert.NotNil(t, rerr) - assert.Equal(t, vmssvmUpdateVMsErr, rerr) -} - -func TestUpdateVMsRetryAfterReader(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - instances := map[string]compute.VirtualMachineScaleSetVM{} - vmssvmUpdateVMsErr := &retry.Error{ - RawError: fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", "VMSSVMUpdateVMs", "client throttled"), - Retriable: true, - RetryAfter: getFutureTime(), - } - - armClient := mockarmclient.NewMockInterface(ctrl) - vmClient := getTestVMSSVMClientWithRetryAfterReader(armClient) - rerr := vmClient.UpdateVMs(context.TODO(), "rg", "vmss1", instances, "test", 0) - assert.NotNil(t, rerr) - assert.Equal(t, vmssvmUpdateVMsErr, rerr) -} - -func TestUpdateVMsThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssVM := getTestVMSSVM("vmss1", "1") - instances := map[string]compute.VirtualMachineScaleSetVM{ - "1": vmssVM, - } - testvmssVMs := map[string]interface{}{ - ptr.Deref(vmssVM.ID, ""): vmssVM, - } - throttleErr := retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - responses := map[string]*armclient.PutResourcesResponse{ - ptr.Deref(vmssVM.ID, ""): { - Response: &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - }, - Error: &throttleErr, - }, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PutResourcesInBatches(gomock.Any(), testvmssVMs, 0).Return(responses).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - vmssvmClient := getTestVMSSVMClient(armClient) - rerr := vmssvmClient.UpdateVMs(context.TODO(), "rg", "vmss1", instances, "test", 0) - assert.NotNil(t, rerr) - assert.EqualError(t, throttleErr.Error(), rerr.RawError.Error()) -} - -func TestUpdateVMsIgnoreError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - vmssVM := getTestVMSSVM("vmss1", "1") - vmssVM2 := getTestVMSSVM("vmss1", "2") - vmssVM3 := getTestVMSSVM("vmss1", "3") - vmssVM4 := getTestVMSSVM("vmss1", "4") - instances := map[string]compute.VirtualMachineScaleSetVM{ - "1": vmssVM, - "2": vmssVM2, - "3": vmssVM3, - "4": vmssVM4, - } - testvmssVMs := map[string]interface{}{ - ptr.Deref(vmssVM.ID, ""): vmssVM, - ptr.Deref(vmssVM2.ID, ""): vmssVM2, - ptr.Deref(vmssVM3.ID, ""): vmssVM3, - ptr.Deref(vmssVM4.ID, ""): vmssVM4, - } - notActiveError := retry.Error{ - RawError: fmt.Errorf(consts.VmssVMNotActiveErrorMessage), - Retriable: false, - } - parentResourceNotFoundError := retry.Error{ - RawError: fmt.Errorf(consts.ParentResourceNotFoundMessageCode), - Retriable: false, - } - concurrentRequestConflictError := retry.Error{ - RawError: fmt.Errorf(consts.ConcurrentRequestConflictMessage), - Retriable: false, - } - beingDeletedError := retry.Error{ - RawError: fmt.Errorf("operation 'Put on Virtual Machine Scale Set VM Instance' is not allowed on Virtual Machine Scale Set 'aks-stg1pool1-17586529-vmss' since it is marked for deletion. For more information on your operations, please refer to https://aka.ms/activitylog"), - Retriable: false, - } - responses := map[string]*armclient.PutResourcesResponse{ - ptr.Deref(vmssVM.ID, ""): { - Error: ¬ActiveError, - }, - ptr.Deref(vmssVM2.ID, ""): { - Error: &parentResourceNotFoundError, - }, - ptr.Deref(vmssVM3.ID, ""): { - Error: &concurrentRequestConflictError, - }, - ptr.Deref(vmssVM4.ID, ""): { - Error: &beingDeletedError, - }, - } - - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().PutResourcesInBatches(gomock.Any(), testvmssVMs, 0).Return(responses).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(len(instances)) - - vmssvmClient := getTestVMSSVMClient(armClient) - rerr := vmssvmClient.UpdateVMs(context.TODO(), "rg", "vmss1", instances, "test", 0) - assert.NotNil(t, rerr) - assert.Equal(t, rerr.Error().Error(), "Retriable: false, RetryAfter: 4s, HTTPStatusCode: 0, RawError: Retriable: true, RetryAfter: 4s, HTTPStatusCode: 0, RawError: The request failed due to conflict with a concurrent request.") -} - -func getTestVMSSVM(vmssName, instanceID string) compute.VirtualMachineScaleSetVM { - resourceID := fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/%s/virtualMachines/%s", vmssName, instanceID) - return compute.VirtualMachineScaleSetVM{ - ID: ptr.To(resourceID), - InstanceID: ptr.To(instanceID), - Location: ptr.To("eastus"), - } -} - -func getTestVMSSVMClient(armClient armclient.Interface) *Client { - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(&azclients.RateLimitConfig{}) - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestVMSSVMClientWithNeverRateLimiter(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeNeverRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeNeverRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} - -func getTestVMSSVMClientWithRetryAfterReader(armClient armclient.Interface) *Client { - rateLimiterReader := flowcontrol.NewFakeAlwaysRateLimiter() - rateLimiterWriter := flowcontrol.NewFakeAlwaysRateLimiter() - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - RetryAfterReader: getFutureTime(), - RetryAfterWriter: getFutureTime(), - } -} - -func getFutureTime() time.Time { - return time.Unix(3000000000, 0) -} diff --git a/pkg/azureclients/vmssvmclient/doc.go b/pkg/azureclients/vmssvmclient/doc.go deleted file mode 100644 index 885f695f34..0000000000 --- a/pkg/azureclients/vmssvmclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package vmssvmclient implements the client for VirtualMachineScaleSetVM. -package vmssvmclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssvmclient" diff --git a/pkg/azureclients/vmssvmclient/interface.go b/pkg/azureclients/vmssvmclient/interface.go deleted file mode 100644 index 352c3aa642..0000000000 --- a/pkg/azureclients/vmssvmclient/interface.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package vmssvmclient - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/azure" - - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - // APIVersion is the API version for VMSS. - APIVersion = "2022-03-01" - // AzureStackCloudAPIVersion is the API version for Azure Stack - AzureStackCloudAPIVersion = "2019-07-01" - // AzureStackCloudName is the cloud name of Azure Stack - AzureStackCloudName = "AZURESTACKCLOUD" -) - -// Interface is the client interface for VirtualMachineScaleSetVM. -// Don't forget to run "hack/update-mock-clients.sh" command to generate the mock client. -type Interface interface { - // Get gets a VirtualMachineScaleSetVM. - Get(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, expand compute.InstanceViewTypes) (compute.VirtualMachineScaleSetVM, *retry.Error) - - // List gets a list of VirtualMachineScaleSetVMs in the virtualMachineScaleSet. - List(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, expand string) ([]compute.VirtualMachineScaleSetVM, *retry.Error) - - // Update updates a VirtualMachineScaleSetVM. - Update(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters compute.VirtualMachineScaleSetVM, source string) (*compute.VirtualMachineScaleSetVM, *retry.Error) - - // UpdateAsync updates a VirtualMachineScaleSetVM asynchronously - UpdateAsync(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters compute.VirtualMachineScaleSetVM, source string) (*azure.Future, *retry.Error) - - // WaitForUpdateResult waits for the response of the update request - WaitForUpdateResult(ctx context.Context, future *azure.Future, resourceGroupName, source string) (*compute.VirtualMachineScaleSetVM, *retry.Error) - - // UpdateVMs updates a list of VirtualMachineScaleSetVM from map[instanceID]compute.VirtualMachineScaleSetVM. - UpdateVMs(ctx context.Context, resourceGroupName string, VMScaleSetName string, instances map[string]compute.VirtualMachineScaleSetVM, source string, batchSize int) *retry.Error -} diff --git a/pkg/azureclients/vmssvmclient/mockvmssvmclient/doc.go b/pkg/azureclients/vmssvmclient/mockvmssvmclient/doc.go deleted file mode 100644 index 10e986a1c1..0000000000 --- a/pkg/azureclients/vmssvmclient/mockvmssvmclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package mockvmssvmclient implements the mock client for VirtualMachineScaleSetVM. -package mockvmssvmclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssvmclient/mockvmssvmclient" diff --git a/pkg/azureclients/vmssvmclient/mockvmssvmclient/interface.go b/pkg/azureclients/vmssvmclient/mockvmssvmclient/interface.go deleted file mode 100644 index 0bc207ca6a..0000000000 --- a/pkg/azureclients/vmssvmclient/mockvmssvmclient/interface.go +++ /dev/null @@ -1,149 +0,0 @@ -// /* -// Copyright The Kubernetes Authors. -// -// 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 MockGen. DO NOT EDIT. -// Source: pkg/azureclients/vmssvmclient/interface.go -// -// Generated by this command: -// -// mockgen -copyright_file=/home/runner/work/cloud-provider-azure/cloud-provider-azure/hack/boilerplate/boilerplate.generatego.txt -source=pkg/azureclients/vmssvmclient/interface.go -package=mockvmssvmclient Interface -// - -// Package mockvmssvmclient is a generated GoMock package. -package mockvmssvmclient - -import ( - context "context" - reflect "reflect" - - compute "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - azure "github.com/Azure/go-autorest/autorest/azure" - gomock "go.uber.org/mock/gomock" - retry "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -// MockInterface is a mock of Interface interface. -type MockInterface struct { - ctrl *gomock.Controller - recorder *MockInterfaceMockRecorder -} - -// MockInterfaceMockRecorder is the mock recorder for MockInterface. -type MockInterfaceMockRecorder struct { - mock *MockInterface -} - -// NewMockInterface creates a new mock instance. -func NewMockInterface(ctrl *gomock.Controller) *MockInterface { - mock := &MockInterface{ctrl: ctrl} - mock.recorder = &MockInterfaceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { - return m.recorder -} - -// Get mocks base method. -func (m *MockInterface) Get(ctx context.Context, resourceGroupName, VMScaleSetName, instanceID string, expand compute.InstanceViewTypes) (compute.VirtualMachineScaleSetVM, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", ctx, resourceGroupName, VMScaleSetName, instanceID, expand) - ret0, _ := ret[0].(compute.VirtualMachineScaleSetVM) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, VMScaleSetName, instanceID, expand any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, VMScaleSetName, instanceID, expand) -} - -// List mocks base method. -func (m *MockInterface) List(ctx context.Context, resourceGroupName, virtualMachineScaleSetName, expand string) ([]compute.VirtualMachineScaleSetVM, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "List", ctx, resourceGroupName, virtualMachineScaleSetName, expand) - ret0, _ := ret[0].([]compute.VirtualMachineScaleSetVM) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// List indicates an expected call of List. -func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName, virtualMachineScaleSetName, expand any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName, virtualMachineScaleSetName, expand) -} - -// Update mocks base method. -func (m *MockInterface) Update(ctx context.Context, resourceGroupName, VMScaleSetName, instanceID string, parameters compute.VirtualMachineScaleSetVM, source string) (*compute.VirtualMachineScaleSetVM, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Update", ctx, resourceGroupName, VMScaleSetName, instanceID, parameters, source) - ret0, _ := ret[0].(*compute.VirtualMachineScaleSetVM) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// Update indicates an expected call of Update. -func (mr *MockInterfaceMockRecorder) Update(ctx, resourceGroupName, VMScaleSetName, instanceID, parameters, source any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockInterface)(nil).Update), ctx, resourceGroupName, VMScaleSetName, instanceID, parameters, source) -} - -// UpdateAsync mocks base method. -func (m *MockInterface) UpdateAsync(ctx context.Context, resourceGroupName, VMScaleSetName, instanceID string, parameters compute.VirtualMachineScaleSetVM, source string) (*azure.Future, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateAsync", ctx, resourceGroupName, VMScaleSetName, instanceID, parameters, source) - ret0, _ := ret[0].(*azure.Future) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// UpdateAsync indicates an expected call of UpdateAsync. -func (mr *MockInterfaceMockRecorder) UpdateAsync(ctx, resourceGroupName, VMScaleSetName, instanceID, parameters, source any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateAsync", reflect.TypeOf((*MockInterface)(nil).UpdateAsync), ctx, resourceGroupName, VMScaleSetName, instanceID, parameters, source) -} - -// UpdateVMs mocks base method. -func (m *MockInterface) UpdateVMs(ctx context.Context, resourceGroupName, VMScaleSetName string, instances map[string]compute.VirtualMachineScaleSetVM, source string, batchSize int) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateVMs", ctx, resourceGroupName, VMScaleSetName, instances, source, batchSize) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// UpdateVMs indicates an expected call of UpdateVMs. -func (mr *MockInterfaceMockRecorder) UpdateVMs(ctx, resourceGroupName, VMScaleSetName, instances, source, batchSize any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateVMs", reflect.TypeOf((*MockInterface)(nil).UpdateVMs), ctx, resourceGroupName, VMScaleSetName, instances, source, batchSize) -} - -// WaitForUpdateResult mocks base method. -func (m *MockInterface) WaitForUpdateResult(ctx context.Context, future *azure.Future, resourceGroupName, source string) (*compute.VirtualMachineScaleSetVM, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WaitForUpdateResult", ctx, future, resourceGroupName, source) - ret0, _ := ret[0].(*compute.VirtualMachineScaleSetVM) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// WaitForUpdateResult indicates an expected call of WaitForUpdateResult. -func (mr *MockInterfaceMockRecorder) WaitForUpdateResult(ctx, future, resourceGroupName, source any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WaitForUpdateResult", reflect.TypeOf((*MockInterface)(nil).WaitForUpdateResult), ctx, future, resourceGroupName, source) -} diff --git a/pkg/consts/consts.go b/pkg/consts/consts.go index 45ae303427..6f75dc435e 100644 --- a/pkg/consts/consts.go +++ b/pkg/consts/consts.go @@ -232,10 +232,10 @@ const ( // ref: https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits#load-balancer. MaximumLoadBalancerRuleCount = 250 - // LoadBalancerSkuBasic is the load balancer basic sku - LoadBalancerSkuBasic = "basic" - // LoadBalancerSkuStandard is the load balancer standard sku - LoadBalancerSkuStandard = "standard" + // LoadBalancerSKUBasic is the load balancer basic SKU + LoadBalancerSKUBasic = "basic" + // LoadBalancerSKUStandard is the load balancer standard SKU + LoadBalancerSKUStandard = "standard" // ServiceAnnotationLoadBalancerInternal is the annotation used on the service ServiceAnnotationLoadBalancerInternal = "service.beta.kubernetes.io/azure-load-balancer-internal" @@ -246,7 +246,7 @@ const ( // ServiceAnnotationLoadBalancerMode is the annotation used on the service to specify // which load balancer should be associated with the service. This is valid when using the basic - // sku load balancer, or it would be ignored. + // SKU load balancer, or it would be ignored. // 1. Default mode - service has no annotation ("service.beta.kubernetes.io/azure-load-balancer-mode") // In this case the Loadbalancer of the primary VMSS/VMAS is selected. // 2. "__auto__" mode - service is annotated with __auto__ value, this when loadbalancer from any VMSS/VMAS diff --git a/pkg/metrics/azure_metrics.go b/pkg/metrics/azure_metrics.go index b80c29fb7e..e161c5c4b1 100644 --- a/pkg/metrics/azure_metrics.go +++ b/pkg/metrics/azure_metrics.go @@ -25,7 +25,6 @@ import ( "k8s.io/klog/v2" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) var ( @@ -83,18 +82,6 @@ func (mc *MetricContext) ThrottledCount() { apiMetrics.throttledCount.WithLabelValues(mc.attributes...).Inc() } -// Observe observes the request latency and failed requests. -func (mc *MetricContext) Observe(rerr *retry.Error, labelAndValues ...interface{}) { - latency := time.Since(mc.start).Seconds() - apiMetrics.latency.WithLabelValues(mc.attributes...).Observe(latency) - if rerr != nil { - errorCode := rerr.ServiceErrorCode() - attributes := append(mc.attributes, errorCode) - apiMetrics.errors.WithLabelValues(attributes...).Inc() - } - mc.logLatency(6, latency, append(labelAndValues, "error_code", rerr.ServiceErrorCode())...) -} - // ObserveOperationWithResult observes the request latency and failed requests of an operation. func (mc *MetricContext) ObserveOperationWithResult(isOperationSucceeded bool, labelAndValues ...interface{}) { latency := time.Since(mc.start).Seconds() diff --git a/pkg/nodeipam/ipam/cloud_cidr_allocator_test.go b/pkg/nodeipam/ipam/cloud_cidr_allocator_test.go index c1556966c1..872feb3502 100644 --- a/pkg/nodeipam/ipam/cloud_cidr_allocator_test.go +++ b/pkg/nodeipam/ipam/cloud_cidr_allocator_test.go @@ -23,18 +23,18 @@ import ( "testing" "time" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes/fake" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/mock_virtualmachinescalesetclient" "sigs.k8s.io/cloud-provider-azure/pkg/consts" azureprovider "sigs.k8s.io/cloud-provider-azure/pkg/provider" "sigs.k8s.io/cloud-provider-azure/pkg/util/controller/testutil" @@ -208,18 +208,18 @@ func TestUpdateNodeSubnetMaskSizes(t *testing.T) { ss, err := azureprovider.NewTestScaleSet(ctrl) assert.NoError(t, err) - expectedVMSS := compute.VirtualMachineScaleSet{ + expectedVMSS := &armcompute.VirtualMachineScaleSet{ Name: ptr.To("vmss"), Tags: tc.tags, - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - OrchestrationMode: compute.Uniform, + Properties: &armcompute.VirtualMachineScaleSetProperties{ + OrchestrationMode: to.Ptr(armcompute.OrchestrationModeUniform), }, } - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), cloud.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).MaxTimes(1) + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), cloud.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).MaxTimes(1) cloud.VMSet = ss - mockVMsClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachine{}, nil).AnyTimes() + mockVMsClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() clusterCIDRs := func() []*net.IPNet { _, cidrIPV4, _ := net.ParseCIDR("10.240.0.0/16") diff --git a/pkg/provider/azure.go b/pkg/provider/azure.go index 242d3e1d51..d50c14b14e 100644 --- a/pkg/provider/azure.go +++ b/pkg/provider/azure.go @@ -18,17 +18,13 @@ package provider import ( "context" - "errors" "fmt" - "net/http" "os" "strings" "sync" "time" "github.com/Azure/azure-sdk-for-go/sdk/azcore" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" "github.com/Azure/go-autorest/autorest/azure" v1 "k8s.io/api/core/v1" @@ -49,31 +45,18 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/azclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader" - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/diskclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/subnetclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmasclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmsizeclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssvmclient" + azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" + "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" + azureconfig "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" "sigs.k8s.io/cloud-provider-azure/pkg/provider/privatelinkservice" "sigs.k8s.io/cloud-provider-azure/pkg/provider/routetable" "sigs.k8s.io/cloud-provider-azure/pkg/provider/securitygroup" "sigs.k8s.io/cloud-provider-azure/pkg/provider/subnet" "sigs.k8s.io/cloud-provider-azure/pkg/provider/zone" - "sigs.k8s.io/cloud-provider-azure/pkg/version" - - azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" - "sigs.k8s.io/cloud-provider-azure/pkg/consts" - azureconfig "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" "sigs.k8s.io/cloud-provider-azure/pkg/util/taints" + "sigs.k8s.io/cloud-provider-azure/pkg/version" ) var ( @@ -106,23 +89,13 @@ type Cloud struct { azureconfig.Config Environment azure.Environment - SubnetsClient subnetclient.Interface - InterfacesClient interfaceclient.Interface - LoadBalancerClient loadbalancerclient.Interface - PublicIPAddressesClient publicipclient.Interface - VirtualMachinesClient vmclient.Interface - DisksClient diskclient.Interface - VirtualMachineScaleSetsClient vmssclient.Interface - VirtualMachineScaleSetVMsClient vmssvmclient.Interface - VirtualMachineSizesClient vmsizeclient.Interface - AvailabilitySetsClient vmasclient.Interface - ComputeClientFactory azclient.ClientFactory - NetworkClientFactory azclient.ClientFactory - AuthProvider *azclient.AuthProvider - ResourceRequestBackoff wait.Backoff - Metadata *InstanceMetadataService - VMSet VMSet - LoadBalancerBackendPool BackendPool + ComputeClientFactory azclient.ClientFactory + NetworkClientFactory azclient.ClientFactory + AuthProvider *azclient.AuthProvider + ResourceRequestBackoff wait.Backoff + Metadata *InstanceMetadataService + VMSet VMSet + LoadBalancerBackendPool BackendPool // ipv6DualStack allows overriding for unit testing. It's normally initialized from featuregates ipv6DualStackEnabled bool @@ -276,7 +249,7 @@ func NewCloudFromSecret(ctx context.Context, clientBuilder cloudprovider.Control } // InitializeCloudFromConfig initializes the Cloud from config. -func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *config.Config, fromSecret, callFromCCM bool) error { +func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *config.Config, _, callFromCCM bool) error { if config == nil { // should not reach here return fmt.Errorf("InitializeCloudFromConfig: cannot initialize from nil config") @@ -407,15 +380,16 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *config.C return err } } - servicePrincipalToken, err := azureconfig.GetServicePrincipalToken(&config.AzureClientConfig, env, env.ServiceManagementEndpoint) - if errors.Is(err, azureconfig.ErrorNoAuth) { - // Only controller-manager would lazy-initialize from secret, and credentials are required for such case. - if fromSecret { - err := fmt.Errorf("no credentials provided for Azure cloud provider") - klog.Fatal(err) + + if az.AuthProvider == nil { + var authProvider *azclient.AuthProvider + authProvider, err = azclient.NewAuthProvider(&az.ARMClientConfig, &az.AzureClientConfig.AzureAuthConfig) + if err != nil { return err } - + az.AuthProvider = authProvider + } + if az.AuthProvider.GetAzIdentity() == nil { // No credentials provided, useInstanceMetadata should be enabled for Kubelet. // TODO(feiskyer): print different error message for Kubelet and controller-manager, as they're // requiring different credential settings. @@ -424,38 +398,18 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *config.C } klog.V(2).Infof("Azure cloud provider is starting without credentials") - } else if err != nil { - return err - } - // No credentials provided, InstanceMetadataService would be used for getting Azure resources. - // Note that this only applies to Kubelet, controller-manager should configure credentials for managing Azure resources. - if servicePrincipalToken == nil { - return nil } - var authProvider *azclient.AuthProvider - authProvider, err = azclient.NewAuthProvider(&az.ARMClientConfig, &az.AzureClientConfig.AzureAuthConfig) - if err != nil { - return err - } - az.AuthProvider = authProvider - // If uses network resources in different AAD Tenant, then prepare corresponding Service Principal Token for VM/VMSS client and network resources client - multiTenantServicePrincipalToken, networkResourceServicePrincipalToken, err := az.getAuthTokenInMultiTenantEnv(servicePrincipalToken, authProvider) - if err != nil { - return err + if az.ARMClientConfig.UserAgent == "" { + k8sVersion := version.Get().GitVersion + az.ARMClientConfig.UserAgent = fmt.Sprintf("kubernetes-cloudprovider/%s", k8sVersion) } - az.configAzureClients(servicePrincipalToken, multiTenantServicePrincipalToken, networkResourceServicePrincipalToken) if az.ComputeClientFactory == nil { - if az.ARMClientConfig.UserAgent == "" { - k8sVersion := version.Get().GitVersion - az.ARMClientConfig.UserAgent = fmt.Sprintf("kubernetes-cloudprovider/%s", k8sVersion) - } - var cred azcore.TokenCredential - if authProvider.IsMultiTenantModeEnabled() { - multiTenantCred := authProvider.GetMultiTenantIdentity() - networkTenantCred := authProvider.GetNetworkAzIdentity() + if az.AuthProvider.IsMultiTenantModeEnabled() { + multiTenantCred := az.AuthProvider.GetMultiTenantIdentity() + networkTenantCred := az.AuthProvider.GetNetworkAzIdentity() az.NetworkClientFactory, err = azclient.NewClientFactory(&azclient.ClientFactoryConfig{ SubscriptionID: az.NetworkResourceSubscriptionID, }, &az.ARMClientConfig, networkTenantCred) @@ -464,7 +418,7 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *config.C } cred = multiTenantCred } else { - cred = authProvider.GetAzIdentity() + cred = az.AuthProvider.GetAzIdentity() } az.ComputeClientFactory, err = azclient.NewClientFactory(&azclient.ClientFactoryConfig{ SubscriptionID: az.SubscriptionID, @@ -472,51 +426,50 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *config.C if err != nil { return err } + } - networkClientFactory := az.NetworkClientFactory - if networkClientFactory == nil { - networkClientFactory = az.ComputeClientFactory - } + networkClientFactory := az.NetworkClientFactory + if networkClientFactory == nil { + networkClientFactory = az.ComputeClientFactory + } + if az.nsgRepo == nil { az.nsgRepo, err = securitygroup.NewSecurityGroupRepo(az.SecurityGroupResourceGroup, az.SecurityGroupName, az.NsgCacheTTLInSeconds, az.DisableAPICallCache, networkClientFactory.GetSecurityGroupClient()) if err != nil { return err } + } + if az.zoneRepo == nil { az.zoneRepo, err = zone.NewRepo(az.ComputeClientFactory.GetProviderClient()) if err != nil { return err } - + } + if az.plsRepo == nil { az.plsRepo, err = privatelinkservice.NewRepo(az.ComputeClientFactory.GetPrivateLinkServiceClient(), time.Duration(az.PlsCacheTTLInSeconds)*time.Second, az.DisableAPICallCache) if err != nil { return err } + } + if az.subnetRepo == nil { az.subnetRepo, err = subnet.NewRepo(networkClientFactory.GetSubnetClient()) if err != nil { return err } + } + if az.routeTableRepo == nil { az.routeTableRepo, err = routetable.NewRepo(networkClientFactory.GetRouteTableClient(), az.RouteTableResourceGroup, time.Duration(az.RouteTableCacheTTLInSeconds)*time.Second, az.DisableAPICallCache) if err != nil { return err } } + err = az.initCaches() if err != nil { return err } - - // Common controller contains the function - // needed by both blob disk and managed disk controllers - qps := float32(azureconfig.DefaultAtachDetachDiskQPS) - bucket := azureconfig.DefaultAtachDetachDiskBucket - if az.Config.AttachDetachDiskRateLimit != nil { - qps = az.Config.AttachDetachDiskRateLimit.CloudProviderRateLimitQPSWrite - bucket = az.Config.AttachDetachDiskRateLimit.CloudProviderRateLimitBucketWrite - } - klog.V(2).Infof("attach/detach disk operation rate limit QPS: %f, Bucket: %d", qps, bucket) - // updating routes and syncing zones only in CCM if callFromCCM { // start delayed route updater. @@ -603,11 +556,11 @@ func (az *Cloud) initCaches() (err error) { } func (az *Cloud) setLBDefaults(config *azureconfig.Config) error { - if config.LoadBalancerSku == "" { - config.LoadBalancerSku = consts.LoadBalancerSkuStandard + if config.LoadBalancerSKU == "" { + config.LoadBalancerSKU = consts.LoadBalancerSKUStandard } - if strings.EqualFold(config.LoadBalancerSku, consts.LoadBalancerSkuStandard) { + if strings.EqualFold(config.LoadBalancerSKU, consts.LoadBalancerSKUStandard) { // Do not add master nodes to standard LB by default. if config.ExcludeMasterFromStandardLB == nil { config.ExcludeMasterFromStandardLB = &defaultExcludeMasterFromStandardLB @@ -619,29 +572,12 @@ func (az *Cloud) setLBDefaults(config *azureconfig.Config) error { } } else { if config.DisableOutboundSNAT != nil && *config.DisableOutboundSNAT { - return fmt.Errorf("disableOutboundSNAT should only set when loadBalancerSku is standard") + return fmt.Errorf("disableOutboundSNAT should only set when loadBalancerSKU is standard") } } return nil } -func (az *Cloud) getAuthTokenInMultiTenantEnv(_ *adal.ServicePrincipalToken, authProvider *azclient.AuthProvider) (adal.MultitenantOAuthTokenProvider, adal.OAuthTokenProvider, error) { - var err error - var multiTenantOAuthToken adal.MultitenantOAuthTokenProvider - var networkResourceServicePrincipalToken adal.OAuthTokenProvider - if az.Config.UsesNetworkResourceInDifferentTenant() { - multiTenantOAuthToken, err = azureconfig.GetMultiTenantServicePrincipalToken(&az.Config.AzureClientConfig, &az.Environment, authProvider) - if err != nil { - return nil, nil, err - } - networkResourceServicePrincipalToken, err = azureconfig.GetNetworkResourceServicePrincipalToken(&az.Config.AzureClientConfig, &az.Environment, authProvider) - if err != nil { - return nil, nil, err - } - } - return multiTenantOAuthToken, networkResourceServicePrincipalToken, nil -} - func (az *Cloud) setCloudProviderBackoffDefaults(config *azureconfig.Config) wait.Backoff { // Conditionally configure resource request backoff resourceRequestBackoff := wait.Backoff{ @@ -682,99 +618,6 @@ func (az *Cloud) setCloudProviderBackoffDefaults(config *azureconfig.Config) wai return resourceRequestBackoff } -func (az *Cloud) configAzureClients( - servicePrincipalToken *adal.ServicePrincipalToken, - multiTenantOAuthTokenProvider adal.MultitenantOAuthTokenProvider, - networkResourceServicePrincipalToken adal.OAuthTokenProvider, -) { - azClientConfig := az.getAzureClientConfig(servicePrincipalToken) - - // Prepare AzureClientConfig for all azure clients - interfaceClientConfig := azClientConfig.WithRateLimiter(az.Config.InterfaceRateLimit) - vmSizeClientConfig := azClientConfig.WithRateLimiter(az.Config.VirtualMachineSizeRateLimit) - diskClientConfig := azClientConfig.WithRateLimiter(az.Config.DiskRateLimit) - vmClientConfig := azClientConfig.WithRateLimiter(az.Config.VirtualMachineRateLimit) - vmssClientConfig := azClientConfig.WithRateLimiter(az.Config.VirtualMachineScaleSetRateLimit) - // Error "not an active Virtual Machine Scale Set VM" is not retriable for VMSS VM. - // But http.StatusNotFound is retriable because of ARM replication latency. - vmssVMClientConfig := azClientConfig.WithRateLimiter(az.Config.VirtualMachineScaleSetRateLimit) - vmssVMClientConfig.Backoff = vmssVMClientConfig.Backoff.WithNonRetriableErrors([]string{consts.VmssVMNotActiveErrorMessage}).WithRetriableHTTPStatusCodes([]int{http.StatusNotFound}) - subnetClientConfig := azClientConfig.WithRateLimiter(az.Config.SubnetsRateLimit) - routeTableClientConfig := azClientConfig.WithRateLimiter(az.Config.RouteTableRateLimit) - loadBalancerClientConfig := azClientConfig.WithRateLimiter(az.Config.LoadBalancerRateLimit) - publicIPClientConfig := azClientConfig.WithRateLimiter(az.Config.PublicIPAddressRateLimit) - vmasClientConfig := azClientConfig.WithRateLimiter(az.Config.AvailabilitySetRateLimit) - - // If uses network resources in different AAD Tenant, update Authorizer for VM/VMSS/VMAS client config - if multiTenantOAuthTokenProvider != nil { - multiTenantServicePrincipalTokenAuthorizer := autorest.NewMultiTenantServicePrincipalTokenAuthorizer(multiTenantOAuthTokenProvider) - - vmClientConfig.Authorizer = multiTenantServicePrincipalTokenAuthorizer - vmssClientConfig.Authorizer = multiTenantServicePrincipalTokenAuthorizer - vmssVMClientConfig.Authorizer = multiTenantServicePrincipalTokenAuthorizer - vmasClientConfig.Authorizer = multiTenantServicePrincipalTokenAuthorizer - } - - // If uses network resources in different AAD Tenant, update SubscriptionID and Authorizer for network resources client config - if networkResourceServicePrincipalToken != nil { - networkResourceServicePrincipalTokenAuthorizer := autorest.NewBearerAuthorizer(networkResourceServicePrincipalToken) - subnetClientConfig.Authorizer = networkResourceServicePrincipalTokenAuthorizer - routeTableClientConfig.Authorizer = networkResourceServicePrincipalTokenAuthorizer - loadBalancerClientConfig.Authorizer = networkResourceServicePrincipalTokenAuthorizer - publicIPClientConfig.Authorizer = networkResourceServicePrincipalTokenAuthorizer - } - - if az.UsesNetworkResourceInDifferentSubscription() { - subnetClientConfig.SubscriptionID = az.Config.NetworkResourceSubscriptionID - routeTableClientConfig.SubscriptionID = az.Config.NetworkResourceSubscriptionID - loadBalancerClientConfig.SubscriptionID = az.Config.NetworkResourceSubscriptionID - publicIPClientConfig.SubscriptionID = az.Config.NetworkResourceSubscriptionID - } - - // Initialize all azure clients based on client config - az.InterfacesClient = interfaceclient.New(interfaceClientConfig) - az.VirtualMachineSizesClient = vmsizeclient.New(vmSizeClientConfig) - az.DisksClient = diskclient.New(diskClientConfig) - az.VirtualMachinesClient = vmclient.New(vmClientConfig) - az.VirtualMachineScaleSetsClient = vmssclient.New(vmssClientConfig) - az.VirtualMachineScaleSetVMsClient = vmssvmclient.New(vmssVMClientConfig) - az.SubnetsClient = subnetclient.New(subnetClientConfig) - az.LoadBalancerClient = loadbalancerclient.New(loadBalancerClientConfig) - az.PublicIPAddressesClient = publicipclient.New(publicIPClientConfig) - az.AvailabilitySetsClient = vmasclient.New(vmasClientConfig) -} - -func (az *Cloud) getAzureClientConfig(servicePrincipalToken *adal.ServicePrincipalToken) *azclients.ClientConfig { - azClientConfig := &azclients.ClientConfig{ - CloudName: az.Config.Cloud, - Location: az.Config.Location, - SubscriptionID: az.Config.SubscriptionID, - ResourceManagerEndpoint: az.Environment.ResourceManagerEndpoint, - Authorizer: autorest.NewBearerAuthorizer(servicePrincipalToken), - Backoff: &retry.Backoff{Steps: 1}, - DisableAzureStackCloud: az.Config.DisableAzureStackCloud, - UserAgent: az.Config.UserAgent, - } - - if az.Config.CloudProviderBackoff { - azClientConfig.Backoff = &retry.Backoff{ - Steps: az.Config.CloudProviderBackoffRetries, - Factor: az.Config.CloudProviderBackoffExponent, - Duration: time.Duration(az.Config.CloudProviderBackoffDuration) * time.Second, - Jitter: az.Config.CloudProviderBackoffJitter, - } - } - - if az.Config.HasExtendedLocation() { - azClientConfig.ExtendedLocation = &azclients.ExtendedLocation{ - Name: az.Config.ExtendedLocationName, - Type: az.Config.ExtendedLocationType, - } - } - - return azClientConfig -} - // Initialize passes a Kubernetes clientBuilder interface to the cloud provider func (az *Cloud) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, _ <-chan struct{}) { az.KubeClient = clientBuilder.ClientOrDie("azure-cloud-provider") diff --git a/pkg/provider/azure_controller_common.go b/pkg/provider/azure_controller_common.go index e2f0128b10..c2c7b9e5ae 100644 --- a/pkg/provider/azure_controller_common.go +++ b/pkg/provider/azure_controller_common.go @@ -18,15 +18,17 @@ package provider import ( "context" + "errors" "fmt" "net/http" "path" "strings" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "k8s.io/klog/v2" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/diskclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient" ) const ( @@ -52,20 +54,20 @@ type ExtendedLocation struct { Type string `json:"type,omitempty"` } -func FilterNonExistingDisks(ctx context.Context, diskClient diskclient.Interface, unfilteredDisks []compute.DataDisk) []compute.DataDisk { - filteredDisks := []compute.DataDisk{} +func FilterNonExistingDisks(ctx context.Context, clientFactory azclient.ClientFactory, unfilteredDisks []*armcompute.DataDisk) []*armcompute.DataDisk { + filteredDisks := []*armcompute.DataDisk{} for _, disk := range unfilteredDisks { filter := false if disk.ManagedDisk != nil && disk.ManagedDisk.ID != nil { - diskURI := *disk.ManagedDisk.ID - exist, err := checkDiskExists(ctx, diskClient, diskURI) + diSKURI := *disk.ManagedDisk.ID + exist, err := checkDiskExists(ctx, clientFactory, diSKURI) if err != nil { - klog.Errorf("checkDiskExists(%s) failed with error: %v", diskURI, err) + klog.Errorf("checkDiskExists(%s) failed with error: %v", diSKURI, err) } else { // only filter disk when checkDiskExists returns filter = !exist if filter { - klog.Errorf("disk(%s) does not exist, removed from data disk list", diskURI) + klog.Errorf("disk(%s) does not exist, removed from data disk list", diSKURI) } } } @@ -77,18 +79,26 @@ func FilterNonExistingDisks(ctx context.Context, diskClient diskclient.Interface return filteredDisks } -func checkDiskExists(ctx context.Context, diskClient diskclient.Interface, diskURI string) (bool, error) { - diskName := path.Base(diskURI) - resourceGroup, subsID, err := getInfoFromDiskURI(diskURI) +func checkDiskExists(ctx context.Context, clientFactory azclient.ClientFactory, diSKURI string) (bool, error) { + diskName := path.Base(diSKURI) + resourceGroup, subsID, err := getInfoFromDiSKURI(diSKURI) + if err != nil { + return false, err + } + diskClient, err := clientFactory.GetDiskClientForSub(subsID) if err != nil { return false, err } - if _, rerr := diskClient.Get(ctx, subsID, resourceGroup, diskName); rerr != nil { - if rerr.HTTPStatusCode == http.StatusNotFound { - return false, nil + _, err = diskClient.Get(ctx, resourceGroup, diskName) + if err != nil { + rerr := &azcore.ResponseError{} + if errors.As(err, &rerr) { + if rerr.StatusCode == http.StatusNotFound { + return false, nil + } } - return false, rerr.Error() + return false, err } return true, nil @@ -97,10 +107,10 @@ func checkDiskExists(ctx context.Context, diskClient diskclient.Interface, diskU // get resource group name, subs id from a managed disk URI, e.g. return {group-name}, {sub-id} according to // /subscriptions/{sub-id}/resourcegroups/{group-name}/providers/microsoft.compute/disks/{disk-id} // according to https://docs.microsoft.com/en-us/rest/api/compute/disks/get -func getInfoFromDiskURI(diskURI string) (string, string, error) { - fields := strings.Split(diskURI, "/") +func getInfoFromDiSKURI(diSKURI string) (string, string, error) { + fields := strings.Split(diSKURI, "/") if len(fields) != 9 || strings.ToLower(fields[3]) != "resourcegroups" { - return "", "", fmt.Errorf("invalid disk URI: %s", diskURI) + return "", "", fmt.Errorf("invalid disk URI: %s", diSKURI) } return fields[4], fields[2], nil } diff --git a/pkg/provider/azure_controller_standard.go b/pkg/provider/azure_controller_standard.go index 39f4d8258a..d657a6fd71 100644 --- a/pkg/provider/azure_controller_standard.go +++ b/pkg/provider/azure_controller_standard.go @@ -19,12 +19,11 @@ package provider import ( "context" "fmt" - "net/http" "strings" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/azure" "k8s.io/apimachinery/pkg/types" "k8s.io/klog/v2" @@ -32,7 +31,7 @@ import ( azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" + "sigs.k8s.io/cloud-provider-azure/pkg/util/errutils" ) // AttachDisk attaches a disk to vm @@ -48,76 +47,81 @@ func (as *availabilitySet) AttachDisk(ctx context.Context, nodeName types.NodeNa return err } - disks := make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks)) - copy(disks, *vm.StorageProfile.DataDisks) + disks := make([]*armcompute.DataDisk, len(vm.Properties.StorageProfile.DataDisks)) + copy(disks, vm.Properties.StorageProfile.DataDisks) for k, v := range diskMap { - diskURI := k + diSKURI := k opt := v attached := false - for _, disk := range *vm.StorageProfile.DataDisks { - if disk.ManagedDisk != nil && strings.EqualFold(*disk.ManagedDisk.ID, diskURI) && disk.Lun != nil { + for _, disk := range vm.Properties.StorageProfile.DataDisks { + if disk.ManagedDisk != nil && strings.EqualFold(*disk.ManagedDisk.ID, diSKURI) && disk.Lun != nil { if *disk.Lun == opt.Lun { attached = true break } - return fmt.Errorf("disk(%s) already attached to node(%s) on LUN(%d), but target LUN is %d", diskURI, nodeName, *disk.Lun, opt.Lun) + return fmt.Errorf("disk(%s) already attached to node(%s) on LUN(%d), but target LUN is %d", diSKURI, nodeName, *disk.Lun, opt.Lun) } } if attached { - klog.V(2).Infof("azureDisk - disk(%s) already attached to node(%s) on LUN(%d)", diskURI, nodeName, opt.Lun) + klog.V(2).Infof("azureDisk - disk(%s) already attached to node(%s) on LUN(%d)", diSKURI, nodeName, opt.Lun) continue } - managedDisk := &compute.ManagedDiskParameters{ID: &diskURI} + managedDisk := &armcompute.ManagedDiskParameters{ID: &diSKURI} if opt.DiskEncryptionSetID == "" { - if vm.StorageProfile.OsDisk != nil && - vm.StorageProfile.OsDisk.ManagedDisk != nil && - vm.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet != nil && - vm.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.ID != nil { + if vm.Properties.StorageProfile.OSDisk != nil && + vm.Properties.StorageProfile.OSDisk.ManagedDisk != nil && + vm.Properties.StorageProfile.OSDisk.ManagedDisk.DiskEncryptionSet != nil && + vm.Properties.StorageProfile.OSDisk.ManagedDisk.DiskEncryptionSet.ID != nil { // set diskEncryptionSet as value of os disk by default - opt.DiskEncryptionSetID = *vm.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.ID + opt.DiskEncryptionSetID = *vm.Properties.StorageProfile.OSDisk.ManagedDisk.DiskEncryptionSet.ID } } if opt.DiskEncryptionSetID != "" { - managedDisk.DiskEncryptionSet = &compute.DiskEncryptionSetParameters{ID: &opt.DiskEncryptionSetID} + managedDisk.DiskEncryptionSet = &armcompute.DiskEncryptionSetParameters{ID: &opt.DiskEncryptionSetID} } disks = append(disks, - compute.DataDisk{ + &armcompute.DataDisk{ Name: &opt.DiskName, Lun: &opt.Lun, - Caching: opt.CachingMode, - CreateOption: "attach", + Caching: to.Ptr(opt.CachingMode), + CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesAttach), ManagedDisk: managedDisk, WriteAcceleratorEnabled: ptr.To(opt.WriteAcceleratorEnabled), }) } - newVM := compute.VirtualMachineUpdate{ - VirtualMachineProperties: &compute.VirtualMachineProperties{ - StorageProfile: &compute.StorageProfile{ - DataDisks: &disks, + newVM := armcompute.VirtualMachine{ + Properties: &armcompute.VirtualMachineProperties{ + StorageProfile: &armcompute.StorageProfile{ + DataDisks: disks, }, }, } klog.V(2).Infof("azureDisk - update(%s): vm(%s) - attach disk list(%v)", nodeResourceGroup, vmName, diskMap) - future, rerr := as.VirtualMachinesClient.UpdateAsync(ctx, nodeResourceGroup, vmName, newVM, "attach_disk") + result, rerr := as.ComputeClientFactory.GetVirtualMachineClient().CreateOrUpdate(ctx, nodeResourceGroup, vmName, newVM) if rerr != nil { klog.Errorf("azureDisk - attach disk list(%v) on rg(%s) vm(%s) failed, err: %+v", diskMap, nodeResourceGroup, vmName, rerr) - if rerr.HTTPStatusCode == http.StatusNotFound { + if exists, err := errutils.CheckResourceExistsFromAzcoreError(rerr); !exists && err == nil { klog.Errorf("azureDisk - begin to filterNonExistingDisks(%v) on rg(%s) vm(%s)", diskMap, nodeResourceGroup, vmName) - disks := FilterNonExistingDisks(ctx, as.DisksClient, *newVM.VirtualMachineProperties.StorageProfile.DataDisks) - newVM.VirtualMachineProperties.StorageProfile.DataDisks = &disks - future, rerr = as.VirtualMachinesClient.UpdateAsync(ctx, nodeResourceGroup, vmName, newVM, "attach_disk") + disks := FilterNonExistingDisks(ctx, as.ComputeClientFactory, newVM.Properties.StorageProfile.DataDisks) + newVM.Properties.StorageProfile.DataDisks = disks + result, rerr = as.ComputeClientFactory.GetVirtualMachineClient().CreateOrUpdate(ctx, nodeResourceGroup, vmName, newVM) } } klog.V(2).Infof("azureDisk - update(%s): vm(%s) - attach disk list(%v) returned with %v", nodeResourceGroup, vmName, diskMap, rerr) if rerr != nil { - return rerr.Error() + return rerr } - return as.WaitForUpdateResult(ctx, future, nodeName, "attach_disk") + + // clean node cache first and then update cache + _ = as.DeleteCacheForNode(ctx, vmName) + // if we have an updated result, we update the vmss vm cache + as.updateCache(vmName, result) + return nil } func (as *availabilitySet) DeleteCacheForNode(_ context.Context, nodeName string) error { @@ -130,28 +134,6 @@ func (as *availabilitySet) DeleteCacheForNode(_ context.Context, nodeName string return err } -// WaitForUpdateResult waits for the response of the update request -func (as *availabilitySet) WaitForUpdateResult(ctx context.Context, future *azure.Future, nodeName types.NodeName, source string) error { - vmName := mapNodeNameToVMName(nodeName) - nodeResourceGroup, err := as.GetNodeResourceGroup(vmName) - if err != nil { - return err - } - - result, rerr := as.VirtualMachinesClient.WaitForUpdateResult(ctx, future, nodeResourceGroup, source) - if rerr != nil { - return rerr.Error() - } - - // clean node cache first and then update cache - _ = as.DeleteCacheForNode(ctx, vmName) - if result != nil && result.VirtualMachineProperties != nil { - // if we have an updated result, we update the vmss vm cache - as.updateCache(vmName, result) - } - return nil -} - // DetachDisk detaches a disk from VM func (as *availabilitySet) DetachDisk(ctx context.Context, nodeName types.NodeName, diskMap map[string]string, forceDetach bool) error { vm, err := as.getVirtualMachine(ctx, nodeName, azcache.CacheReadTypeDefault) @@ -167,20 +149,20 @@ func (as *availabilitySet) DetachDisk(ctx context.Context, nodeName types.NodeNa return err } - disks := make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks)) - copy(disks, *vm.StorageProfile.DataDisks) + disks := make([]*armcompute.DataDisk, len(vm.Properties.StorageProfile.DataDisks)) + copy(disks, vm.Properties.StorageProfile.DataDisks) bFoundDisk := false for i, disk := range disks { - for diskURI, diskName := range diskMap { + for diSKURI, diskName := range diskMap { if disk.Lun != nil && (disk.Name != nil && diskName != "" && strings.EqualFold(*disk.Name, diskName)) || - (disk.Vhd != nil && disk.Vhd.URI != nil && diskURI != "" && strings.EqualFold(*disk.Vhd.URI, diskURI)) || - (disk.ManagedDisk != nil && diskURI != "" && strings.EqualFold(*disk.ManagedDisk.ID, diskURI)) { + (disk.Vhd != nil && disk.Vhd.URI != nil && diSKURI != "" && strings.EqualFold(*disk.Vhd.URI, diSKURI)) || + (disk.ManagedDisk != nil && diSKURI != "" && strings.EqualFold(*disk.ManagedDisk.ID, diSKURI)) { // found the disk - klog.V(2).Infof("azureDisk - detach disk: name %s uri %s", diskName, diskURI) + klog.V(2).Infof("azureDisk - detach disk: name %s uri %s", diskName, diSKURI) disks[i].ToBeDetached = ptr.To(true) if forceDetach { - disks[i].DetachOption = compute.ForceDetach + disks[i].DetachOption = to.Ptr(armcompute.DiskDetachOptionTypesForceDetach) } bFoundDisk = true } @@ -193,7 +175,7 @@ func (as *availabilitySet) DetachDisk(ctx context.Context, nodeName types.NodeNa } else { if strings.EqualFold(as.Environment.Name, consts.AzureStackCloudName) && !as.Config.DisableAzureStackCloud { // Azure stack does not support ToBeDetached flag, use original way to detach disk - newDisks := []compute.DataDisk{} + newDisks := []*armcompute.DataDisk{} for _, disk := range disks { if !ptr.Deref(disk.ToBeDetached, false) { newDisks = append(newDisks, disk) @@ -203,71 +185,72 @@ func (as *availabilitySet) DetachDisk(ctx context.Context, nodeName types.NodeNa } } - newVM := compute.VirtualMachineUpdate{ - VirtualMachineProperties: &compute.VirtualMachineProperties{ - StorageProfile: &compute.StorageProfile{ - DataDisks: &disks, + newVM := armcompute.VirtualMachine{ + Properties: &armcompute.VirtualMachineProperties{ + StorageProfile: &armcompute.StorageProfile{ + DataDisks: disks, }, }, } klog.V(2).Infof("azureDisk - update(%s): vm(%s) node(%s)- detach disk list(%s)", nodeResourceGroup, vmName, nodeName, diskMap) - var result *compute.VirtualMachine - var rerr *retry.Error + var result *armcompute.VirtualMachine defer func() { // invalidate the cache right after updating _ = as.DeleteCacheForNode(ctx, vmName) // update the cache with the updated result only if its not nil - // and contains the VirtualMachineProperties - if rerr == nil && result != nil && result.VirtualMachineProperties != nil { + // and contains the.Properties + if err == nil && result != nil && result.Properties != nil { as.updateCache(vmName, result) } }() - result, rerr = as.VirtualMachinesClient.Update(ctx, nodeResourceGroup, vmName, newVM, "detach_disk") - if rerr != nil { - klog.Errorf("azureDisk - detach disk list(%s) on rg(%s) vm(%s) failed, err: %v", diskMap, nodeResourceGroup, vmName, rerr) - if rerr.HTTPStatusCode == http.StatusNotFound { + result, err = as.ComputeClientFactory.GetVirtualMachineClient().CreateOrUpdate(ctx, nodeResourceGroup, vmName, newVM) + if err != nil { + klog.Errorf("azureDisk - detach disk list(%s) on rg(%s) vm(%s) failed, err: %v", diskMap, nodeResourceGroup, vmName, err) + var exists bool + if exists, err = errutils.CheckResourceExistsFromAzcoreError(err); !exists && err == nil { klog.Errorf("azureDisk - begin to filterNonExistingDisks(%v) on rg(%s) vm(%s)", diskMap, nodeResourceGroup, vmName) - disks := FilterNonExistingDisks(ctx, as.DisksClient, *vm.StorageProfile.DataDisks) - newVM.VirtualMachineProperties.StorageProfile.DataDisks = &disks - result, rerr = as.VirtualMachinesClient.Update(ctx, nodeResourceGroup, vmName, newVM, "detach_disk") + disks := FilterNonExistingDisks(ctx, as.ComputeClientFactory, vm.Properties.StorageProfile.DataDisks) + newVM.Properties.StorageProfile.DataDisks = disks + result, err = as.ComputeClientFactory.GetVirtualMachineClient().CreateOrUpdate(ctx, nodeResourceGroup, vmName, newVM) } } - klog.V(2).Infof("azureDisk - update(%s): vm(%s) - detach disk list(%s) returned with %v", nodeResourceGroup, vmName, diskMap, rerr) - if rerr != nil { - return rerr.Error() + klog.V(2).Infof("azureDisk - update(%s): vm(%s) - detach disk list(%s) returned with %v", nodeResourceGroup, vmName, diskMap, err) + if err != nil { + return err } return nil } // UpdateVM updates a vm func (as *availabilitySet) UpdateVM(ctx context.Context, nodeName types.NodeName) error { - future, err := as.UpdateVMAsync(ctx, nodeName) - if err != nil { - return err - } - return as.WaitForUpdateResult(ctx, future, nodeName, "update_vm") -} - -// UpdateVMAsync updates a vm asynchronously -func (as *availabilitySet) UpdateVMAsync(ctx context.Context, nodeName types.NodeName) (*azure.Future, error) { vmName := mapNodeNameToVMName(nodeName) nodeResourceGroup, err := as.GetNodeResourceGroup(vmName) if err != nil { - return nil, err + return err } - future, rerr := as.VirtualMachinesClient.UpdateAsync(ctx, nodeResourceGroup, vmName, compute.VirtualMachineUpdate{}, "update_vm") + result, rerr := as.ComputeClientFactory.GetVirtualMachineClient().CreateOrUpdate(ctx, nodeResourceGroup, vmName, armcompute.VirtualMachine{}) + // clean node cache first and then update cache + _ = as.DeleteCacheForNode(ctx, vmName) if rerr != nil { - return future, rerr.Error() + if exists, err := errutils.CheckResourceExistsFromAzcoreError(rerr); !exists && err == nil { + // if the VM does not exist, we should not update the cache + return nil + } + return rerr } - return future, nil + // clean node cache first and then update cache + _ = as.DeleteCacheForNode(ctx, vmName) + // if we have an updated result, we update the vmss vm cache + as.updateCache(vmName, result) + return nil } -func (as *availabilitySet) updateCache(nodeName string, vm *compute.VirtualMachine) { +func (as *availabilitySet) updateCache(nodeName string, vm *armcompute.VirtualMachine) { as.vmCache.Update(nodeName, vm) klog.V(2).Infof("updateCache(%s) successfully", nodeName) } @@ -279,13 +262,8 @@ func (as *availabilitySet) GetDataDisks(ctx context.Context, nodeName types.Node return nil, nil, err } - if vm.StorageProfile.DataDisks == nil { + if vm.Properties.StorageProfile.DataDisks == nil { return nil, nil, nil } - - result, err := ToArmcomputeDisk(*vm.StorageProfile.DataDisks) - if err != nil { - return nil, nil, err - } - return result, vm.ProvisioningState, nil + return vm.Properties.StorageProfile.DataDisks, vm.Properties.ProvisioningState, nil } diff --git a/pkg/provider/azure_controller_standard_test.go b/pkg/provider/azure_controller_standard_test.go index 65ffe23edb..723a156113 100644 --- a/pkg/provider/azure_controller_standard_test.go +++ b/pkg/provider/azure_controller_standard_test.go @@ -23,21 +23,17 @@ import ( "testing" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/azure" - autorestmocks "github.com/Azure/go-autorest/autorest/mocks" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - "k8s.io/apimachinery/pkg/types" cloudprovider "k8s.io/cloud-provider" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) var ( @@ -90,41 +86,40 @@ func TestStandardAttachDisk(t *testing.T) { testCloud := GetTestCloud(ctrl) vmSet := testCloud.VMSet expectedVMs := setTestVirtualMachines(testCloud, map[string]string{"vm1": "PowerState/Running"}, false) - mockVMsClient := testCloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMsClient := testCloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) for _, vm := range expectedVMs { - vm.StorageProfile = &compute.StorageProfile{ - OsDisk: &compute.OSDisk{ - Name: ptr.To("osdisk1"), - ManagedDisk: &compute.ManagedDiskParameters{ + vm.Properties.StorageProfile = &armcompute.StorageProfile{ + OSDisk: &armcompute.OSDisk{ + Name: ptr.To("OSDisk1"), + ManagedDisk: &armcompute.ManagedDiskParameters{ ID: ptr.To("ManagedID"), - DiskEncryptionSet: &compute.DiskEncryptionSetParameters{ + DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{ ID: ptr.To("DiskEncryptionSetID"), }, }, }, - DataDisks: &[]compute.DataDisk{}, + DataDisks: []*armcompute.DataDisk{}, } if test.inconsistentLUN { diskName := "disk-name2" - diskURI := "uri" - vm.StorageProfile.DataDisks = &[]compute.DataDisk{ - {Lun: ptr.To(int32(0)), Name: &diskName, ManagedDisk: &compute.ManagedDiskParameters{ID: &diskURI}}, + diSKURI := "uri" + vm.Properties.StorageProfile.DataDisks = []*armcompute.DataDisk{ + {Lun: ptr.To(int32(0)), Name: &diskName, ManagedDisk: &armcompute.ManagedDiskParameters{ID: &diSKURI}}, } } mockVMsClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, *vm.Name, gomock.Any()).Return(vm, nil).AnyTimes() } - mockVMsClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, "vm2", gomock.Any()).Return(compute.VirtualMachine{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockVMsClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, "vm2", gomock.Any()).Return(&armcompute.VirtualMachine{}, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() if test.isAttachFail { - mockVMsClient.EXPECT().UpdateAsync(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockVMsClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() } else { - mockVMsClient.EXPECT().UpdateAsync(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - mockVMsClient.EXPECT().WaitForUpdateResult(gomock.Any(), gomock.Any(), testCloud.ResourceGroup, gomock.Any()).Return(nil, nil).AnyTimes() + mockVMsClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() } options := AttachDiskOptions{ Lun: 0, DiskName: "disk-name2", - CachingMode: compute.CachingTypesReadOnly, + CachingMode: armcompute.CachingTypesReadOnly, DiskEncryptionSetID: "", WriteAcceleratorEnabled: false, } @@ -196,22 +191,22 @@ func TestStandardDetachDisk(t *testing.T) { testCloud := GetTestCloud(ctrl) vmSet := testCloud.VMSet expectedVMs := setTestVirtualMachines(testCloud, map[string]string{"vm1": "PowerState/Running"}, false) - mockVMsClient := testCloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMsClient := testCloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) for _, vm := range expectedVMs { mockVMsClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, *vm.Name, gomock.Any()).Return(vm, nil).AnyTimes() } - mockVMsClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, "vm2", gomock.Any()).Return(compute.VirtualMachine{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockVMsClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, "vm2", gomock.Any()).Return(&armcompute.VirtualMachine{}, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() if test.isDetachFail { - mockVMsClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockVMsClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() } else { - mockVMsClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, "vm1", gomock.Any(), "detach_disk").Return(nil, nil).AnyTimes() + mockVMsClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, "vm1", gomock.Any()).Return(nil, nil).AnyTimes() } diskMap := map[string]string{} for _, diskName := range test.disks { - diskURI := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/disks/%s", + diSKURI := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/disks/%s", testCloud.SubscriptionID, testCloud.ResourceGroup, diskName) - diskMap[diskURI] = diskName + diskMap[diSKURI] = diskName } err := vmSet.DetachDisk(ctx, test.nodeName, diskMap, test.forceDetach) assert.Equal(t, test.expectedError, err != nil, "TestCase[%d]: %s", i, test.desc) @@ -265,27 +260,19 @@ func TestStandardUpdateVM(t *testing.T) { testCloud := GetTestCloud(ctrl) vmSet := testCloud.VMSet expectedVMs := setTestVirtualMachines(testCloud, map[string]string{"vm1": "PowerState/Running"}, false) - mockVMsClient := testCloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMsClient := testCloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) for _, vm := range expectedVMs { mockVMsClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, *vm.Name, gomock.Any()).Return(vm, nil).AnyTimes() } - mockVMsClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, "vm2", gomock.Any()).Return(compute.VirtualMachine{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() - - r := autorestmocks.NewResponseWithStatus("200", 200) - r.Request.Method = http.MethodPut - - future, err := azure.NewFutureFromResponse(r) - - mockVMsClient.EXPECT().UpdateAsync(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(&future, err).AnyTimes() + mockVMsClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, "vm2", gomock.Any()).Return(&armcompute.VirtualMachine{}, runtime.NewResponseErrorWithErrorCode(&http.Response{StatusCode: http.StatusNotFound}, cloudprovider.InstanceNotFound.Error())).AnyTimes() if test.isDetachFail { - mockVMsClient.EXPECT().WaitForUpdateResult(gomock.Any(), &future, testCloud.ResourceGroup, gomock.Any()).Return(nil, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockVMsClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, &azcore.ResponseError{StatusCode: http.StatusBadRequest, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() + } else { - mockVMsClient.EXPECT().WaitForUpdateResult(gomock.Any(), &future, testCloud.ResourceGroup, gomock.Any()).Return(nil, nil).AnyTimes() - mockVMsClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockVMsClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() } - - err = vmSet.UpdateVM(ctx, test.nodeName) + err := vmSet.UpdateVM(ctx, test.nodeName) assert.Equal(t, test.expectedError, err != nil, "TestCase[%d]: %s", i, test.desc) if !test.expectedError && test.diskName != "" { dataDisks, _, err := vmSet.GetDataDisks(context.TODO(), test.nodeName, azcache.CacheReadTypeDefault) @@ -366,15 +353,15 @@ func TestGetDataDisks(t *testing.T) { testCloud := GetTestCloud(ctrl) vmSet := testCloud.VMSet expectedVMs := setTestVirtualMachines(testCloud, map[string]string{"vm1": "PowerState/Running"}, false) - mockVMsClient := testCloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMsClient := testCloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) for _, vm := range expectedVMs { if test.isDataDiskNull { - vm.StorageProfile = &compute.StorageProfile{} + vm.Properties.StorageProfile = &armcompute.StorageProfile{} } mockVMsClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, *vm.Name, gomock.Any()).Return(vm, nil).AnyTimes() } - mockVMsClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, gomock.Not("vm1"), gomock.Any()).Return(compute.VirtualMachine{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() - mockVMsClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + mockVMsClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, gomock.Not("vm1"), gomock.Any()).Return(&armcompute.VirtualMachine{}, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() + mockVMsClient.EXPECT().BeginUpdate(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() dataDisks, _, err := vmSet.GetDataDisks(context.TODO(), test.nodeName, test.crt) assert.Equal(t, test.expectedDataDisks, dataDisks, "TestCase[%d]: %s", i, test.desc) diff --git a/pkg/provider/azure_controller_vmss.go b/pkg/provider/azure_controller_vmss.go index 48e4185048..0519f2533d 100644 --- a/pkg/provider/azure_controller_vmss.go +++ b/pkg/provider/azure_controller_vmss.go @@ -19,12 +19,10 @@ package provider import ( "context" "fmt" - "net/http" "strings" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/azure" "k8s.io/apimachinery/pkg/types" "k8s.io/klog/v2" @@ -32,7 +30,7 @@ import ( azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" + "sigs.k8s.io/cloud-provider-azure/pkg/util/errutils" ) // AttachDisk attaches a disk to vm @@ -48,100 +46,88 @@ func (ss *ScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, dis return err } - var disks []compute.DataDisk + var disks []*armcompute.DataDisk - storageProfile := vm.AsVirtualMachineScaleSetVM().StorageProfile + storageProfile := vm.AsVirtualMachineScaleSetVM().Properties.StorageProfile if storageProfile != nil && storageProfile.DataDisks != nil { - disks = make([]compute.DataDisk, len(*storageProfile.DataDisks)) - copy(disks, *storageProfile.DataDisks) + disks = make([]*armcompute.DataDisk, len(storageProfile.DataDisks)) + copy(disks, storageProfile.DataDisks) } for k, v := range diskMap { - diskURI := k + diSKURI := k opt := v attached := false - for _, disk := range *storageProfile.DataDisks { - if disk.ManagedDisk != nil && strings.EqualFold(*disk.ManagedDisk.ID, diskURI) && disk.Lun != nil { + for _, disk := range storageProfile.DataDisks { + if disk.ManagedDisk != nil && strings.EqualFold(*disk.ManagedDisk.ID, diSKURI) && disk.Lun != nil { if *disk.Lun == opt.Lun { attached = true break } - return fmt.Errorf("disk(%s) already attached to node(%s) on LUN(%d), but target LUN is %d", diskURI, nodeName, *disk.Lun, opt.Lun) + return fmt.Errorf("disk(%s) already attached to node(%s) on LUN(%d), but target LUN is %d", diSKURI, nodeName, *disk.Lun, opt.Lun) } } if attached { - klog.V(2).Infof("azureDisk - disk(%s) already attached to node(%s) on LUN(%d)", diskURI, nodeName, opt.Lun) + klog.V(2).Infof("azureDisk - disk(%s) already attached to node(%s) on LUN(%d)", diSKURI, nodeName, opt.Lun) continue } - managedDisk := &compute.ManagedDiskParameters{ID: &diskURI} + managedDisk := &armcompute.ManagedDiskParameters{ID: &diSKURI} if opt.DiskEncryptionSetID == "" { - if storageProfile.OsDisk != nil && - storageProfile.OsDisk.ManagedDisk != nil && - storageProfile.OsDisk.ManagedDisk.DiskEncryptionSet != nil && - storageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.ID != nil { + if storageProfile.OSDisk != nil && + storageProfile.OSDisk.ManagedDisk != nil && + storageProfile.OSDisk.ManagedDisk.DiskEncryptionSet != nil && + storageProfile.OSDisk.ManagedDisk.DiskEncryptionSet.ID != nil { // set diskEncryptionSet as value of os disk by default - opt.DiskEncryptionSetID = *storageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.ID + opt.DiskEncryptionSetID = *storageProfile.OSDisk.ManagedDisk.DiskEncryptionSet.ID } } if opt.DiskEncryptionSetID != "" { - managedDisk.DiskEncryptionSet = &compute.DiskEncryptionSetParameters{ID: &opt.DiskEncryptionSetID} + managedDisk.DiskEncryptionSet = &armcompute.DiskEncryptionSetParameters{ID: &opt.DiskEncryptionSetID} } disks = append(disks, - compute.DataDisk{ + &armcompute.DataDisk{ Name: &opt.DiskName, Lun: &opt.Lun, - Caching: opt.CachingMode, - CreateOption: "attach", + Caching: to.Ptr(opt.CachingMode), + CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesAttach), ManagedDisk: managedDisk, WriteAcceleratorEnabled: ptr.To(opt.WriteAcceleratorEnabled), }) } - newVM := compute.VirtualMachineScaleSetVM{ - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - StorageProfile: &compute.StorageProfile{ - DataDisks: &disks, + newVM := &armcompute.VirtualMachineScaleSetVM{ + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ + StorageProfile: &armcompute.StorageProfile{ + DataDisks: disks, }, }, } klog.V(2).Infof("azureDisk - update: rg(%s) vm(%s) - attach disk list(%+v)", nodeResourceGroup, nodeName, diskMap) - future, rerr := ss.VirtualMachineScaleSetVMsClient.UpdateAsync(ctx, nodeResourceGroup, vm.VMSSName, vm.InstanceID, newVM, "attach_disk") + result, rerr := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().Update(ctx, nodeResourceGroup, vm.VMSSName, vm.InstanceID, *newVM) if rerr != nil { klog.Errorf("azureDisk - attach disk list(%+v) on rg(%s) vm(%s) failed, err: %v", diskMap, nodeResourceGroup, nodeName, rerr) - if rerr.HTTPStatusCode == http.StatusNotFound { + if exists, err := errutils.CheckResourceExistsFromAzcoreError(rerr); exists && err == nil { klog.Errorf("azureDisk - begin to filterNonExistingDisks(%v) on rg(%s) vm(%s)", diskMap, nodeResourceGroup, nodeName) - disks := FilterNonExistingDisks(ctx, ss.DisksClient, *newVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks) - newVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks = &disks - future, rerr = ss.VirtualMachineScaleSetVMsClient.UpdateAsync(ctx, nodeResourceGroup, vm.VMSSName, vm.InstanceID, newVM, "attach_disk") + disks := FilterNonExistingDisks(ctx, ss.ComputeClientFactory, newVM.Properties.StorageProfile.DataDisks) + newVM.Properties.StorageProfile.DataDisks = disks + result, rerr = ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().Update(ctx, nodeResourceGroup, vm.VMSSName, vm.InstanceID, *newVM) } } klog.V(2).Infof("azureDisk - update: rg(%s) vm(%s) - attach disk list(%+v) returned with %v", nodeResourceGroup, nodeName, diskMap, rerr) if rerr != nil { - return rerr.Error() - } - return ss.WaitForUpdateResult(ctx, future, nodeName, "attach_disk") -} - -// WaitForUpdateResult waits for the response of the update request -func (ss *ScaleSet) WaitForUpdateResult(ctx context.Context, future *azure.Future, nodeName types.NodeName, source string) error { - vmName := mapNodeNameToVMName(nodeName) - nodeResourceGroup, err := ss.GetNodeResourceGroup(vmName) - if err != nil { - return err + return rerr } - result, rerr := ss.VirtualMachineScaleSetVMsClient.WaitForUpdateResult(ctx, future, nodeResourceGroup, source) - if rerr != nil { - return rerr.Error() - } + // clean node cache first and then update cache + _ = ss.DeleteCacheForNode(ctx, vmName) var vmssName, instanceID string - if result != nil && result.VirtualMachineScaleSetVMProperties != nil { + if result != nil && result.Properties != nil { // get vmssName, instanceID from cache first vm, err := ss.getVmssVM(ctx, vmName, azcache.CacheReadTypeDefault) if err == nil && vm != nil { @@ -150,16 +136,14 @@ func (ss *ScaleSet) WaitForUpdateResult(ctx context.Context, future *azure.Futur } else { klog.Errorf("getVmssVM failed with error(%v) or nil pointer", err) } - } - // clean node cache first and then update cache - _ = ss.DeleteCacheForNode(ctx, vmName) - if vmssName != "" && instanceID != "" { - if err := ss.updateCache(ctx, vmName, nodeResourceGroup, vmssName, instanceID, result); err != nil { - klog.Errorf("updateCache(%s, %s, %s, %s) failed with error: %v", vmName, nodeResourceGroup, vmssName, instanceID, err) + if vm.VMSSName != "" && instanceID != "" { + if err := ss.updateCache(ctx, vmName, nodeResourceGroup, vmssName, instanceID, result); err != nil { + klog.Errorf("updateCache(%s, %s, %s, %s) failed with error: %v", vmName, nodeResourceGroup, vmssName, instanceID, err) + } } } - return nil + return rerr } // DetachDisk detaches a disk from VM @@ -175,26 +159,26 @@ func (ss *ScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, dis return err } - var disks []compute.DataDisk + var disks []*armcompute.DataDisk - if vm != nil && vm.VirtualMachineScaleSetVMProperties != nil { - storageProfile := vm.VirtualMachineScaleSetVMProperties.StorageProfile + if vm != nil && vm.VirtualMachineProperties != nil { + storageProfile := vm.VirtualMachineProperties.StorageProfile if storageProfile != nil && storageProfile.DataDisks != nil { - disks = make([]compute.DataDisk, len(*storageProfile.DataDisks)) - copy(disks, *storageProfile.DataDisks) + disks = make([]*armcompute.DataDisk, len(storageProfile.DataDisks)) + copy(disks, storageProfile.DataDisks) } } bFoundDisk := false for i, disk := range disks { - for diskURI, diskName := range diskMap { + for diSKURI, diskName := range diskMap { if disk.Lun != nil && (disk.Name != nil && diskName != "" && strings.EqualFold(*disk.Name, diskName)) || - (disk.Vhd != nil && disk.Vhd.URI != nil && diskURI != "" && strings.EqualFold(*disk.Vhd.URI, diskURI)) || - (disk.ManagedDisk != nil && diskURI != "" && strings.EqualFold(*disk.ManagedDisk.ID, diskURI)) { + (disk.Vhd != nil && disk.Vhd.URI != nil && diSKURI != "" && strings.EqualFold(*disk.Vhd.URI, diSKURI)) || + (disk.ManagedDisk != nil && diSKURI != "" && strings.EqualFold(*disk.ManagedDisk.ID, diSKURI)) { // found the disk - klog.V(2).Infof("azureDisk - detach disk: name %s uri %s", diskName, diskURI) + klog.V(2).Infof("azureDisk - detach disk: name %s uri %s", diskName, diSKURI) disks[i].ToBeDetached = ptr.To(true) if forceDetach { - disks[i].DetachOption = compute.ForceDetach + disks[i].DetachOption = to.Ptr(armcompute.DiskDetachOptionTypesForceDetach) } bFoundDisk = true } @@ -207,7 +191,7 @@ func (ss *ScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, dis } else { if strings.EqualFold(ss.Environment.Name, consts.AzureStackCloudName) && !ss.Config.DisableAzureStackCloud { // Azure stack does not support ToBeDetached flag, use original way to detach disk - var newDisks []compute.DataDisk + var newDisks []*armcompute.DataDisk for _, disk := range disks { if !ptr.Deref(disk.ToBeDetached, false) { newDisks = append(newDisks, disk) @@ -217,23 +201,23 @@ func (ss *ScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, dis } } - newVM := compute.VirtualMachineScaleSetVM{ - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - StorageProfile: &compute.StorageProfile{ - DataDisks: &disks, + newVM := &armcompute.VirtualMachineScaleSetVM{ + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ + StorageProfile: &armcompute.StorageProfile{ + DataDisks: disks, }, }, } - var result *compute.VirtualMachineScaleSetVM - var rerr *retry.Error + var result *armcompute.VirtualMachineScaleSetVM + var rerr error defer func() { _ = ss.DeleteCacheForNode(ctx, vmName) // Update the cache with the updated result only if its not nil - // and contains the VirtualMachineScaleSetVMProperties - if rerr == nil && result != nil && result.VirtualMachineScaleSetVMProperties != nil { + // and contains the.Properties + if rerr == nil && result != nil && result.Properties != nil { if err := ss.updateCache(ctx, vmName, nodeResourceGroup, vm.VMSSName, vm.InstanceID, result); err != nil { klog.Errorf("updateCache(%s, %s, %s, %s) failed with error: %v", vmName, nodeResourceGroup, vm.VMSSName, vm.InstanceID, err) } @@ -241,52 +225,42 @@ func (ss *ScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, dis }() klog.V(2).Infof("azureDisk - update(%s): vm(%s) - detach disk list(%s)", nodeResourceGroup, nodeName, diskMap) - result, rerr = ss.VirtualMachineScaleSetVMsClient.Update(ctx, nodeResourceGroup, vm.VMSSName, vm.InstanceID, newVM, - "detach_disk") + result, rerr = ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().Update(ctx, nodeResourceGroup, vm.VMSSName, vm.InstanceID, *newVM) if rerr != nil { klog.Errorf("azureDisk - detach disk list(%s) on rg(%s) vm(%s) failed, err: %v", diskMap, nodeResourceGroup, nodeName, rerr) - if rerr.HTTPStatusCode == http.StatusNotFound { + if exists, err := errutils.CheckResourceExistsFromAzcoreError(rerr); exists && err == nil { klog.Errorf("azureDisk - begin to filterNonExistingDisks(%v) on rg(%s) vm(%s)", diskMap, nodeResourceGroup, nodeName) - disks := FilterNonExistingDisks(ctx, ss.DisksClient, *newVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks) - newVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks = &disks - result, rerr = ss.VirtualMachineScaleSetVMsClient.Update(ctx, nodeResourceGroup, vm.VMSSName, vm.InstanceID, newVM, "detach_disk") + disks := FilterNonExistingDisks(ctx, ss.ComputeClientFactory, newVM.Properties.StorageProfile.DataDisks) + newVM.Properties.StorageProfile.DataDisks = disks + result, rerr = ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().Update(ctx, nodeResourceGroup, vm.VMSSName, vm.InstanceID, *newVM) } } klog.V(2).Infof("azureDisk - update(%s): vm(%s) - detach disk(%v) returned with %v", nodeResourceGroup, nodeName, diskMap, rerr) if rerr != nil { - return rerr.Error() + return rerr } return nil } // UpdateVM updates a vm func (ss *ScaleSet) UpdateVM(ctx context.Context, nodeName types.NodeName) error { - future, err := ss.UpdateVMAsync(ctx, nodeName) - if err != nil { - return err - } - return ss.WaitForUpdateResult(ctx, future, nodeName, "update_vm") -} - -// UpdateVMAsync updates a vm asynchronously -func (ss *ScaleSet) UpdateVMAsync(ctx context.Context, nodeName types.NodeName) (*azure.Future, error) { vmName := mapNodeNameToVMName(nodeName) vm, err := ss.getVmssVM(ctx, vmName, azcache.CacheReadTypeDefault) if err != nil { - return nil, err + return err } nodeResourceGroup, err := ss.GetNodeResourceGroup(vmName) if err != nil { - return nil, err + return err } - future, rerr := ss.VirtualMachineScaleSetVMsClient.UpdateAsync(ctx, nodeResourceGroup, vm.VMSSName, vm.InstanceID, compute.VirtualMachineScaleSetVM{}, "update_vmss_instance") + _, rerr := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().Update(ctx, nodeResourceGroup, vm.VMSSName, vm.InstanceID, armcompute.VirtualMachineScaleSetVM{}) if rerr != nil { - return future, rerr.Error() + return rerr } - return future, nil + return nil } // GetDataDisks gets a list of data disks attached to the node. @@ -296,17 +270,13 @@ func (ss *ScaleSet) GetDataDisks(ctx context.Context, nodeName types.NodeName, c return nil, nil, err } - if vm != nil && vm.AsVirtualMachineScaleSetVM() != nil && vm.AsVirtualMachineScaleSetVM().VirtualMachineScaleSetVMProperties != nil { - storageProfile := vm.AsVirtualMachineScaleSetVM().StorageProfile + if vm != nil && vm.AsVirtualMachineScaleSetVM() != nil && vm.AsVirtualMachineScaleSetVM().Properties != nil { + storageProfile := vm.AsVirtualMachineScaleSetVM().Properties.StorageProfile if storageProfile == nil || storageProfile.DataDisks == nil { return nil, nil, nil } - result, err := ToArmcomputeDisk(*storageProfile.DataDisks) - if err != nil { - return nil, nil, err - } - return result, vm.AsVirtualMachineScaleSetVM().ProvisioningState, nil + return storageProfile.DataDisks, vm.AsVirtualMachineScaleSetVM().Properties.ProvisioningState, nil } return nil, nil, nil diff --git a/pkg/provider/azure_controller_vmss_test.go b/pkg/provider/azure_controller_vmss_test.go index 5dff138cfb..8b63724c60 100644 --- a/pkg/provider/azure_controller_vmss_test.go +++ b/pkg/provider/azure_controller_vmss_test.go @@ -23,10 +23,8 @@ import ( "strings" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/azure" - autorestmocks "github.com/Azure/go-autorest/autorest/mocks" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -35,11 +33,10 @@ import ( cloudprovider "k8s.io/cloud-provider" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssvmclient/mockvmssvmclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/mock_virtualmachinescalesetclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetvmclient/mock_virtualmachinescalesetvmclient" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) func TestAttachDiskWithVMSS(t *testing.T) { @@ -101,42 +98,41 @@ func TestAttachDiskWithVMSS(t *testing.T) { testCloud := ss.Cloud testCloud.PrimaryScaleSetName = scaleSetName expectedVMSS := buildTestVMSSWithLB(scaleSetName, "vmss00-vm-", []string{testLBBackendpoolID0}, false) - mockVMSSClient := testCloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - mockVMSSClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, scaleSetName).Return(expectedVMSS, nil).MaxTimes(1) - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(nil).MaxTimes(1) - mockVMClient := testCloud.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachine{}, nil).AnyTimes() + mockVMSSClient := testCloud.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + mockVMSSClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, scaleSetName, nil).Return(expectedVMSS, nil).MaxTimes(1) + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(nil, nil).MaxTimes(1) + mockVMClient := testCloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(testCloud, scaleSetName, "", 0, test.vmssVMList, "succeeded", false) for _, vmssvm := range expectedVMSSVMs { - vmssvm.StorageProfile = &compute.StorageProfile{ - OsDisk: &compute.OSDisk{ - Name: ptr.To("osdisk1"), - ManagedDisk: &compute.ManagedDiskParameters{ + vmssvm.Properties.StorageProfile = &armcompute.StorageProfile{ + OSDisk: &armcompute.OSDisk{ + Name: ptr.To("OSDisk1"), + ManagedDisk: &armcompute.ManagedDiskParameters{ ID: ptr.To("ManagedID"), - DiskEncryptionSet: &compute.DiskEncryptionSetParameters{ + DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{ ID: ptr.To("DiskEncryptionSetID"), }, }, }, - DataDisks: &[]compute.DataDisk{}, + DataDisks: []*armcompute.DataDisk{}, } if test.inconsistentLUN { - diskURI := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/disks/%s", + diSKURI := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/disks/%s", testCloud.SubscriptionID, testCloud.ResourceGroup, diskname) - vmssvm.StorageProfile.DataDisks = &[]compute.DataDisk{ - {Lun: ptr.To(int32(0)), Name: &diskname, ManagedDisk: &compute.ManagedDiskParameters{ID: &diskURI}}, + vmssvm.Properties.StorageProfile.DataDisks = []*armcompute.DataDisk{ + {Lun: ptr.To(int32(0)), Name: &diskname, ManagedDisk: &armcompute.ManagedDiskParameters{ID: &diSKURI}}, } } } - mockVMSSVMClient := testCloud.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + mockVMSSVMClient := testCloud.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), testCloud.ResourceGroup, scaleSetName).Return(expectedVMSSVMs, nil).AnyTimes() if scaleSetName == string(fakeStatusNotFoundVMSSName) { - mockVMSSVMClient.EXPECT().UpdateAsync(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockVMSSVMClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any(), gomock.Any()).Return(nil, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() } else { - mockVMSSVMClient.EXPECT().UpdateAsync(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - mockVMSSVMClient.EXPECT().WaitForUpdateResult(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + mockVMSSVMClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() } diskMap := map[string]*AttachDiskOptions{} @@ -144,7 +140,7 @@ func TestAttachDiskWithVMSS(t *testing.T) { options := AttachDiskOptions{ Lun: int32(i), DiskName: diskName, - CachingMode: compute.CachingTypesReadWrite, + CachingMode: armcompute.CachingTypesReadWrite, DiskEncryptionSetID: "", WriteAcceleratorEnabled: true, } @@ -152,9 +148,9 @@ func TestAttachDiskWithVMSS(t *testing.T) { options.Lun = 63 } - diskURI := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/disks/%s", + diSKURI := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/disks/%s", testCloud.SubscriptionID, testCloud.ResourceGroup, diskName) - diskMap[diskURI] = &options + diskMap[diSKURI] = &options } err = ss.AttachDisk(ctx, test.vmssvmName, diskMap) assert.Equal(t, test.expectedErr, err, "TestCase[%d]: %s, expected error: %v, return error: %v", i, test.desc, test.expectedErr, err) @@ -179,7 +175,7 @@ func TestDetachDiskWithVMSS(t *testing.T) { disks []string forceDetach bool expectedErr bool - expectedErrMsg error + expectedErrMsg string }{ { desc: "an error shall be returned if it is invalid vmss name", @@ -188,7 +184,7 @@ func TestDetachDiskWithVMSS(t *testing.T) { vmssvmName: "vm1", disks: []string{diskName}, expectedErr: true, - expectedErrMsg: fmt.Errorf("not a vmss instance"), + expectedErrMsg: "not a vmss instance", }, { desc: "no error shall be returned if everything is good", @@ -222,7 +218,7 @@ func TestDetachDiskWithVMSS(t *testing.T) { vmssvmName: "vmss00-vm-000000", disks: []string{diskName}, expectedErr: true, - expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 404, RawError: %w", fmt.Errorf("instance not found")), + expectedErrMsg: "instance not found", }, { desc: "no error shall be returned if everything is good and the attaching disk does not match data disk", @@ -241,25 +237,25 @@ func TestDetachDiskWithVMSS(t *testing.T) { testCloud := ss.Cloud testCloud.PrimaryScaleSetName = scaleSetName expectedVMSS := buildTestVMSSWithLB(scaleSetName, "vmss00-vm-", []string{testLBBackendpoolID0}, false) - mockVMSSClient := testCloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - mockVMSSClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, scaleSetName).Return(expectedVMSS, nil).MaxTimes(1) - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(nil).MaxTimes(1) + mockVMSSClient := testCloud.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + mockVMSSClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(expectedVMSS, nil).MaxTimes(1) + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(nil, nil).MaxTimes(1) expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(testCloud, scaleSetName, "", 0, test.vmssVMList, "succeeded", false) - var updatedVMSSVM *compute.VirtualMachineScaleSetVM + var updatedVMSSVM *armcompute.VirtualMachineScaleSetVM for itr, vmssvm := range expectedVMSSVMs { - vmssvm.StorageProfile = &compute.StorageProfile{ - OsDisk: &compute.OSDisk{ - Name: ptr.To("osdisk1"), - ManagedDisk: &compute.ManagedDiskParameters{ + vmssvm.Properties.StorageProfile = &armcompute.StorageProfile{ + OSDisk: &armcompute.OSDisk{ + Name: ptr.To("OSDisk1"), + ManagedDisk: &armcompute.ManagedDiskParameters{ ID: ptr.To("ManagedID"), - DiskEncryptionSet: &compute.DiskEncryptionSetParameters{ + DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{ ID: ptr.To("DiskEncryptionSetID"), }, }, }, - DataDisks: &[]compute.DataDisk{ + DataDisks: []*armcompute.DataDisk{ { Lun: ptr.To(int32(0)), Name: ptr.To(diskName), @@ -275,31 +271,31 @@ func TestDetachDiskWithVMSS(t *testing.T) { }, } - if string(test.vmssvmName) == *vmssvm.VirtualMachineScaleSetVMProperties.OsProfile.ComputerName { - updatedVMSSVM = &expectedVMSSVMs[itr] + if string(test.vmssvmName) == *vmssvm.Properties.OSProfile.ComputerName { + updatedVMSSVM = expectedVMSSVMs[itr] } } - mockVMSSVMClient := testCloud.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + mockVMSSVMClient := testCloud.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), testCloud.ResourceGroup, scaleSetName).Return(expectedVMSSVMs, nil).AnyTimes() if scaleSetName == strings.ToLower(string(fakeStatusNotFoundVMSSName)) { - mockVMSSVMClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any(), gomock.Any(), gomock.Any()).Return(updatedVMSSVM, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockVMSSVMClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any(), gomock.Any()).Return(updatedVMSSVM, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() } else { - mockVMSSVMClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any(), gomock.Any(), gomock.Any()).Return(updatedVMSSVM, nil).AnyTimes() + mockVMSSVMClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any(), gomock.Any()).Return(updatedVMSSVM, nil).AnyTimes() } - mockVMClient := testCloud.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachine{}, nil).AnyTimes() + mockVMClient := testCloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() diskMap := map[string]string{} for _, diskName := range test.disks { - diskURI := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/disks/%s", + diSKURI := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/disks/%s", testCloud.SubscriptionID, testCloud.ResourceGroup, diskName) - diskMap[diskURI] = diskName + diskMap[diSKURI] = diskName } err = ss.DetachDisk(ctx, test.vmssvmName, diskMap, test.forceDetach) assert.Equal(t, test.expectedErr, err != nil, "TestCase[%d]: %s, err: %v", i, test.desc, err) if test.expectedErr { - assert.EqualError(t, test.expectedErrMsg, err.Error(), "TestCase[%d]: %s, expected error: %v, return error: %v", i, test.desc, test.expectedErrMsg, err) + assert.Contains(t, err.Error(), test.expectedErrMsg, "TestCase[%d]: %s, expected error: %v, return error: %v", i, test.desc, test.expectedErrMsg, err) } if !test.expectedErr { @@ -324,25 +320,25 @@ func TestUpdateVMWithVMSS(t *testing.T) { vmssVMList []string vmssName types.NodeName vmssvmName types.NodeName - existedDisk compute.Disk + existedDisk armcompute.Disk expectedErr bool - expectedErrMsg error + expectedErrMsg string }{ { desc: "an error shall be returned if it is invalid vmss name", vmssVMList: []string{"vmss-vm-000001"}, vmssName: "vm1", vmssvmName: "vm1", - existedDisk: compute.Disk{Name: ptr.To(diskName)}, + existedDisk: armcompute.Disk{Name: ptr.To(diskName)}, expectedErr: true, - expectedErrMsg: fmt.Errorf("not a vmss instance"), + expectedErrMsg: "not a vmss instance", }, { desc: "no error shall be returned if everything is good", vmssVMList: []string{"vmss00-vm-000000", "vmss00-vm-000001", "vmss00-vm-000002"}, vmssName: "vmss00", vmssvmName: "vmss00-vm-000000", - existedDisk: compute.Disk{Name: ptr.To(diskName)}, + existedDisk: armcompute.Disk{Name: ptr.To(diskName)}, expectedErr: false, }, { @@ -350,16 +346,16 @@ func TestUpdateVMWithVMSS(t *testing.T) { vmssVMList: []string{"vmss00-vm-000000", "vmss00-vm-000001", "vmss00-vm-000002"}, vmssName: fakeStatusNotFoundVMSSName, vmssvmName: "vmss00-vm-000000", - existedDisk: compute.Disk{Name: ptr.To(diskName)}, + existedDisk: armcompute.Disk{Name: ptr.To(diskName)}, expectedErr: true, - expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 404, RawError: %w", fmt.Errorf("instance not found")), + expectedErrMsg: "instance not found", }, { desc: "no error shall be returned if everything is good and the attaching disk does not match data disk", vmssVMList: []string{"vmss00-vm-000000", "vmss00-vm-000001", "vmss00-vm-000002"}, vmssName: "vmss00", vmssvmName: "vmss00-vm-000000", - existedDisk: compute.Disk{Name: ptr.To("disk-name-err")}, + existedDisk: armcompute.Disk{Name: ptr.To("disk-name-err")}, expectedErr: false, }, } @@ -371,58 +367,51 @@ func TestUpdateVMWithVMSS(t *testing.T) { testCloud := ss.Cloud testCloud.PrimaryScaleSetName = scaleSetName expectedVMSS := buildTestVMSSWithLB(scaleSetName, "vmss00-vm-", []string{testLBBackendpoolID0}, false) - mockVMSSClient := testCloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - mockVMSSClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, scaleSetName).Return(expectedVMSS, nil).MaxTimes(1) - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(nil).MaxTimes(1) + mockVMSSClient := testCloud.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + mockVMSSClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(expectedVMSS, nil).MaxTimes(1) + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(nil, nil).MaxTimes(1) expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(testCloud, scaleSetName, "", 0, test.vmssVMList, "succeeded", false) - var updatedVMSSVM *compute.VirtualMachineScaleSetVM + var updatedVMSSVM *armcompute.VirtualMachineScaleSetVM for itr, vmssvm := range expectedVMSSVMs { - vmssvm.StorageProfile = &compute.StorageProfile{ - OsDisk: &compute.OSDisk{ - Name: ptr.To("osdisk1"), - ManagedDisk: &compute.ManagedDiskParameters{ + vmssvm.Properties.StorageProfile = &armcompute.StorageProfile{ + OSDisk: &armcompute.OSDisk{ + Name: ptr.To("OSDisk1"), + ManagedDisk: &armcompute.ManagedDiskParameters{ ID: ptr.To("ManagedID"), - DiskEncryptionSet: &compute.DiskEncryptionSetParameters{ + DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{ ID: ptr.To("DiskEncryptionSetID"), }, }, }, - DataDisks: &[]compute.DataDisk{{ + DataDisks: []*armcompute.DataDisk{{ Lun: ptr.To(int32(0)), Name: ptr.To(diskName), }}, } - if string(test.vmssvmName) == *vmssvm.VirtualMachineScaleSetVMProperties.OsProfile.ComputerName { - updatedVMSSVM = &expectedVMSSVMs[itr] + if string(test.vmssvmName) == *vmssvm.Properties.OSProfile.ComputerName { + updatedVMSSVM = expectedVMSSVMs[itr] } } - mockVMSSVMClient := testCloud.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() - - r := autorestmocks.NewResponseWithStatus("200", 200) - r.Request.Method = http.MethodPut - - future, err := azure.NewFutureFromResponse(r) - - mockVMSSVMClient.EXPECT().UpdateAsync(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&future, err).AnyTimes() + mockVMSSVMClient := testCloud.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), testCloud.ResourceGroup, scaleSetName).Return(expectedVMSSVMs, nil).AnyTimes() if scaleSetName == strings.ToLower(string(fakeStatusNotFoundVMSSName)) { - mockVMSSVMClient.EXPECT().WaitForUpdateResult(gomock.Any(), &future, testCloud.ResourceGroup, gomock.Any()).Return(updatedVMSSVM, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockVMSSVMClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(updatedVMSSVM, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() } else { - mockVMSSVMClient.EXPECT().WaitForUpdateResult(gomock.Any(), &future, testCloud.ResourceGroup, gomock.Any()).Return(updatedVMSSVM, nil).AnyTimes() + mockVMSSVMClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(updatedVMSSVM, err).AnyTimes() } - mockVMClient := testCloud.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachine{}, nil).AnyTimes() + mockVMClient := testCloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() err = ss.UpdateVM(ctx, test.vmssvmName) assert.Equal(t, test.expectedErr, err != nil, "TestCase[%d]: %s, err: %v", i, test.desc, err) if test.expectedErr { - assert.EqualError(t, test.expectedErrMsg, err.Error(), "TestCase[%d]: %s, expected error: %v, return error: %v", i, test.desc, test.expectedErrMsg, err) + assert.Contains(t, err.Error(), test.expectedErrMsg, "TestCase[%d]: %s, expected error: %v, return error: %v", i, test.desc, test.expectedErrMsg, err) } if !test.expectedErr { @@ -493,26 +482,26 @@ func TestGetDataDisksWithVMSS(t *testing.T) { testCloud := ss.Cloud testCloud.PrimaryScaleSetName = scaleSetName expectedVMSS := buildTestVMSSWithLB(scaleSetName, "vmss00-vm-", []string{testLBBackendpoolID0}, false) - mockVMSSClient := testCloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - mockVMSSClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, scaleSetName).Return(expectedVMSS, nil).MaxTimes(1) - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(nil).MaxTimes(1) + mockVMSSClient := testCloud.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + mockVMSSClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(expectedVMSS, nil).MaxTimes(1) + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(nil, nil).MaxTimes(1) expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(testCloud, scaleSetName, "", 0, []string{"vmss00-vm-000000"}, "succeeded", false) if !test.isDataDiskNull { for _, vmssvm := range expectedVMSSVMs { - vmssvm.StorageProfile = &compute.StorageProfile{ - DataDisks: &[]compute.DataDisk{{ + vmssvm.Properties.StorageProfile = &armcompute.StorageProfile{ + DataDisks: []*armcompute.DataDisk{{ Lun: ptr.To(int32(0)), Name: ptr.To("disk1"), }}, } } } - updatedVMSSVM := &expectedVMSSVMs[0] - mockVMSSVMClient := testCloud.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() - mockVMSSVMClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any(), gomock.Any(), gomock.Any()).Return(updatedVMSSVM, nil).AnyTimes() + updatedVMSSVM := expectedVMSSVMs[0] + mockVMSSVMClient := testCloud.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), testCloud.ResourceGroup, scaleSetName).Return(expectedVMSSVMs, nil).AnyTimes() + mockVMSSVMClient.EXPECT().Update(gomock.Any(), testCloud.ResourceGroup, scaleSetName, gomock.Any(), gomock.Any()).Return(updatedVMSSVM, nil).AnyTimes() dataDisks, _, err := ss.GetDataDisks(context.TODO(), test.nodeName, test.crt) assert.Equal(t, test.expectedDataDisks, dataDisks, "TestCase[%d]: %s", i, test.desc) assert.Equal(t, test.expectedErr, err != nil, "TestCase[%d]: %s", i, test.desc) diff --git a/pkg/provider/azure_controller_vmssflex.go b/pkg/provider/azure_controller_vmssflex.go index 7e22880879..80fbfa772b 100644 --- a/pkg/provider/azure_controller_vmssflex.go +++ b/pkg/provider/azure_controller_vmssflex.go @@ -18,14 +18,16 @@ package provider import ( "context" + "errors" "fmt" "net/http" "strings" "sync" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/azure" "k8s.io/apimachinery/pkg/types" "k8s.io/klog/v2" @@ -33,7 +35,6 @@ import ( azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) // AttachDisk attaches a disk to vm @@ -49,77 +50,84 @@ func (fs *FlexScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, return err } - disks := make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks)) - copy(disks, *vm.StorageProfile.DataDisks) + disks := make([]*armcompute.DataDisk, len(vm.Properties.StorageProfile.DataDisks)) + copy(disks, vm.Properties.StorageProfile.DataDisks) for k, v := range diskMap { - diskURI := k + diSKURI := k opt := v attached := false - for _, disk := range *vm.StorageProfile.DataDisks { - if disk.ManagedDisk != nil && strings.EqualFold(*disk.ManagedDisk.ID, diskURI) && disk.Lun != nil { + for _, disk := range vm.Properties.StorageProfile.DataDisks { + if disk.ManagedDisk != nil && strings.EqualFold(*disk.ManagedDisk.ID, diSKURI) && disk.Lun != nil { if *disk.Lun == opt.Lun { attached = true break } - return fmt.Errorf("disk(%s) already attached to node(%s) on LUN(%d), but target LUN is %d", diskURI, nodeName, *disk.Lun, opt.Lun) + return fmt.Errorf("disk(%s) already attached to node(%s) on LUN(%d), but target LUN is %d", diSKURI, nodeName, *disk.Lun, opt.Lun) } } if attached { - klog.V(2).Infof("azureDisk - disk(%s) already attached to node(%s) on LUN(%d)", diskURI, nodeName, opt.Lun) + klog.V(2).Infof("azureDisk - disk(%s) already attached to node(%s) on LUN(%d)", diSKURI, nodeName, opt.Lun) continue } - managedDisk := &compute.ManagedDiskParameters{ID: &diskURI} + managedDisk := &armcompute.ManagedDiskParameters{ID: &diSKURI} if opt.DiskEncryptionSetID == "" { - if vm.StorageProfile.OsDisk != nil && - vm.StorageProfile.OsDisk.ManagedDisk != nil && - vm.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet != nil && - vm.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.ID != nil { + if vm.Properties.StorageProfile.OSDisk != nil && + vm.Properties.StorageProfile.OSDisk.ManagedDisk != nil && + vm.Properties.StorageProfile.OSDisk.ManagedDisk.DiskEncryptionSet != nil && + vm.Properties.StorageProfile.OSDisk.ManagedDisk.DiskEncryptionSet.ID != nil { // set diskEncryptionSet as value of os disk by default - opt.DiskEncryptionSetID = *vm.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.ID + opt.DiskEncryptionSetID = *vm.Properties.StorageProfile.OSDisk.ManagedDisk.DiskEncryptionSet.ID } } if opt.DiskEncryptionSetID != "" { - managedDisk.DiskEncryptionSet = &compute.DiskEncryptionSetParameters{ID: &opt.DiskEncryptionSetID} + managedDisk.DiskEncryptionSet = &armcompute.DiskEncryptionSetParameters{ID: &opt.DiskEncryptionSetID} } disks = append(disks, - compute.DataDisk{ + &armcompute.DataDisk{ Name: &opt.DiskName, Lun: &opt.Lun, - Caching: opt.CachingMode, - CreateOption: "attach", + Caching: to.Ptr(opt.CachingMode), + CreateOption: to.Ptr(armcompute.DiskCreateOptionTypesAttach), ManagedDisk: managedDisk, WriteAcceleratorEnabled: ptr.To(opt.WriteAcceleratorEnabled), }) } - newVM := compute.VirtualMachineUpdate{ - VirtualMachineProperties: &compute.VirtualMachineProperties{ - StorageProfile: &compute.StorageProfile{ - DataDisks: &disks, + newVM := armcompute.VirtualMachine{ + Properties: &armcompute.VirtualMachineProperties{ + StorageProfile: &armcompute.StorageProfile{ + DataDisks: disks, }, }, } klog.V(2).Infof("azureDisk - update: rg(%s) vm(%s) - attach disk list(%+v)", nodeResourceGroup, vmName, diskMap) - - future, rerr := fs.VirtualMachinesClient.UpdateAsync(ctx, nodeResourceGroup, *vm.Name, newVM, "attach_disk") - if rerr != nil { + result, err := fs.ComputeClientFactory.GetVirtualMachineClient().CreateOrUpdate(ctx, nodeResourceGroup, *vm.Name, newVM) + var rerr *azcore.ResponseError + if err != nil && errors.As(err, &rerr) { klog.Errorf("azureDisk - attach disk list(%+v) on rg(%s) vm(%s) failed, err: %v", diskMap, nodeResourceGroup, vmName, rerr) - if rerr.HTTPStatusCode == http.StatusNotFound { + if rerr.StatusCode == http.StatusNotFound { klog.Errorf("azureDisk - begin to filterNonExistingDisks(%v) on rg(%s) vm(%s)", diskMap, nodeResourceGroup, vmName) - disks := FilterNonExistingDisks(ctx, fs.DisksClient, *newVM.VirtualMachineProperties.StorageProfile.DataDisks) - newVM.VirtualMachineProperties.StorageProfile.DataDisks = &disks - future, rerr = fs.VirtualMachinesClient.UpdateAsync(ctx, nodeResourceGroup, *vm.Name, newVM, "attach_disk") + disks := FilterNonExistingDisks(ctx, fs.ComputeClientFactory, newVM.Properties.StorageProfile.DataDisks) + newVM.Properties.StorageProfile.DataDisks = disks + result, err = fs.ComputeClientFactory.GetVirtualMachineClient().CreateOrUpdate(ctx, nodeResourceGroup, *vm.Name, newVM) } } klog.V(2).Infof("azureDisk - update(%s): vm(%s) - attach disk list(%+v) returned with %v", nodeResourceGroup, vmName, diskMap, rerr) - if rerr != nil { - return rerr.Error() + if err != nil { + return err } - return fs.WaitForUpdateResult(ctx, future, nodeName, "attach_disk") + // clean node cache first and then update cache + _ = fs.DeleteCacheForNode(ctx, vmName) + if result != nil && result.Properties != nil { + if err := fs.updateCache(ctx, vmName, result); err != nil { + klog.Errorf("updateCache(%s) failed with error: %v", vmName, err) + } + } + return nil } // DetachDisk detaches a disk from VM @@ -137,20 +145,20 @@ func (fs *FlexScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, return err } - disks := make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks)) - copy(disks, *vm.StorageProfile.DataDisks) + disks := make([]*armcompute.DataDisk, len(vm.Properties.StorageProfile.DataDisks)) + copy(disks, vm.Properties.StorageProfile.DataDisks) bFoundDisk := false for i, disk := range disks { - for diskURI, diskName := range diskMap { + for diSKURI, diskName := range diskMap { if disk.Lun != nil && (disk.Name != nil && diskName != "" && strings.EqualFold(*disk.Name, diskName)) || - (disk.Vhd != nil && disk.Vhd.URI != nil && diskURI != "" && strings.EqualFold(*disk.Vhd.URI, diskURI)) || - (disk.ManagedDisk != nil && diskURI != "" && strings.EqualFold(*disk.ManagedDisk.ID, diskURI)) { + (disk.Vhd != nil && disk.Vhd.URI != nil && diSKURI != "" && strings.EqualFold(*disk.Vhd.URI, diSKURI)) || + (disk.ManagedDisk != nil && diSKURI != "" && strings.EqualFold(*disk.ManagedDisk.ID, diSKURI)) { // found the disk - klog.V(2).Infof("azureDisk - detach disk: name %s uri %s", diskName, diskURI) + klog.V(2).Infof("azureDisk - detach disk: name %s uri %s", diskName, diSKURI) disks[i].ToBeDetached = ptr.To(true) if forceDetach { - disks[i].DetachOption = compute.ForceDetach + disks[i].DetachOption = to.Ptr(armcompute.DiskDetachOptionTypesForceDetach) } bFoundDisk = true } @@ -163,7 +171,7 @@ func (fs *FlexScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, } else { if strings.EqualFold(fs.Environment.Name, consts.AzureStackCloudName) && !fs.Config.DisableAzureStackCloud { // Azure stack does not support ToBeDetached flag, use original way to detach disk - newDisks := []compute.DataDisk{} + newDisks := []*armcompute.DataDisk{} for _, disk := range disks { if !ptr.Deref(disk.ToBeDetached, false) { newDisks = append(newDisks, disk) @@ -173,22 +181,21 @@ func (fs *FlexScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, } } - newVM := compute.VirtualMachineUpdate{ - VirtualMachineProperties: &compute.VirtualMachineProperties{ - StorageProfile: &compute.StorageProfile{ - DataDisks: &disks, + newVM := armcompute.VirtualMachine{ + Properties: &armcompute.VirtualMachineProperties{ + StorageProfile: &armcompute.StorageProfile{ + DataDisks: disks, }, }, } - var result *compute.VirtualMachine - var rerr *retry.Error + var result *armcompute.VirtualMachine defer func() { _ = fs.DeleteCacheForNode(ctx, vmName) // update the cache with the updated result only if its not nil - // and contains the VirtualMachineProperties - if rerr == nil && result != nil && result.VirtualMachineProperties != nil { + // and contains the.Properties + if err == nil && result != nil && result.Properties != nil { if err := fs.updateCache(ctx, vmName, result); err != nil { klog.Errorf("updateCache(%s) failed with error: %v", vmName, err) } @@ -197,39 +204,27 @@ func (fs *FlexScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, klog.V(2).Infof("azureDisk - update(%s): vm(%s) node(%s)- detach disk list(%s)", nodeResourceGroup, vmName, nodeName, diskMap) - result, rerr = fs.VirtualMachinesClient.Update(ctx, nodeResourceGroup, *vm.Name, newVM, "detach_disk") - if rerr != nil { - klog.Errorf("azureDisk - detach disk list(%s) on rg(%s) vm(%s) failed, err: %v", diskMap, nodeResourceGroup, vmName, rerr) - if rerr.HTTPStatusCode == http.StatusNotFound { - klog.Errorf("azureDisk - begin to filterNonExistingDisks(%v) on rg(%s) vm(%s)", diskMap, nodeResourceGroup, vmName) - disks := FilterNonExistingDisks(ctx, fs.DisksClient, *vm.StorageProfile.DataDisks) - newVM.VirtualMachineProperties.StorageProfile.DataDisks = &disks - result, rerr = fs.VirtualMachinesClient.Update(ctx, nodeResourceGroup, *vm.Name, newVM, "detach_disk") + result, err = fs.ComputeClientFactory.GetVirtualMachineClient().CreateOrUpdate(ctx, nodeResourceGroup, *vm.Name, newVM) + if err != nil { + klog.Errorf("azureDisk - detach disk list(%s) on rg(%s) vm(%s) failed, err: %v", diskMap, nodeResourceGroup, vmName, err) + var rerr *azcore.ResponseError + if errors.As(err, &rerr) { + if rerr.StatusCode == http.StatusNotFound { + klog.Errorf("azureDisk - begin to filterNonExistingDisks(%v) on rg(%s) vm(%s)", diskMap, nodeResourceGroup, vmName) + disks := FilterNonExistingDisks(ctx, fs.ComputeClientFactory, vm.Properties.StorageProfile.DataDisks) + newVM.Properties.StorageProfile.DataDisks = disks + result, err = fs.ComputeClientFactory.GetVirtualMachineClient().CreateOrUpdate(ctx, nodeResourceGroup, *vm.Name, newVM) + } } } - klog.V(2).Infof("azureDisk - update(%s): vm(%s) - detach disk list(%s) returned with %v", nodeResourceGroup, vmName, diskMap, rerr) - if rerr != nil { - return rerr.Error() - } - return nil -} - -// WaitForUpdateResult waits for the response of the update request -func (fs *FlexScaleSet) WaitForUpdateResult(ctx context.Context, future *azure.Future, nodeName types.NodeName, source string) error { - vmName := mapNodeNameToVMName(nodeName) - nodeResourceGroup, err := fs.GetNodeResourceGroup(vmName) + klog.V(2).Infof("azureDisk - update(%s): vm(%s) - detach disk list(%s) returned with %v", nodeResourceGroup, vmName, diskMap, err) if err != nil { return err } - result, rerr := fs.VirtualMachinesClient.WaitForUpdateResult(ctx, future, nodeResourceGroup, source) - if rerr != nil { - return rerr.Error() - } - // clean node cache first and then update cache _ = fs.DeleteCacheForNode(ctx, vmName) - if result != nil && result.VirtualMachineProperties != nil { + if result != nil && result.Properties != nil { if err := fs.updateCache(ctx, vmName, result); err != nil { klog.Errorf("updateCache(%s) failed with error: %v", vmName, err) } @@ -239,46 +234,37 @@ func (fs *FlexScaleSet) WaitForUpdateResult(ctx context.Context, future *azure.F // UpdateVM updates a vm func (fs *FlexScaleSet) UpdateVM(ctx context.Context, nodeName types.NodeName) error { - future, err := fs.UpdateVMAsync(ctx, nodeName) - if err != nil { - return err - } - return fs.WaitForUpdateResult(ctx, future, nodeName, "update_vm") -} - -// UpdateVMAsync updates a vm asynchronously -func (fs *FlexScaleSet) UpdateVMAsync(ctx context.Context, nodeName types.NodeName) (*azure.Future, error) { vmName := mapNodeNameToVMName(nodeName) vm, err := fs.getVmssFlexVM(ctx, vmName, azcache.CacheReadTypeDefault) if err != nil { // if host doesn't exist, no need to update klog.Warningf("azureDisk - cannot find node %s, skip updating vm", nodeName) - return nil, nil + return nil } nodeResourceGroup, err := fs.GetNodeResourceGroup(vmName) if err != nil { - return nil, err + return err } - future, rerr := fs.VirtualMachinesClient.UpdateAsync(ctx, nodeResourceGroup, *vm.Name, compute.VirtualMachineUpdate{}, "update_vm") + _, rerr := fs.ComputeClientFactory.GetVirtualMachineClient().CreateOrUpdate(ctx, nodeResourceGroup, *vm.Name, armcompute.VirtualMachine{}) if rerr != nil { - return future, rerr.Error() + return rerr } - return future, nil + return nil } -func (fs *FlexScaleSet) updateCache(ctx context.Context, nodeName string, vm *compute.VirtualMachine) error { +func (fs *FlexScaleSet) updateCache(ctx context.Context, nodeName string, vm *armcompute.VirtualMachine) error { if vm == nil { return fmt.Errorf("vm is nil") } if vm.Name == nil { return fmt.Errorf("vm.Name is nil") } - if vm.VirtualMachineProperties == nil { - return fmt.Errorf("vm.VirtualMachineProperties is nil") + if vm.Properties == nil { + return fmt.Errorf("vm.Properties is nil") } - if vm.OsProfile == nil || vm.OsProfile.ComputerName == nil { - return fmt.Errorf("vm.OsProfile.ComputerName is nil") + if vm.Properties.OSProfile == nil || vm.Properties.OSProfile.ComputerName == nil { + return fmt.Errorf("vm.Properties.OSProfile.ComputerName is nil") } vmssFlexID, err := fs.getNodeVmssFlexID(ctx, nodeName) @@ -295,8 +281,8 @@ func (fs *FlexScaleSet) updateCache(ctx context.Context, nodeName string, vm *co vmMap := cached.(*sync.Map) vmMap.Store(nodeName, vm) - fs.vmssFlexVMNameToVmssID.Store(strings.ToLower(*vm.OsProfile.ComputerName), vmssFlexID) - fs.vmssFlexVMNameToNodeName.Store(*vm.Name, strings.ToLower(*vm.OsProfile.ComputerName)) + fs.vmssFlexVMNameToVmssID.Store(strings.ToLower(*vm.Properties.OSProfile.ComputerName), vmssFlexID) + fs.vmssFlexVMNameToNodeName.Store(*vm.Name, strings.ToLower(*vm.Properties.OSProfile.ComputerName)) klog.V(2).Infof("updateCache(%s) for vmssFlexID(%s) successfully", nodeName, vmssFlexID) return nil } @@ -308,12 +294,8 @@ func (fs *FlexScaleSet) GetDataDisks(ctx context.Context, nodeName types.NodeNam return nil, nil, err } - if vm.StorageProfile.DataDisks == nil { + if vm.Properties.StorageProfile.DataDisks == nil { return nil, nil, nil } - result, err := ToArmcomputeDisk(*vm.StorageProfile.DataDisks) - if err != nil { - return nil, nil, err - } - return result, vm.ProvisioningState, nil + return vm.Properties.StorageProfile.DataDisks, vm.Properties.ProvisioningState, nil } diff --git a/pkg/provider/azure_controller_vmssflex_test.go b/pkg/provider/azure_controller_vmssflex_test.go index afd57f54b9..7504555a10 100644 --- a/pkg/provider/azure_controller_vmssflex_test.go +++ b/pkg/provider/azure_controller_vmssflex_test.go @@ -22,10 +22,8 @@ import ( "net/http" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/azure" - autorestmocks "github.com/Azure/go-autorest/autorest/mocks" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -34,10 +32,9 @@ import ( cloudprovider "k8s.io/cloud-provider" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/mock_virtualmachinescalesetclient" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) func TestAttachDiskWithVmssFlex(t *testing.T) { @@ -51,10 +48,10 @@ func TestAttachDiskWithVmssFlex(t *testing.T) { nodeName types.NodeName vmName string inconsistentLUN bool - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error - vmssFlexVMUpdateError *retry.Error + vmssFlexVMUpdateError error expectedErr error }{ { @@ -70,8 +67,8 @@ func TestAttachDiskWithVmssFlex(t *testing.T) { { description: "AttachDisk should should throw InstanceNotFound error if the VM cannot be found", nodeName: types.NodeName(nonExistingNodeName), - testVMListWithoutInstanceView: []compute.VirtualMachine{}, - testVMListWithOnlyInstanceView: []compute.VirtualMachine{}, + testVMListWithoutInstanceView: []*armcompute.VirtualMachine{}, + testVMListWithOnlyInstanceView: []*armcompute.VirtualMachine{}, vmListErr: nil, vmssFlexVMUpdateError: nil, expectedErr: cloudprovider.InstanceNotFound, @@ -83,8 +80,8 @@ func TestAttachDiskWithVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - vmssFlexVMUpdateError: &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 404, RawError: instance not found"), + vmssFlexVMUpdateError: &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}, + expectedErr: fmt.Errorf("instance not found"), }, { description: "error should be returned when disk lun is inconsistent", @@ -103,19 +100,18 @@ func TestAttachDiskWithVmssFlex(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().UpdateAsync(gomock.Any(), gomock.Any(), tc.vmName, gomock.Any(), gomock.Any()).Return(nil, tc.vmssFlexVMUpdateError).AnyTimes() - mockVMClient.EXPECT().WaitForUpdateResult(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, tc.vmssFlexVMUpdateError).AnyTimes() + mockVMClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), tc.vmName, gomock.Any()).Return(nil, tc.vmssFlexVMUpdateError).AnyTimes() options := AttachDiskOptions{ Lun: 1, DiskName: "diskname", - CachingMode: compute.CachingTypesReadOnly, + CachingMode: armcompute.CachingTypesReadOnly, DiskEncryptionSetID: "", WriteAcceleratorEnabled: false, } @@ -130,7 +126,7 @@ func TestAttachDiskWithVmssFlex(t *testing.T) { if tc.expectedErr == nil { assert.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr.Error(), tc.description) + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) } } } @@ -145,11 +141,11 @@ func TestDettachDiskWithVmssFlex(t *testing.T) { description string nodeName types.NodeName vmName string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine forceDetach bool vmListErr error - vmssFlexVMUpdateError *retry.Error + vmssFlexVMUpdateError error diskMap map[string]string expectedErr error }{ @@ -161,7 +157,7 @@ func TestDettachDiskWithVmssFlex(t *testing.T) { testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, vmssFlexVMUpdateError: nil, - diskMap: map[string]string{"diskUri1": "dataDisktestvm1"}, + diskMap: map[string]string{"diSKUri1": "dataDisktestvm1"}, expectedErr: nil, }, { @@ -173,17 +169,17 @@ func TestDettachDiskWithVmssFlex(t *testing.T) { forceDetach: true, vmListErr: nil, vmssFlexVMUpdateError: nil, - diskMap: map[string]string{"diskUri1": "dataDisktestvm1"}, + diskMap: map[string]string{"diSKUri1": "dataDisktestvm1"}, expectedErr: nil, }, { description: "AttachDisk should should do nothing if the VM cannot be found", nodeName: types.NodeName(nonExistingNodeName), - testVMListWithoutInstanceView: []compute.VirtualMachine{}, - testVMListWithOnlyInstanceView: []compute.VirtualMachine{}, + testVMListWithoutInstanceView: []*armcompute.VirtualMachine{}, + testVMListWithOnlyInstanceView: []*armcompute.VirtualMachine{}, vmListErr: nil, vmssFlexVMUpdateError: nil, - diskMap: map[string]string{"diskUri1": "dataDisktestvm1"}, + diskMap: map[string]string{"diSKUri1": "dataDisktestvm1"}, expectedErr: nil, }, { @@ -194,7 +190,7 @@ func TestDettachDiskWithVmssFlex(t *testing.T) { testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, vmssFlexVMUpdateError: nil, - diskMap: map[string]string{"diskUri1": "dataDisktestvm3"}, + diskMap: map[string]string{"diSKUri1": "dataDisktestvm3"}, expectedErr: nil, }, { @@ -204,9 +200,9 @@ func TestDettachDiskWithVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - vmssFlexVMUpdateError: &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}, - diskMap: map[string]string{"diskUri1": "dataDisktestvm1"}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 404, RawError: instance not found"), + vmssFlexVMUpdateError: &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}, + diskMap: map[string]string{"diSKUri1": "dataDisktestvm1"}, + expectedErr: fmt.Errorf("instance not found"), }, } @@ -214,20 +210,20 @@ func TestDettachDiskWithVmssFlex(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().Update(gomock.Any(), gomock.Any(), tc.vmName, gomock.Any(), "detach_disk").Return(nil, tc.vmssFlexVMUpdateError).AnyTimes() + mockVMClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), tc.vmName, gomock.Any()).Return(nil, tc.vmssFlexVMUpdateError).AnyTimes() err = fs.DetachDisk(ctx, tc.nodeName, tc.diskMap, tc.forceDetach) if tc.expectedErr == nil { assert.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr.Error(), tc.description) + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) } } @@ -244,10 +240,10 @@ func TestUpdateVMWithVmssFlex(t *testing.T) { description string nodeName types.NodeName vmName string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error - vmssFlexVMUpdateError *retry.Error + vmssFlexVMUpdateError error expectedErr error }{ { @@ -267,8 +263,8 @@ func TestUpdateVMWithVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - vmssFlexVMUpdateError: &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 404, RawError: instance not found"), + vmssFlexVMUpdateError: &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}, + expectedErr: fmt.Errorf("instance not found"), }, } @@ -276,28 +272,22 @@ func TestUpdateVMWithVmssFlex(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() - r := autorestmocks.NewResponseWithStatus("200", 200) - r.Request.Method = http.MethodPut - - future, err := azure.NewFutureFromResponse(r) - - mockVMClient.EXPECT().UpdateAsync(gomock.Any(), gomock.Any(), tc.vmName, gomock.Any(), "update_vm").Return(&future, err).AnyTimes() - mockVMClient.EXPECT().WaitForUpdateResult(gomock.Any(), &future, gomock.Any(), gomock.Any()).Return(nil, tc.vmssFlexVMUpdateError).AnyTimes() - mockVMClient.EXPECT().Update(gomock.Any(), gomock.Any(), tc.vmName, gomock.Any(), "update_vm").Return(nil, tc.vmssFlexVMUpdateError).AnyTimes() + mockVMClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), tc.vmName, gomock.Any()).Return(nil, tc.vmssFlexVMUpdateError).AnyTimes() + mockVMClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), tc.vmName, gomock.Any()).Return(nil, tc.vmssFlexVMUpdateError).AnyTimes() err = fs.UpdateVM(ctx, tc.nodeName) if tc.expectedErr == nil { assert.NoError(t, err) } else { - assert.EqualError(t, err, tc.expectedErr.Error(), tc.description) + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) } } @@ -310,8 +300,8 @@ func TestGetDataDisksWithVmssFlex(t *testing.T) { testCases := []struct { description string nodeName types.NodeName - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error expectedDataDisks []*armcompute.DataDisk expectedErr error @@ -334,8 +324,8 @@ func TestGetDataDisksWithVmssFlex(t *testing.T) { { description: "GetDataDisks should should throw InstanceNotFound error if the VM cannot be found", nodeName: types.NodeName(nonExistingNodeName), - testVMListWithoutInstanceView: []compute.VirtualMachine{}, - testVMListWithOnlyInstanceView: []compute.VirtualMachine{}, + testVMListWithoutInstanceView: []*armcompute.VirtualMachine{}, + testVMListWithOnlyInstanceView: []*armcompute.VirtualMachine{}, vmListErr: nil, expectedDataDisks: nil, expectedErr: cloudprovider.InstanceNotFound, @@ -346,17 +336,17 @@ func TestGetDataDisksWithVmssFlex(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() dataDisks, _, err := fs.GetDataDisks(context.TODO(), tc.nodeName, azcache.CacheReadTypeDefault) - assert.Equal(t, tc.expectedDataDisks, dataDisks) + assert.Equal(t, len(tc.expectedDataDisks), len(dataDisks)) if tc.expectedErr != nil { - assert.EqualError(t, err, tc.expectedErr.Error(), tc.description) + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) } } } @@ -371,7 +361,7 @@ func TestVMSSFlexUpdateCache(t *testing.T) { testCases := []struct { description string nodeName string - vm *compute.VirtualMachine + vm *armcompute.VirtualMachine expectedErr error }{ { @@ -380,30 +370,30 @@ func TestVMSSFlexUpdateCache(t *testing.T) { expectedErr: fmt.Errorf("vm is nil"), }, { - description: "vm.VirtualMachineProperties is nil", + description: "vm.Properties is nil", nodeName: "vmssflex1000001", - vm: &compute.VirtualMachine{Name: ptr.To("vmssflex1000001")}, - expectedErr: fmt.Errorf("vm.VirtualMachineProperties is nil"), + vm: &armcompute.VirtualMachine{Name: ptr.To("vmssflex1000001")}, + expectedErr: fmt.Errorf("vm.Properties is nil"), }, { - description: "vm.OsProfile.ComputerName is nil", + description: "vm.Properties.OSProfile.ComputerName is nil", nodeName: "vmssflex1000001", - vm: &compute.VirtualMachine{ - Name: ptr.To("vmssflex1000001"), - VirtualMachineProperties: &compute.VirtualMachineProperties{}, + vm: &armcompute.VirtualMachine{ + Name: ptr.To("vmssflex1000001"), + Properties: &armcompute.VirtualMachineProperties{}, }, - expectedErr: fmt.Errorf("vm.OsProfile.ComputerName is nil"), + expectedErr: fmt.Errorf("vm.Properties.OSProfile.ComputerName is nil"), }, { - description: "vm.OsProfile.ComputerName is nil", + description: "vm.Properties.OSProfile.ComputerName is nil", nodeName: "vmssflex1000001", - vm: &compute.VirtualMachine{ + vm: &armcompute.VirtualMachine{ Name: ptr.To("vmssflex1000001"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ - OsProfile: &compute.OSProfile{}, + Properties: &armcompute.VirtualMachineProperties{ + OSProfile: &armcompute.OSProfile{}, }, }, - expectedErr: fmt.Errorf("vm.OsProfile.ComputerName is nil"), + expectedErr: fmt.Errorf("vm.Properties.OSProfile.ComputerName is nil"), }, } diff --git a/pkg/provider/azure_fakes.go b/pkg/provider/azure_fakes.go index de97d0b9f4..2f6b4cb1ae 100644 --- a/pkg/provider/azure_fakes.go +++ b/pkg/provider/azure_fakes.go @@ -24,26 +24,30 @@ import ( "k8s.io/client-go/tools/record" "sigs.k8s.io/cloud-provider-azure/pkg/azclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/availabilitysetclient/mock_availabilitysetclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/backendaddresspoolclient/mock_backendaddresspoolclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/diskclient/mock_diskclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/mock_interfaceclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/loadbalancerclient/mock_loadbalancerclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/mock_azclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/privateendpointclient/mock_privateendpointclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/privatelinkserviceclient/mock_privatelinkserviceclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/privatezoneclient/mock_privatezoneclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipaddressclient/mock_publicipaddressclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/routetableclient/mock_routetableclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/securitygroupclient/mock_securitygroupclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/subnetclient/mock_subnetclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/mock_virtualmachinescalesetclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetvmclient/mock_virtualmachinescalesetvmclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworklinkclient/mock_virtualnetworklinkclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/diskclient/mockdiskclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient/mockloadbalancerclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/subnetclient/mocksubnetclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssvmclient/mockvmssvmclient" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" "sigs.k8s.io/cloud-provider-azure/pkg/provider/privatelinkservice" "sigs.k8s.io/cloud-provider-azure/pkg/provider/routetable" "sigs.k8s.io/cloud-provider-azure/pkg/provider/securitygroup" "sigs.k8s.io/cloud-provider-azure/pkg/provider/subnet" + "sigs.k8s.io/cloud-provider-azure/pkg/provider/zone" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) @@ -108,17 +112,31 @@ func GetTestCloud(ctrl *gomock.Controller) (az *Cloud) { routeCIDRs: map[string]string{}, eventRecorder: &record.FakeRecorder{}, } - az.DisksClient = mockdiskclient.NewMockInterface(ctrl) - az.InterfacesClient = mockinterfaceclient.NewMockInterface(ctrl) - az.LoadBalancerClient = mockloadbalancerclient.NewMockInterface(ctrl) - az.PublicIPAddressesClient = mockpublicipclient.NewMockInterface(ctrl) - az.SubnetsClient = mocksubnetclient.NewMockInterface(ctrl) - az.VirtualMachineScaleSetsClient = mockvmssclient.NewMockInterface(ctrl) - az.VirtualMachineScaleSetVMsClient = mockvmssvmclient.NewMockInterface(ctrl) - az.VirtualMachinesClient = mockvmclient.NewMockInterface(ctrl) clientFactory := mock_azclient.NewMockClientFactory(ctrl) az.ComputeClientFactory = clientFactory az.NetworkClientFactory = clientFactory + disksClient := mock_diskclient.NewMockInterface(ctrl) + clientFactory.EXPECT().GetDiskClient().Return(disksClient).AnyTimes() + interfacesClient := mock_interfaceclient.NewMockInterface(ctrl) + clientFactory.EXPECT().GetInterfaceClient().Return(interfacesClient).AnyTimes() + loadBalancerClient := mock_loadbalancerclient.NewMockInterface(ctrl) + clientFactory.EXPECT().GetLoadBalancerClient().Return(loadBalancerClient).AnyTimes() + publicIPAddressesClient := mock_publicipaddressclient.NewMockInterface(ctrl) + clientFactory.EXPECT().GetPublicIPAddressClient().Return(publicIPAddressesClient).AnyTimes() + subnetsClient := mock_subnetclient.NewMockInterface(ctrl) + clientFactory.EXPECT().GetSubnetClient().Return(subnetsClient).AnyTimes() + bpClient := mock_backendaddresspoolclient.NewMockInterface(ctrl) + clientFactory.EXPECT().GetBackendAddressPoolClient().Return(bpClient).AnyTimes() + vmasClient := mock_availabilitysetclient.NewMockInterface(ctrl) + clientFactory.EXPECT().GetAvailabilitySetClient().Return(vmasClient).AnyTimes() + virtualMachineScaleSetsClient := mock_virtualmachinescalesetclient.NewMockInterface(ctrl) + clientFactory.EXPECT().GetVirtualMachineScaleSetClient().Return(virtualMachineScaleSetsClient).AnyTimes() + virtualMachineScaleSetVMsClient := mock_virtualmachinescalesetvmclient.NewMockInterface(ctrl) + clientFactory.EXPECT().GetVirtualMachineScaleSetVMClient().Return(virtualMachineScaleSetVMsClient).AnyTimes() + + virtualMachinesClient := mock_virtualmachineclient.NewMockInterface(ctrl) + clientFactory.EXPECT().GetVirtualMachineClient().Return(virtualMachinesClient).AnyTimes() + securtyGrouptrack2Client := mock_securitygroupclient.NewMockInterface(ctrl) clientFactory.EXPECT().GetSecurityGroupClient().Return(securtyGrouptrack2Client).AnyTimes() mockPrivateDNSClient := mock_privatezoneclient.NewMockInterface(ctrl) @@ -127,6 +145,10 @@ func GetTestCloud(ctrl *gomock.Controller) (az *Cloud) { clientFactory.EXPECT().GetVirtualNetworkLinkClient().Return(virtualNetworkLinkClient).AnyTimes() subnetTrack2Client := mock_subnetclient.NewMockInterface(ctrl) clientFactory.EXPECT().GetSubnetClient().Return(subnetTrack2Client).AnyTimes() + privatelinkserviceClient := mock_privatelinkserviceclient.NewMockInterface(ctrl) + clientFactory.EXPECT().GetPrivateLinkServiceClient().Return(privatelinkserviceClient).AnyTimes() + routetableClient := mock_routetableclient.NewMockInterface(ctrl) + clientFactory.EXPECT().GetRouteTableClient().Return(routetableClient).AnyTimes() privateendpointTrack2Client := mock_privateendpointclient.NewMockInterface(ctrl) clientFactory.EXPECT().GetPrivateEndpointClient().Return(privateendpointTrack2Client).AnyTimes() az.AuthProvider = &azclient.AuthProvider{ @@ -142,6 +164,7 @@ func GetTestCloud(ctrl *gomock.Controller) (az *Cloud) { az.plsRepo = privatelinkservice.NewMockRepository(ctrl) az.routeTableRepo = routetable.NewMockRepository(ctrl) + az.zoneRepo = zone.NewMockRepository(ctrl) az.regionZonesMap = map[string][]string{az.Location: {"1", "2", "3"}} { diff --git a/pkg/provider/azure_instance_metadata.go b/pkg/provider/azure_instance_metadata.go index ed3c22c010..2f13181d01 100644 --- a/pkg/provider/azure_instance_metadata.go +++ b/pkg/provider/azure_instance_metadata.go @@ -33,7 +33,7 @@ import ( // NetworkMetadata contains metadata about an instance's network type NetworkMetadata struct { - Interface []NetworkInterface `json:"interface"` + Interface []*NetworkInterface `json:"interface"` } // NetworkInterface represents an instances network interface. @@ -43,7 +43,7 @@ type NetworkInterface struct { MAC string `json:"macAddress"` } -// NetworkData contains IP information for a network. +// NetworkData contains IP information for a armnetwork. type NetworkData struct { IPAddress []IPAddress `json:"ipAddress"` Subnet []Subnet `json:"subnet"` @@ -64,7 +64,7 @@ type Subnet struct { // ComputeMetadata represents compute information type ComputeMetadata struct { Environment string `json:"azEnvironment,omitempty"` - SKU string `json:"sku,omitempty"` + SKU string `json:"SKU,omitempty"` Name string `json:"name,omitempty"` Zone string `json:"zone,omitempty"` VMSize string `json:"vmSize,omitempty"` @@ -172,7 +172,7 @@ func (ims *InstanceMetadataService) getMetadata(_ context.Context, key string) ( } publicIPs := loadBalancerMetadata.LoadBalancer.PublicIPAddresses - fillNetInterfacePublicIPs(publicIPs, &netInterface) + fillNetInterfacePublicIPs(publicIPs, netInterface) } return instanceMetadata, nil diff --git a/pkg/provider/azure_instances_test.go b/pkg/provider/azure_instances_test.go index ec2abe0978..9afb3640a9 100644 --- a/pkg/provider/azure_instances_test.go +++ b/pkg/provider/azure_instances_test.go @@ -26,8 +26,12 @@ import ( "k8s.io/apimachinery/pkg/util/wait" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -38,30 +42,29 @@ import ( cloudprovider "k8s.io/cloud-provider" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssvmclient/mockvmssvmclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/mock_interfaceclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipaddressclient/mock_publicipaddressclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/mock_virtualmachinescalesetclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetvmclient/mock_virtualmachinescalesetvmclient" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) // setTestVirtualMachines sets test virtual machine with powerstate. -func setTestVirtualMachines(c *Cloud, vmList map[string]string, isDataDisksFull bool) []compute.VirtualMachine { - expectedVMs := make([]compute.VirtualMachine, 0) +func setTestVirtualMachines(c *Cloud, vmList map[string]string, isDataDisksFull bool) []*armcompute.VirtualMachine { + expectedVMs := make([]*armcompute.VirtualMachine, 0) for nodeName, powerState := range vmList { nodeName := nodeName instanceID := fmt.Sprintf("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/%s", nodeName) - vm := compute.VirtualMachine{ + vm := &armcompute.VirtualMachine{ Name: &nodeName, ID: &instanceID, Location: &c.Location, } - status := []compute.InstanceViewStatus{ + status := []*armcompute.InstanceViewStatus{ { Code: ptr.To(powerState), }, @@ -69,20 +72,20 @@ func setTestVirtualMachines(c *Cloud, vmList map[string]string, isDataDisksFull Code: ptr.To("ProvisioningState/succeeded"), }, } - vm.VirtualMachineProperties = &compute.VirtualMachineProperties{ + vm.Properties = &armcompute.VirtualMachineProperties{ ProvisioningState: ptr.To(string(consts.ProvisioningStateSucceeded)), - HardwareProfile: &compute.HardwareProfile{ - VMSize: compute.StandardA0, + HardwareProfile: &armcompute.HardwareProfile{ + VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardA0), }, - InstanceView: &compute.VirtualMachineInstanceView{ - Statuses: &status, + InstanceView: &armcompute.VirtualMachineInstanceView{ + Statuses: status, }, - StorageProfile: &compute.StorageProfile{ - DataDisks: &[]compute.DataDisk{}, + StorageProfile: &armcompute.StorageProfile{ + DataDisks: []*armcompute.DataDisk{}, }, } if !isDataDisksFull { - vm.StorageProfile.DataDisks = &[]compute.DataDisk{ + vm.Properties.StorageProfile.DataDisks = []*armcompute.DataDisk{ { Lun: ptr.To(int32(0)), Name: ptr.To("disk1"), @@ -97,11 +100,11 @@ func setTestVirtualMachines(c *Cloud, vmList map[string]string, isDataDisksFull }, } } else { - dataDisks := make([]compute.DataDisk, maxLUN) + dataDisks := make([]*armcompute.DataDisk, maxLUN) for i := 0; i < maxLUN; i++ { - dataDisks[i] = compute.DataDisk{Lun: ptr.To(int32(i))} + dataDisks[i] = &armcompute.DataDisk{Lun: ptr.To(int32(i))} } - vm.StorageProfile.DataDisks = &dataDisks + vm.Properties.StorageProfile.DataDisks = dataDisks } expectedVMs = append(expectedVMs, vm) @@ -259,12 +262,12 @@ func TestInstanceID(t *testing.T) { vmListWithPowerState[vm] = "" } expectedVMs := setTestVirtualMachines(cloud, vmListWithPowerState, false) - mockVMsClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMsClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) for _, vm := range expectedVMs { mockVMsClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, *vm.Name, gomock.Any()).Return(vm, nil).AnyTimes() } - mockVMsClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm3", gomock.Any()).Return(compute.VirtualMachine{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() - mockVMsClient.EXPECT().Update(gomock.Any(), cloud.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + mockVMsClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm3", gomock.Any()).Return(&armcompute.VirtualMachine{}, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() + mockVMsClient.EXPECT().CreateOrUpdate(gomock.Any(), cloud.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() instanceID, err := cloud.InstanceID(context.Background(), types.NodeName(test.nodeName)) assert.Equal(t, test.expectedErrMsg, err, test.name) @@ -366,13 +369,13 @@ func TestInstanceShutdownByProviderID(t *testing.T) { cloud := GetTestCloud(ctrl) expectedVMs := setTestVirtualMachines(cloud, test.vmList, false) if test.provisioningState != "" { - expectedVMs[0].ProvisioningState = ptr.To(test.provisioningState) + expectedVMs[0].Properties.ProvisioningState = ptr.To(test.provisioningState) } - mockVMsClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMsClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) for _, vm := range expectedVMs { mockVMsClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, *vm.Name, gomock.Any()).Return(vm, nil).AnyTimes() } - mockVMsClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, test.nodeName, gomock.Any()).Return(compute.VirtualMachine{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockVMsClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, test.nodeName, gomock.Any()).Return(&armcompute.VirtualMachine{}, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() hasShutdown, err := cloud.InstanceShutdownByProviderID(context.Background(), test.providerID) assert.Equal(t, test.expectedErrMsg, err, test.name) @@ -394,12 +397,12 @@ func TestNodeAddresses(t *testing.T) { defer ctrl.Finish() cloud := GetTestCloud(ctrl) - expectedVM := compute.VirtualMachine{ - VirtualMachineProperties: &compute.VirtualMachineProperties{ - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &[]compute.NetworkInterfaceReference{ + expectedVM := &armcompute.VirtualMachine{ + Properties: &armcompute.VirtualMachineProperties{ + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: []*armcompute.NetworkInterfaceReference{ { - NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ + Properties: &armcompute.NetworkInterfaceReferenceProperties{ Primary: ptr.To(true), }, ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"), @@ -409,21 +412,21 @@ func TestNodeAddresses(t *testing.T) { }, } - expectedPIP := network.PublicIPAddress{ + expectedPIP := &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), ID: ptr.To("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("192.168.1.12"), }, } - expectedInterface := network.Interface{ - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - IPConfigurations: &[]network.InterfaceIPConfiguration{ + expectedInterface := &armnetwork.Interface{ + Properties: &armnetwork.InterfacePropertiesFormat{ + IPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ PrivateIPAddress: ptr.To("172.1.0.3"), - PublicIPAddress: &expectedPIP, + PublicIPAddress: expectedPIP, }, }, }, @@ -457,7 +460,7 @@ func TestNodeAddresses(t *testing.T) { ipV6 string ipV4Public string ipV6Public string - loadBalancerSku string + loadBalancerSKU string expectedAddress []v1.NodeAddress useInstanceMetadata bool useCustomImsCache bool @@ -477,7 +480,7 @@ func TestNodeAddresses(t *testing.T) { expectedErrMsg: fmt.Errorf("failure of getting instance metadata"), }, { - name: "NodeAddresses should report error if metadata.Network.Interface is nil", + name: "NodeAddresses should report error if metadata.armnetwork.Interface is nil", nodeName: "vm1", metadataName: "vm1", vmType: consts.VMTypeStandard, @@ -540,7 +543,7 @@ func TestNodeAddresses(t *testing.T) { ipV4Public: "192.168.1.12", ipV6: "1111:11111:00:00:1111:1111:000:111", ipV6Public: "2222:22221:00:00:2222:2222:000:111", - loadBalancerSku: "basic", + loadBalancerSKU: "basic", useInstanceMetadata: true, expectedAddress: []v1.NodeAddress{ { @@ -574,7 +577,7 @@ func TestNodeAddresses(t *testing.T) { ipV4Public: "192.168.1.12", ipV6: "1111:11111:00:00:1111:1111:000:111", ipV6Public: "2222:22221:00:00:2222:2222:000:111", - loadBalancerSku: "standard", + loadBalancerSKU: "standard", useInstanceMetadata: true, expectedAddress: []v1.NodeAddress{ { @@ -624,7 +627,7 @@ func TestNodeAddresses(t *testing.T) { if test.metadataTemplate != "" { fmt.Fprint(w, test.metadataTemplate) } else { - if test.loadBalancerSku == "standard" { + if test.loadBalancerSKU == "standard" { fmt.Fprintf(w, metadataTemplate, test.metadataName, test.ipV4, "", test.ipV6, "") } else { fmt.Fprintf(w, metadataTemplate, test.metadataName, test.ipV4, test.ipV4Public, test.ipV6, test.ipV6Public) @@ -649,14 +652,14 @@ func TestNodeAddresses(t *testing.T) { t.Errorf("Test [%s] unexpected error: %v", test.name, err) } } - mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm1", gomock.Any()).Return(expectedVM, nil).AnyTimes() - mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm2", gomock.Any()).Return(compute.VirtualMachine{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm2", gomock.Any()).Return(&armcompute.VirtualMachine{}, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() - mockPublicIPAddressesClient := cloud.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) - mockPublicIPAddressesClient.EXPECT().List(gomock.Any(), cloud.ResourceGroup).Return([]network.PublicIPAddress{expectedPIP}, nil).AnyTimes() + pipClient := cloud.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + pipClient.EXPECT().List(gomock.Any(), cloud.ResourceGroup).Return([]*armnetwork.PublicIPAddress{expectedPIP}, nil).AnyTimes() - mockInterfaceClient := cloud.InterfacesClient.(*mockinterfaceclient.MockInterface) + mockInterfaceClient := cloud.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) mockInterfaceClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "nic", gomock.Any()).Return(expectedInterface, nil).AnyTimes() ipAddresses, err := cloud.NodeAddresses(context.Background(), types.NodeName(test.nodeName)) @@ -716,12 +719,12 @@ func TestInstanceExistsByProviderID(t *testing.T) { vmListWithPowerState[vm] = "" } expectedVMs := setTestVirtualMachines(cloud, vmListWithPowerState, false) - mockVMsClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMsClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) for _, vm := range expectedVMs { mockVMsClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, *vm.Name, gomock.Any()).Return(vm, nil).AnyTimes() } - mockVMsClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm3", gomock.Any()).Return(compute.VirtualMachine{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() - mockVMsClient.EXPECT().Update(gomock.Any(), cloud.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + mockVMsClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm3", gomock.Any()).Return(&armcompute.VirtualMachine{}, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() + mockVMsClient.EXPECT().CreateOrUpdate(gomock.Any(), cloud.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() exist, err := cloud.InstanceExistsByProviderID(context.Background(), test.providerID) assert.Equal(t, test.expectedErrMsg, err, test.name) @@ -734,7 +737,7 @@ func TestInstanceExistsByProviderID(t *testing.T) { scaleSet string vmList []string expected bool - rerr *retry.Error + rerr error }{ { name: "InstanceExistsByProviderID should return true if VMSS and VM exist", @@ -752,7 +755,7 @@ func TestInstanceExistsByProviderID(t *testing.T) { { name: "InstanceExistsByProviderID should return false if VMSS doesn't exist", providerID: "azure:///subscriptions/script/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/missing-vmss/virtualMachines/0", - rerr: &retry.Error{HTTPStatusCode: 404}, + rerr: &azcore.ResponseError{StatusCode: 404}, expected: false, }, } @@ -762,19 +765,17 @@ func TestInstanceExistsByProviderID(t *testing.T) { assert.NoError(t, err, test.name) cloud.VMSet = ss - mockVMSSClient := mockvmssclient.NewMockInterface(ctrl) - mockVMSSVMClient := mockvmssvmclient.NewMockInterface(ctrl) - ss.VirtualMachineScaleSetsClient = mockVMSSClient - ss.VirtualMachineScaleSetVMsClient = mockVMSSVMClient + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) expectedScaleSet := buildTestVMSS(test.scaleSet, test.scaleSet) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{expectedScaleSet}, test.rerr).AnyTimes() + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachineScaleSet{expectedScaleSet}, test.rerr).AnyTimes() expectedVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, test.scaleSet, "", 0, test.vmList, "succeeded", false) - mockVMSSVMClient.EXPECT().List(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, test.rerr).AnyTimes() + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, test.rerr).AnyTimes() - mockVMsClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachine{}, nil).AnyTimes() + mockVMsClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() exist, _ := cloud.InstanceExistsByProviderID(context.Background(), test.providerID) assert.Equal(t, test.expected, exist, test.name) @@ -898,32 +899,32 @@ func TestInstanceMetadata(t *testing.T) { t.Run("instance exists", func(t *testing.T) { cloud := GetTestCloud(ctrl) expectedVM := buildDefaultTestVirtualMachine("as", []string{"/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1"}) - expectedVM.HardwareProfile = &compute.HardwareProfile{ - VMSize: compute.BasicA0, + expectedVM.Properties.HardwareProfile = &armcompute.HardwareProfile{ + VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesBasicA0), } expectedVM.Location = ptr.To("westus2") - expectedVM.Zones = &[]string{"1"} + expectedVM.Zones = to.SliceOfPtrs("1") expectedVM.ID = ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/VirtualMachines/vm") - mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm", gomock.Any()).Return(expectedVM, nil) expectedNIC := buildDefaultTestInterface(true, []string{}) - (*expectedNIC.IPConfigurations)[0].PrivateIPAddress = ptr.To("1.2.3.4") - (*expectedNIC.IPConfigurations)[0].PublicIPAddress = &network.PublicIPAddress{ + (expectedNIC.Properties.IPConfigurations)[0].Properties.PrivateIPAddress = ptr.To("1.2.3.4") + (expectedNIC.Properties.IPConfigurations)[0].Properties.PublicIPAddress = &armnetwork.PublicIPAddress{ ID: ptr.To("pip"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("5.6.7.8"), }, } - mockNICClient := cloud.InterfacesClient.(*mockinterfaceclient.MockInterface) + mockNICClient := cloud.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) mockNICClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "k8s-agentpool1-00000000-nic-1", gomock.Any()).Return(expectedNIC, nil) - expectedPIP := network.PublicIPAddress{ + expectedPIP := &armnetwork.PublicIPAddress{ Name: ptr.To("pip"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("5.6.7.8"), }, } - mockPIPClient := cloud.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) - mockPIPClient.EXPECT().List(gomock.Any(), cloud.ResourceGroup).Return([]network.PublicIPAddress{expectedPIP}, nil) + mockPIPClient := cloud.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + mockPIPClient.EXPECT().List(gomock.Any(), cloud.ResourceGroup).Return([]*armnetwork.PublicIPAddress{expectedPIP}, nil) expectedMetadata := cloudprovider.InstanceMetadata{ ProviderID: "azure:///subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/VirtualMachines/vm", diff --git a/pkg/provider/azure_instances_v1.go b/pkg/provider/azure_instances_v1.go index 3eaf2756ed..bba63cd855 100644 --- a/pkg/provider/azure_instances_v1.go +++ b/pkg/provider/azure_instances_v1.go @@ -107,7 +107,7 @@ func (az *Cloud) NodeAddresses(ctx context.Context, name types.NodeName) ([]v1.N return az.addressGetter(ctx, name) } -func (az *Cloud) getLocalInstanceNodeAddresses(netInterfaces []NetworkInterface, nodeName string) ([]v1.NodeAddress, error) { +func (az *Cloud) getLocalInstanceNodeAddresses(netInterfaces []*NetworkInterface, nodeName string) ([]v1.NodeAddress, error) { if len(netInterfaces) == 0 { return nil, fmt.Errorf("no interface is found for the instance") } diff --git a/pkg/provider/azure_interface_repo.go b/pkg/provider/azure_interface_repo.go index 3a5f22934d..cc8ebd98cc 100644 --- a/pkg/provider/azure_interface_repo.go +++ b/pkg/provider/azure_interface_repo.go @@ -19,19 +19,19 @@ package provider import ( "context" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" ) -// CreateOrUpdateInterface invokes az.InterfacesClient.CreateOrUpdate with exponential backoff retry -func (az *Cloud) CreateOrUpdateInterface(ctx context.Context, service *v1.Service, nic network.Interface) error { - rerr := az.InterfacesClient.CreateOrUpdate(ctx, az.ResourceGroup, *nic.Name, nic) +// CreateOrUpdateInterface invokes az.NetworkClientFactory.GetInterfaceClient().CreateOrUpdate with exponential backoff retry +func (az *Cloud) CreateOrUpdateInterface(ctx context.Context, service *v1.Service, nic *armnetwork.Interface) error { + _, rerr := az.NetworkClientFactory.GetInterfaceClient().CreateOrUpdate(ctx, az.ResourceGroup, *nic.Name, *nic) klog.V(10).Infof("InterfacesClient.CreateOrUpdate(%s): end", *nic.Name) if rerr != nil { - klog.Errorf("InterfacesClient.CreateOrUpdate(%s) failed: %s", *nic.Name, rerr.Error().Error()) - az.Event(service, v1.EventTypeWarning, "CreateOrUpdateInterface", rerr.Error().Error()) - return rerr.Error() + klog.Errorf("InterfacesClient.CreateOrUpdate(%s) failed: %s", *nic.Name, rerr.Error()) + az.Event(service, v1.EventTypeWarning, "CreateOrUpdateInterface", rerr.Error()) + return rerr } return nil diff --git a/pkg/provider/azure_interface_repo_test.go b/pkg/provider/azure_interface_repo_test.go index 8859ff0e69..6f8f1374c0 100644 --- a/pkg/provider/azure_interface_repo_test.go +++ b/pkg/provider/azure_interface_repo_test.go @@ -18,11 +18,11 @@ package provider import ( "context" - "fmt" "net/http" "testing" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -30,8 +30,7 @@ import ( v1 "k8s.io/api/core/v1" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/mock_interfaceclient" ) func TestCreateOrUpdateInterface(t *testing.T) { @@ -39,9 +38,9 @@ func TestCreateOrUpdateInterface(t *testing.T) { defer ctrl.Finish() az := GetTestCloud(ctrl) - mockInterfaceClient := az.InterfacesClient.(*mockinterfaceclient.MockInterface) - mockInterfaceClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(&retry.Error{HTTPStatusCode: http.StatusInternalServerError}) + mockInterfaceClient := az.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) + mockInterfaceClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(nil, &azcore.ResponseError{StatusCode: http.StatusInternalServerError}) - err := az.CreateOrUpdateInterface(context.TODO(), &v1.Service{}, network.Interface{Name: ptr.To("nic")}) - assert.EqualError(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil)), err.Error()) + err := az.CreateOrUpdateInterface(context.TODO(), &v1.Service{}, &armnetwork.Interface{Name: ptr.To("nic")}) + assert.Contains(t, err.Error(), "UNAVAILABLE") } diff --git a/pkg/provider/azure_loadbalancer.go b/pkg/provider/azure_loadbalancer.go index 88ce01229c..5252522104 100644 --- a/pkg/provider/azure_loadbalancer.go +++ b/pkg/provider/azure_loadbalancer.go @@ -29,8 +29,9 @@ import ( "strings" "unicode" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/samber/lo" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -47,9 +48,9 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/metrics" "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" "sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" "sigs.k8s.io/cloud-provider-azure/pkg/trace" "sigs.k8s.io/cloud-provider-azure/pkg/trace/attributes" + "sigs.k8s.io/cloud-provider-azure/pkg/util/errutils" "sigs.k8s.io/cloud-provider-azure/pkg/util/iputil" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) @@ -102,13 +103,13 @@ func (az *Cloud) GetLoadBalancer(ctx context.Context, clusterName string, servic return nil, az.existsPip(ctx, clusterName, service), err } - _, _, status, _, existsLb, err := az.getServiceLoadBalancer(ctx, service, clusterName, nil, false, &existingLBs) + _, _, status, _, existsLb, err := az.getServiceLoadBalancer(ctx, service, clusterName, nil, false, existingLBs) if err != nil || existsLb { return status, existsLb || az.existsPip(ctx, clusterName, service), err } flippedService := flipServiceInternalAnnotation(service) - _, _, status, _, existsLb, err = az.getServiceLoadBalancer(ctx, flippedService, clusterName, nil, false, &existingLBs) + _, _, status, _, existsLb, err = az.getServiceLoadBalancer(ctx, flippedService, clusterName, nil, false, existingLBs) if err != nil || existsLb { return status, existsLb || az.existsPip(ctx, clusterName, service), err } @@ -464,8 +465,8 @@ func (az *Cloud) EnsureLoadBalancerDeleted(ctx context.Context, clusterName stri } }() - lb, _, _, lbIPsPrimaryPIPs, _, err := az.getServiceLoadBalancer(ctx, service, clusterName, nil, false, &[]network.LoadBalancer{}) - if err != nil && !retry.HasStatusForbiddenOrIgnoredError(err) { + lb, _, _, lbIPsPrimaryPIPs, _, err := az.getServiceLoadBalancer(ctx, service, clusterName, nil, false, []*armnetwork.LoadBalancer{}) + if err != nil && !errutils.HasStatusForbiddenOrIgnoredError(err) { return err } @@ -475,7 +476,7 @@ func (az *Cloud) EnsureLoadBalancerDeleted(ctx context.Context, clusterName stri } _, err = az.reconcileLoadBalancer(ctx, clusterName, service, nil, false /* wantLb */) - if err != nil && !retry.HasStatusForbiddenOrIgnoredError(err) { + if err != nil && !errutils.HasStatusForbiddenOrIgnoredError(err) { return err } @@ -559,11 +560,11 @@ func (az *Cloud) shouldChangeLoadBalancer(service *v1.Service, currLBName, clust // removeFrontendIPConfigurationFromLoadBalancer removes the given ip configs from the load balancer // and delete the load balancer if there is no ip config on it. It returns the name of the deleted load balancer // and it will be used in reconcileLoadBalancer to remove the load balancer from the list. -func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Context, lb *network.LoadBalancer, existingLBs *[]network.LoadBalancer, fips []*network.FrontendIPConfiguration, clusterName string, service *v1.Service) (string, error) { - if lb == nil || lb.LoadBalancerPropertiesFormat == nil || lb.FrontendIPConfigurations == nil { +func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Context, lb *armnetwork.LoadBalancer, existingLBs []*armnetwork.LoadBalancer, fips []*armnetwork.FrontendIPConfiguration, clusterName string, service *v1.Service) (string, error) { + if lb == nil || lb.Properties == nil || lb.Properties.FrontendIPConfigurations == nil { return "", nil } - fipConfigs := *lb.FrontendIPConfigurations + fipConfigs := lb.Properties.FrontendIPConfigurations for i, fipConfig := range fipConfigs { for _, fip := range fips { if strings.EqualFold(ptr.Deref(fipConfig.Name, ""), ptr.Deref(fip.Name, "")) { @@ -572,11 +573,11 @@ func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Conte } } } - lb.FrontendIPConfigurations = &fipConfigs + lb.Properties.FrontendIPConfigurations = fipConfigs // also remove the corresponding rules/probes - if lb.LoadBalancingRules != nil { - lbRules := *lb.LoadBalancingRules + if lb.Properties.LoadBalancingRules != nil { + lbRules := lb.Properties.LoadBalancingRules for i := len(lbRules) - 1; i >= 0; i-- { for _, fip := range fips { if strings.Contains(ptr.Deref(lbRules[i].Name, ""), ptr.Deref(fip.Name, "")) { @@ -584,10 +585,10 @@ func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Conte } } } - lb.LoadBalancingRules = &lbRules + lb.Properties.LoadBalancingRules = lbRules } - if lb.Probes != nil { - lbProbes := *lb.Probes + if lb.Properties.Probes != nil { + lbProbes := lb.Properties.Probes for i := len(lbProbes) - 1; i >= 0; i-- { for _, fip := range fips { if strings.Contains(ptr.Deref(lbProbes[i].Name, ""), ptr.Deref(fip.Name, "")) { @@ -595,7 +596,7 @@ func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Conte } } } - lb.Probes = &lbProbes + lb.Properties.Probes = lbProbes } // PLS does not support IPv6 so there will not be additional API calls. @@ -615,7 +616,7 @@ func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Conte logPrefix := fmt.Sprintf("removeFrontendIPConfigurationFromLoadBalancer(%s, %q, %s, %s)", ptr.Deref(lb.Name, ""), fipNames, clusterName, service.Name) if len(fipConfigs) == 0 { klog.V(2).Infof("%s: deleting load balancer because there is no remaining frontend IP configurations", logPrefix) - err := az.cleanOrphanedLoadBalancer(ctx, lb, *existingLBs, service, clusterName) + err := az.cleanOrphanedLoadBalancer(ctx, lb, existingLBs, service, clusterName) if err != nil { klog.Errorf("%s: failed to cleanupOrphanedLoadBalancer: %v", logPrefix, err) return "", err @@ -633,7 +634,7 @@ func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Conte return deletedLBName, nil } -func (az *Cloud) cleanOrphanedLoadBalancer(ctx context.Context, lb *network.LoadBalancer, existingLBs []network.LoadBalancer, service *v1.Service, clusterName string) error { +func (az *Cloud) cleanOrphanedLoadBalancer(ctx context.Context, lb *armnetwork.LoadBalancer, existingLBs []*armnetwork.LoadBalancer, service *v1.Service, clusterName string) error { lbName := ptr.Deref(lb.Name, "") serviceName := getServiceName(service) isBackendPoolPreConfigured := az.isBackendPoolPreConfigured(service) @@ -669,26 +670,26 @@ func (az *Cloud) cleanOrphanedLoadBalancer(ctx context.Context, lb *network.Load vmSetName := az.mapLoadBalancerNameToVMSet(lbName, clusterName) if _, ok := az.VMSet.(*availabilitySet); ok { // do nothing for availability set - lb.BackendAddressPools = nil + lb.Properties.BackendAddressPools = nil } if deleteErr := az.safeDeleteLoadBalancer(ctx, *lb, clusterName, vmSetName, service); deleteErr != nil { klog.Warningf("cleanOrphanedLoadBalancer(%s, %s, %s): failed to DeleteLB: %v", lbName, serviceName, clusterName, deleteErr) - rgName, vmssName, parseErr := retry.GetVMSSMetadataByRawError(deleteErr) + rgName, vmssName, parseErr := errutils.GetVMSSMetadataByRawError(deleteErr) if parseErr != nil { klog.Warningf("cleanOrphanedLoadBalancer(%s, %s, %s): failed to parse error: %v", lbName, serviceName, clusterName, parseErr) - return deleteErr.Error() + return deleteErr } if rgName == "" || vmssName == "" { klog.Warningf("cleanOrphanedLoadBalancer(%s, %s, %s): empty rgName or vmssName", lbName, serviceName, clusterName) - return deleteErr.Error() + return deleteErr } // if we reach here, it means the VM couldn't be deleted because it is being referenced by a VMSS if _, ok := az.VMSet.(*ScaleSet); !ok { klog.Warningf("cleanOrphanedLoadBalancer(%s, %s, %s): unexpected VMSet type, expected VMSS", lbName, serviceName, clusterName) - return deleteErr.Error() + return deleteErr } if !strings.EqualFold(rgName, az.ResourceGroup) { @@ -703,7 +704,7 @@ func (az *Cloud) cleanOrphanedLoadBalancer(ctx context.Context, lb *network.Load if deleteErr := az.DeleteLB(ctx, service, lbName); deleteErr != nil { klog.Errorf("cleanOrphanedLoadBalancer(%s, %s, %s): failed delete lb for the second time, stop retrying: %v", lbName, serviceName, clusterName, deleteErr) - return deleteErr.Error() + return deleteErr } } klog.V(10).Infof("cleanOrphanedLoadBalancer(%s, %s, %s): az.DeleteLB finished", lbName, serviceName, clusterName) @@ -712,15 +713,15 @@ func (az *Cloud) cleanOrphanedLoadBalancer(ctx context.Context, lb *network.Load } // safeDeleteLoadBalancer deletes the load balancer after decoupling it from the vmSet -func (az *Cloud) safeDeleteLoadBalancer(ctx context.Context, lb network.LoadBalancer, _, vmSetName string, service *v1.Service) *retry.Error { +func (az *Cloud) safeDeleteLoadBalancer(ctx context.Context, lb armnetwork.LoadBalancer, _, vmSetName string, service *v1.Service) error { lbBackendPoolIDsToDelete := []string{} - if lb.LoadBalancerPropertiesFormat != nil && lb.BackendAddressPools != nil { - for _, bp := range *lb.BackendAddressPools { + if lb.Properties != nil && lb.Properties.BackendAddressPools != nil { + for _, bp := range lb.Properties.BackendAddressPools { lbBackendPoolIDsToDelete = append(lbBackendPoolIDsToDelete, ptr.Deref(bp.ID, "")) } } - if _, err := az.VMSet.EnsureBackendPoolDeleted(ctx, service, lbBackendPoolIDsToDelete, vmSetName, lb.BackendAddressPools, true); err != nil { - return retry.NewError(false, fmt.Errorf("safeDeleteLoadBalancer: failed to EnsureBackendPoolDeleted: %w", err)) + if _, err := az.VMSet.EnsureBackendPoolDeleted(ctx, service, lbBackendPoolIDsToDelete, vmSetName, lb.Properties.BackendAddressPools, true); err != nil { + return fmt.Errorf("safeDeleteLoadBalancer: failed to EnsureBackendPoolDeleted: %w", err) } klog.V(2).Infof("safeDeleteLoadBalancer: deleting LB %s", ptr.Deref(lb.Name, "")) @@ -757,12 +758,12 @@ func (az *Cloud) getServiceLoadBalancer( clusterName string, nodes []*v1.Node, wantLb bool, - existingLBs *[]network.LoadBalancer, -) (lb *network.LoadBalancer, refreshedLBs *[]network.LoadBalancer, status *v1.LoadBalancerStatus, lbIPsPrimaryPIPs []string, exists bool, err error) { + existingLBs []*armnetwork.LoadBalancer, +) (lb *armnetwork.LoadBalancer, refreshedLBs []*armnetwork.LoadBalancer, status *v1.LoadBalancerStatus, lbIPsPrimaryPIPs []string, exists bool, err error) { logger := log.FromContextOrBackground(ctx) isInternal := requiresInternalLoadBalancer(service) - var defaultLB *network.LoadBalancer + var defaultLB *armnetwork.LoadBalancer primaryVMSetName := az.VMSet.GetPrimaryVMSetName() defaultLBName, err := az.getAzureLoadBalancerName(ctx, service, existingLBs, clusterName, primaryVMSetName, isInternal) if err != nil { @@ -770,28 +771,28 @@ func (az *Cloud) getServiceLoadBalancer( } // reuse the lb list from reconcileSharedLoadBalancer to reduce the api call - if existingLBs == nil || len(*existingLBs) == 0 { + if len(existingLBs) == 0 { lbs, err := az.ListLB(ctx, service) if err != nil { return nil, nil, nil, nil, false, err } - existingLBs = &lbs + existingLBs = lbs } // check if the service already has a load balancer var shouldChangeLB bool - for i := range *existingLBs { - existingLB := (*existingLBs)[i] + for i := range existingLBs { + existingLB := (existingLBs)[i] if strings.EqualFold(*existingLB.Name, defaultLBName) { - defaultLB = &existingLB + defaultLB = existingLB } - if isInternalLoadBalancer(&existingLB) != isInternal { + if isInternalLoadBalancer(existingLB) != isInternal { continue } - var fipConfigs []*network.FrontendIPConfiguration - status, lbIPsPrimaryPIPs, fipConfigs, err = az.getServiceLoadBalancerStatus(ctx, service, &existingLB) + var fipConfigs []*armnetwork.FrontendIPConfiguration + status, lbIPsPrimaryPIPs, fipConfigs, err = az.getServiceLoadBalancerStatus(ctx, service, existingLB) if err != nil { return nil, nil, nil, nil, false, err } @@ -813,13 +814,13 @@ func (az *Cloud) getServiceLoadBalancer( for _, fipConfig := range fipConfigs { fipConfigNames = append(fipConfigNames, ptr.Deref(fipConfig.Name, "")) } - deletedLBName, err = az.removeFrontendIPConfigurationFromLoadBalancer(ctx, &existingLB, existingLBs, fipConfigs, clusterName, service) + deletedLBName, err = az.removeFrontendIPConfigurationFromLoadBalancer(ctx, existingLB, existingLBs, fipConfigs, clusterName, service) if err != nil { logger.Error(err, fmt.Sprintf("getServiceLoadBalancer(%s, %s, %v): failed to remove frontend IP configurations %q from load balancer", service.Name, clusterName, wantLb, fipConfigNames)) return nil, nil, nil, nil, false, err } if deletedLBName != "" { - removeLBFromList(existingLBs, deletedLBName) + removeLBFromList(&existingLBs, deletedLBName) } az.reconcileMultipleStandardLoadBalancerConfigurationStatus( false, @@ -849,7 +850,7 @@ func (az *Cloud) getServiceLoadBalancer( break } - return &existingLB, existingLBs, status, lbIPsPrimaryPIPs, true, nil + return existingLB, existingLBs, status, lbIPsPrimaryPIPs, true, nil } // Service does not have a load balancer, select one. @@ -868,31 +869,31 @@ func (az *Cloud) getServiceLoadBalancer( // If the service moves to a different load balancer, return the one // instead of creating a new load balancer if it exists. if shouldChangeLB { - for _, existingLB := range *existingLBs { + for _, existingLB := range existingLBs { if strings.EqualFold(ptr.Deref(existingLB.Name, ""), defaultLBName) { - return &existingLB, existingLBs, status, lbIPsPrimaryPIPs, true, nil + return existingLB, existingLBs, status, lbIPsPrimaryPIPs, true, nil } } } // create a default LB with meta data if not present if defaultLB == nil { - defaultLB = &network.LoadBalancer{ - Name: &defaultLBName, - Location: &az.Location, - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, + defaultLB = &armnetwork.LoadBalancer{ + Name: &defaultLBName, + Location: &az.Location, + Properties: &armnetwork.LoadBalancerPropertiesFormat{}, } if az.UseStandardLoadBalancer() { - defaultLB.Sku = &network.LoadBalancerSku{ - Name: network.LoadBalancerSkuNameStandard, + defaultLB.SKU = &armnetwork.LoadBalancerSKU{ + Name: to.Ptr(armnetwork.LoadBalancerSKUNameStandard), } } if az.HasExtendedLocation() { - var typ network.ExtendedLocationTypes + var typ *armnetwork.ExtendedLocationTypes if getExtendedLocationTypeFromString(az.ExtendedLocationType) == armnetwork.ExtendedLocationTypesEdgeZone { - typ = network.EdgeZone + typ = to.Ptr(armnetwork.ExtendedLocationTypesEdgeZone) } - defaultLB.ExtendedLocation = &network.ExtendedLocation{ + defaultLB.ExtendedLocation = &armnetwork.ExtendedLocation{ Name: &az.ExtendedLocationName, Type: typ, } @@ -907,7 +908,7 @@ func (az *Cloud) getServiceLoadBalancer( // the minimum lb rules. If there are multiple LBs with same number of rules, // then selects the first one (sorted based on name). // Note: this function is only useful for basic LB clusters. -func (az *Cloud) selectLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, existingLBs *[]network.LoadBalancer, nodes []*v1.Node) (selectedLB *network.LoadBalancer, existsLb bool, err error) { +func (az *Cloud) selectLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, existingLBs []*armnetwork.LoadBalancer, nodes []*v1.Node) (selectedLB *armnetwork.LoadBalancer, existsLb bool, err error) { isInternal := requiresInternalLoadBalancer(service) serviceName := getServiceName(service) klog.V(2).Infof("selectLoadBalancer for service (%s): isInternal(%v) - start", serviceName, isInternal) @@ -916,37 +917,37 @@ func (az *Cloud) selectLoadBalancer(ctx context.Context, clusterName string, ser klog.Errorf("az.selectLoadBalancer: cluster(%s) service(%s) isInternal(%t) - az.GetVMSetNames failed, err=(%v)", clusterName, serviceName, isInternal, err) return nil, false, err } - klog.V(2).Infof("selectLoadBalancer: cluster(%s) service(%s) isInternal(%t) - vmSetNames %v", clusterName, serviceName, isInternal, *vmSetNames) + klog.V(2).Infof("selectLoadBalancer: cluster(%s) service(%s) isInternal(%t) - vmSetNames %v", clusterName, serviceName, isInternal, vmSetNames) - mapExistingLBs := map[string]network.LoadBalancer{} - for _, lb := range *existingLBs { + mapExistingLBs := map[string]*armnetwork.LoadBalancer{} + for _, lb := range existingLBs { mapExistingLBs[*lb.Name] = lb } selectedLBRuleCount := math.MaxInt32 - for _, currVMSetName := range *vmSetNames { - currLBName, _ := az.getAzureLoadBalancerName(ctx, service, existingLBs, clusterName, currVMSetName, isInternal) + for _, currVMSetName := range vmSetNames { + currLBName, _ := az.getAzureLoadBalancerName(ctx, service, existingLBs, clusterName, *currVMSetName, isInternal) lb, exists := mapExistingLBs[currLBName] if !exists { // select this LB as this is a new LB and will have minimum rules // create tmp lb struct to hold metadata for the new load-balancer - var loadBalancerSKU network.LoadBalancerSkuName + var loadBalancerSKU *armnetwork.LoadBalancerSKUName if az.UseStandardLoadBalancer() { - loadBalancerSKU = network.LoadBalancerSkuNameStandard + loadBalancerSKU = to.Ptr(armnetwork.LoadBalancerSKUNameStandard) } else { - loadBalancerSKU = network.LoadBalancerSkuNameBasic + loadBalancerSKU = to.Ptr(armnetwork.LoadBalancerSKUNameBasic) } - selectedLB = &network.LoadBalancer{ - Name: &currLBName, - Location: &az.Location, - Sku: &network.LoadBalancerSku{Name: loadBalancerSKU}, - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, + selectedLB = &armnetwork.LoadBalancer{ + Name: &currLBName, + Location: &az.Location, + SKU: &armnetwork.LoadBalancerSKU{Name: loadBalancerSKU}, + Properties: &armnetwork.LoadBalancerPropertiesFormat{}, } if az.HasExtendedLocation() { - var typ network.ExtendedLocationTypes + var typ *armnetwork.ExtendedLocationTypes if getExtendedLocationTypeFromString(az.ExtendedLocationType) == armnetwork.ExtendedLocationTypesEdgeZone { - typ = network.EdgeZone + typ = to.Ptr(armnetwork.ExtendedLocationTypesEdgeZone) } - selectedLB.ExtendedLocation = &network.ExtendedLocation{ + selectedLB.ExtendedLocation = &armnetwork.ExtendedLocation{ Name: &az.ExtendedLocationName, Type: typ, } @@ -955,25 +956,25 @@ func (az *Cloud) selectLoadBalancer(ctx context.Context, clusterName string, ser return selectedLB, false, nil } - lbRules := *lb.LoadBalancingRules + lbRules := lb.Properties.LoadBalancingRules currLBRuleCount := 0 if lbRules != nil { currLBRuleCount = len(lbRules) } if currLBRuleCount < selectedLBRuleCount { selectedLBRuleCount = currLBRuleCount - selectedLB = &lb + selectedLB = lb } } if selectedLB == nil { - err = fmt.Errorf("selectLoadBalancer: cluster(%s) service(%s) isInternal(%t) - unable to find load balancer for selected VM sets %v", clusterName, serviceName, isInternal, *vmSetNames) + err = fmt.Errorf("selectLoadBalancer: cluster(%s) service(%s) isInternal(%t) - unable to find load balancer for selected VM sets %v", clusterName, serviceName, isInternal, vmSetNames) klog.Error(err) return nil, false, err } // validate if the selected LB has not exceeded the MaximumLoadBalancerRuleCount if az.Config.MaximumLoadBalancerRuleCount != 0 && selectedLBRuleCount >= az.Config.MaximumLoadBalancerRuleCount { - err = fmt.Errorf("selectLoadBalancer: cluster(%s) service(%s) isInternal(%t) - all available load balancers have exceeded maximum rule limit %d, vmSetNames (%v)", clusterName, serviceName, isInternal, selectedLBRuleCount, *vmSetNames) + err = fmt.Errorf("selectLoadBalancer: cluster(%s) service(%s) isInternal(%t) - all available load balancers have exceeded maximum rule limit %d, vmSetNames (%v)", clusterName, serviceName, isInternal, selectedLBRuleCount, vmSetNames) klog.Error(err) return selectedLB, existsLb, err } @@ -985,33 +986,33 @@ func (az *Cloud) selectLoadBalancer(ctx context.Context, clusterName string, ser // Before DualStack support, old logic takes the first ingress IP as non-additional one // and the second one as additional one. With DualStack support, the second IP may be // the IP of another IP family so the new logic returns two variables. -func (az *Cloud) getServiceLoadBalancerStatus(ctx context.Context, service *v1.Service, lb *network.LoadBalancer) (status *v1.LoadBalancerStatus, lbIPsPrimaryPIPs []string, fipConfigs []*network.FrontendIPConfiguration, err error) { +func (az *Cloud) getServiceLoadBalancerStatus(ctx context.Context, service *v1.Service, lb *armnetwork.LoadBalancer) (status *v1.LoadBalancerStatus, lbIPsPrimaryPIPs []string, fipConfigs []*armnetwork.FrontendIPConfiguration, err error) { if lb == nil { klog.V(10).Info("getServiceLoadBalancerStatus: lb is nil") return nil, nil, nil, nil } - if lb.FrontendIPConfigurations == nil || len(*lb.FrontendIPConfigurations) == 0 { - klog.V(10).Info("getServiceLoadBalancerStatus: lb.FrontendIPConfigurations is nil") + if lb.Properties == nil || len(lb.Properties.FrontendIPConfigurations) == 0 { + klog.V(10).Info("getServiceLoadBalancerStatus: lb.Properties.FrontendIPConfigurations is nil") return nil, nil, nil, nil } isInternal := requiresInternalLoadBalancer(service) serviceName := getServiceName(service) lbIngresses := []v1.LoadBalancerIngress{} - for i := range *lb.FrontendIPConfigurations { - ipConfiguration := (*lb.FrontendIPConfigurations)[i] + for i := range lb.Properties.FrontendIPConfigurations { + ipConfiguration := lb.Properties.FrontendIPConfigurations[i] owns, isPrimaryService, _ := az.serviceOwnsFrontendIP(ctx, ipConfiguration, service) if owns { klog.V(2).Infof("get(%s): lb(%s) - found frontend IP config, primary service: %v", serviceName, ptr.Deref(lb.Name, ""), isPrimaryService) var lbIP *string if isInternal { - lbIP = ipConfiguration.PrivateIPAddress + lbIP = ipConfiguration.Properties.PrivateIPAddress } else { - if ipConfiguration.PublicIPAddress == nil { + if ipConfiguration.Properties.PublicIPAddress == nil { return nil, nil, nil, fmt.Errorf("get(%s): lb(%s) - failed to get LB PublicIPAddress is Nil", serviceName, *lb.Name) } - pipID := ipConfiguration.PublicIPAddress.ID + pipID := ipConfiguration.Properties.PublicIPAddress.ID if pipID == nil { return nil, nil, nil, fmt.Errorf("get(%s): lb(%s) - failed to get LB PublicIPAddress ID is Nil", serviceName, *lb.Name) } @@ -1024,7 +1025,7 @@ func (az *Cloud) getServiceLoadBalancerStatus(ctx context.Context, service *v1.S return nil, nil, nil, err } if existsPip { - lbIP = pip.IPAddress + lbIP = pip.Properties.IPAddress } } @@ -1032,7 +1033,7 @@ func (az *Cloud) getServiceLoadBalancerStatus(ctx context.Context, service *v1.S lbIngresses = append(lbIngresses, v1.LoadBalancerIngress{IP: ptr.Deref(lbIP, "")}) lbIPsPrimaryPIPs = append(lbIPsPrimaryPIPs, ptr.Deref(lbIP, "")) - fipConfigs = append(fipConfigs, &ipConfiguration) + fipConfigs = append(fipConfigs, ipConfiguration) } } if len(lbIngresses) == 0 { @@ -1113,24 +1114,24 @@ func updateServiceLoadBalancerIPs(service *v1.Service, serviceIPs []string) *v1. return copyService } -func (az *Cloud) ensurePublicIPExists(ctx context.Context, service *v1.Service, pipName string, domainNameLabel, clusterName string, shouldPIPExisted, foundDNSLabelAnnotation, isIPv6 bool) (*network.PublicIPAddress, error) { +func (az *Cloud) ensurePublicIPExists(ctx context.Context, service *v1.Service, pipName string, domainNameLabel, clusterName string, shouldPIPExisted, foundDNSLabelAnnotation, isIPv6 bool) (*armnetwork.PublicIPAddress, error) { pipResourceGroup := az.getPublicIPAddressResourceGroup(service) pip, existsPip, err := az.getPublicIPAddress(ctx, pipResourceGroup, pipName, azcache.CacheReadTypeDefault) if err != nil { return nil, err } serviceName := getServiceName(service) - ipVersion := network.IPv4 + ipVersion := to.Ptr(armnetwork.IPVersionIPv4) if isIPv6 { - ipVersion = network.IPv6 + ipVersion = to.Ptr(armnetwork.IPVersionIPv6) } var changed, owns, isUserAssignedPIP bool if existsPip { // ensure that the service tag is good for managed pips - owns, isUserAssignedPIP = serviceOwnsPublicIP(service, &pip, clusterName) + owns, isUserAssignedPIP = serviceOwnsPublicIP(service, pip, clusterName) if owns && !isUserAssignedPIP { - changed, err = bindServicesToPIP(&pip, []string{serviceName}, false) + changed, err = bindServicesToPIP(pip, []string{serviceName}, false) if err != nil { return nil, err } @@ -1141,32 +1142,32 @@ func (az *Cloud) ensurePublicIPExists(ctx context.Context, service *v1.Service, } // return if pip exist and dns label is the same - if strings.EqualFold(getDomainNameLabel(&pip), domainNameLabel) { + if strings.EqualFold(getDomainNameLabel(pip), domainNameLabel) { if existingServiceName := getServiceFromPIPDNSTags(pip.Tags); existingServiceName != "" && strings.EqualFold(existingServiceName, serviceName) { klog.V(6).Infof("ensurePublicIPExists for service(%s): pip(%s) - "+ "the service is using the DNS label on the public IP", serviceName, pipName) - var rerr *retry.Error + var err error if changed { klog.V(2).Infof("ensurePublicIPExists: updating the PIP %s for the incoming service %s", pipName, serviceName) err = az.CreateOrUpdatePIP(service, pipResourceGroup, pip) if err != nil { return nil, err } - pip, rerr = az.PublicIPAddressesClient.Get(ctx, pipResourceGroup, *pip.Name, "") - if rerr != nil { - return nil, rerr.Error() + pip, err = az.NetworkClientFactory.GetPublicIPAddressClient().Get(ctx, pipResourceGroup, *pip.Name, nil) + if err != nil { + return nil, err } } - return &pip, nil + return pip, nil } } klog.V(2).Infof("ensurePublicIPExists for service(%s): pip(%s) - updating", serviceName, ptr.Deref(pip.Name, "")) - if pip.PublicIPAddressPropertiesFormat == nil { - pip.PublicIPAddressPropertiesFormat = &network.PublicIPAddressPropertiesFormat{ - PublicIPAllocationMethod: network.Static, + if pip.Properties == nil { + pip.Properties = &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), PublicIPAddressVersion: ipVersion, } changed = true @@ -1177,22 +1178,23 @@ func (az *Cloud) ensurePublicIPExists(ctx context.Context, service *v1.Service, } changed = true - - pip.Name = ptr.To(pipName) - pip.Location = ptr.To(az.Location) + pip = &armnetwork.PublicIPAddress{ + Name: ptr.To(pipName), + Location: ptr.To(az.Location), + } if az.HasExtendedLocation() { klog.V(2).Infof("Using extended location with name %s, and type %s for PIP", az.ExtendedLocationName, az.ExtendedLocationType) - var typ network.ExtendedLocationTypes + var typ *armnetwork.ExtendedLocationTypes if getExtendedLocationTypeFromString(az.ExtendedLocationType) == armnetwork.ExtendedLocationTypesEdgeZone { - typ = network.EdgeZone + typ = to.Ptr(armnetwork.ExtendedLocationTypesEdgeZone) } - pip.ExtendedLocation = &network.ExtendedLocation{ + pip.ExtendedLocation = &armnetwork.ExtendedLocation{ Name: &az.ExtendedLocationName, Type: typ, } } - pip.PublicIPAddressPropertiesFormat = &network.PublicIPAddressPropertiesFormat{ - PublicIPAllocationMethod: network.Static, + pip.Properties = &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), PublicIPAddressVersion: ipVersion, IPTags: getServiceIPTagRequestForPublicIP(service).IPTags, } @@ -1200,17 +1202,17 @@ func (az *Cloud) ensurePublicIPExists(ctx context.Context, service *v1.Service, consts.ServiceTagKey: ptr.To(""), consts.ClusterNameKey: &clusterName, } - if _, err = bindServicesToPIP(&pip, []string{serviceName}, false); err != nil { + if _, err = bindServicesToPIP(pip, []string{serviceName}, false); err != nil { return nil, err } if az.UseStandardLoadBalancer() { - pip.Sku = &network.PublicIPAddressSku{ - Name: network.PublicIPAddressSkuNameStandard, + pip.SKU = &armnetwork.PublicIPAddressSKU{ + Name: to.Ptr(armnetwork.PublicIPAddressSKUNameStandard), } if id := getServicePIPPrefixID(service, isIPv6); id != "" { - pip.PublicIPPrefix = &network.SubResource{ID: ptr.To(id)} + pip.Properties.PublicIPPrefix = &armnetwork.SubResource{ID: ptr.To(id)} } // skip adding zone info since edge zones doesn't support multiple availability zones. @@ -1221,18 +1223,18 @@ func (az *Cloud) ensurePublicIPExists(ctx context.Context, service *v1.Service, return nil, err } if len(zones) > 0 { - pip.Zones = &zones + pip.Zones = zones } } } klog.V(2).Infof("ensurePublicIPExists for service(%s): pip(%s) - creating", serviceName, *pip.Name) } - if !isUserAssignedPIP && az.ensurePIPTagged(service, &pip) { + if !isUserAssignedPIP && az.ensurePIPTagged(service, pip) { changed = true } if foundDNSLabelAnnotation { - updatedDNSSettings, err := reconcileDNSSettings(&pip, domainNameLabel, serviceName, pipName, isUserAssignedPIP) + updatedDNSSettings, err := reconcileDNSSettings(pip, domainNameLabel, serviceName, pipName, isUserAssignedPIP) if err != nil { return nil, fmt.Errorf("ensurePublicIPExists for service(%s): failed to reconcileDNSSettings: %w", serviceName, err) } @@ -1244,7 +1246,7 @@ func (az *Cloud) ensurePublicIPExists(ctx context.Context, service *v1.Service, // use the same family as the clusterIP as we support IPv6 single stack as well // as dual-stack clusters - updatedIPSettings := az.reconcileIPSettings(&pip, service, isIPv6) + updatedIPSettings := az.reconcileIPSettings(pip, service, isIPv6) if updatedIPSettings { changed = true } @@ -1260,37 +1262,37 @@ func (az *Cloud) ensurePublicIPExists(ctx context.Context, service *v1.Service, klog.V(10).Infof("CreateOrUpdatePIP(%s, %q): end", pipResourceGroup, *pip.Name) } - pip, rerr := az.PublicIPAddressesClient.Get(ctx, pipResourceGroup, *pip.Name, "") + pip, rerr := az.NetworkClientFactory.GetPublicIPAddressClient().Get(ctx, pipResourceGroup, *pip.Name, nil) if rerr != nil { - return nil, rerr.Error() + return nil, rerr } - return &pip, nil + return pip, nil } -func (az *Cloud) reconcileIPSettings(pip *network.PublicIPAddress, service *v1.Service, isIPv6 bool) bool { +func (az *Cloud) reconcileIPSettings(pip *armnetwork.PublicIPAddress, service *v1.Service, isIPv6 bool) bool { var changed bool serviceName := getServiceName(service) if isIPv6 { - if !strings.EqualFold(string(pip.PublicIPAddressVersion), string(network.IPv6)) { - pip.PublicIPAddressVersion = network.IPv6 + if !strings.EqualFold(string(*pip.Properties.PublicIPAddressVersion), string(armnetwork.IPVersionIPv6)) { + pip.Properties.PublicIPAddressVersion = to.Ptr(armnetwork.IPVersionIPv6) klog.V(2).Infof("service(%s): pip(%s) - should be created as IPv6", serviceName, *pip.Name) changed = true } if az.UseStandardLoadBalancer() { - // standard sku must have static allocation method for ipv6 - if !strings.EqualFold(string(pip.PublicIPAddressPropertiesFormat.PublicIPAllocationMethod), string(network.Static)) { - pip.PublicIPAddressPropertiesFormat.PublicIPAllocationMethod = network.Static + // standard SKU must have static allocation method for ipv6 + if !strings.EqualFold(string(*pip.Properties.PublicIPAllocationMethod), string(armnetwork.IPAllocationMethodStatic)) { + pip.Properties.PublicIPAllocationMethod = to.Ptr(armnetwork.IPAllocationMethodStatic) changed = true } - } else if !strings.EqualFold(string(pip.PublicIPAddressPropertiesFormat.PublicIPAllocationMethod), string(network.Dynamic)) { - pip.PublicIPAddressPropertiesFormat.PublicIPAllocationMethod = network.Dynamic + } else if !strings.EqualFold(string(*pip.Properties.PublicIPAllocationMethod), string(armnetwork.IPAllocationMethodDynamic)) { + pip.Properties.PublicIPAllocationMethod = to.Ptr(armnetwork.IPAllocationMethodDynamic) changed = true } } else { - if !strings.EqualFold(string(pip.PublicIPAddressVersion), string(network.IPv4)) { - pip.PublicIPAddressVersion = network.IPv4 + if !strings.EqualFold(string(*pip.Properties.PublicIPAddressVersion), string(armnetwork.IPVersionIPv4)) { + pip.Properties.PublicIPAddressVersion = to.Ptr(armnetwork.IPVersionIPv4) klog.V(2).Infof("service(%s): pip(%s) - should be created as IPv4", serviceName, *pip.Name) changed = true } @@ -1300,7 +1302,7 @@ func (az *Cloud) reconcileIPSettings(pip *network.PublicIPAddress, service *v1.S } func reconcileDNSSettings( - pip *network.PublicIPAddress, + pip *armnetwork.PublicIPAddress, domainNameLabel, serviceName, pipName string, isUserAssignedPIP bool, ) (bool, error) { @@ -1311,22 +1313,22 @@ func reconcileDNSSettings( } if len(domainNameLabel) == 0 { - if pip.PublicIPAddressPropertiesFormat.DNSSettings != nil { - pip.PublicIPAddressPropertiesFormat.DNSSettings = nil + if pip.Properties.DNSSettings != nil { + pip.Properties.DNSSettings = nil changed = true } } else { - if pip.PublicIPAddressPropertiesFormat.DNSSettings == nil || - pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel == nil { + if pip.Properties.DNSSettings == nil || + pip.Properties.DNSSettings.DomainNameLabel == nil { klog.V(6).Infof("ensurePublicIPExists for service(%s): pip(%s) - no existing DNS label on the public IP, create one", serviceName, pipName) - pip.PublicIPAddressPropertiesFormat.DNSSettings = &network.PublicIPAddressDNSSettings{ + pip.Properties.DNSSettings = &armnetwork.PublicIPAddressDNSSettings{ DomainNameLabel: &domainNameLabel, } changed = true } else { - existingDNSLabel := pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel + existingDNSLabel := pip.Properties.DNSSettings.DomainNameLabel if !strings.EqualFold(ptr.Deref(existingDNSLabel, ""), domainNameLabel) { - pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel = &domainNameLabel + pip.Properties.DNSSettings.DomainNameLabel = &domainNameLabel changed = true } } @@ -1391,7 +1393,7 @@ func getClusterFromPIPClusterTags(tags map[string]*string) string { type serviceIPTagRequest struct { IPTagsRequestedByAnnotation bool - IPTags *[]network.IPTag + IPTags []*armnetwork.IPTag } // Get the ip tag Request for the public ip from service annotations. @@ -1430,67 +1432,67 @@ func getIPTagMap(ipTagString string) map[string]string { return outputMap } -func sortIPTags(ipTags *[]network.IPTag) { +func sortIPTags(ipTags *[]*armnetwork.IPTag) { if ipTags != nil { sort.Slice(*ipTags, func(i, j int) bool { - ipTag := *ipTags - return ptr.Deref(ipTag[i].IPTagType, "") < ptr.Deref(ipTag[j].IPTagType, "") || - ptr.Deref(ipTag[i].Tag, "") < ptr.Deref(ipTag[j].Tag, "") + + return ptr.Deref((*ipTags)[i].IPTagType, "") < ptr.Deref((*ipTags)[j].IPTagType, "") || + ptr.Deref((*ipTags)[i].Tag, "") < ptr.Deref((*ipTags)[j].Tag, "") }) } } -func areIPTagsEquivalent(ipTags1 *[]network.IPTag, ipTags2 *[]network.IPTag) bool { - sortIPTags(ipTags1) - sortIPTags(ipTags2) +func areIPTagsEquivalent(ipTags1 []*armnetwork.IPTag, ipTags2 []*armnetwork.IPTag) bool { + sortIPTags(&ipTags1) + sortIPTags(&ipTags2) if ipTags1 == nil { - ipTags1 = &[]network.IPTag{} + ipTags1 = []*armnetwork.IPTag{} } if ipTags2 == nil { - ipTags2 = &[]network.IPTag{} + ipTags2 = []*armnetwork.IPTag{} } return reflect.DeepEqual(ipTags1, ipTags2) } -func convertIPTagMapToSlice(ipTagMap map[string]string) *[]network.IPTag { +func convertIPTagMapToSlice(ipTagMap map[string]string) []*armnetwork.IPTag { if ipTagMap == nil { return nil } if len(ipTagMap) == 0 { - return &[]network.IPTag{} + return []*armnetwork.IPTag{} } - outputTags := []network.IPTag{} + outputTags := []*armnetwork.IPTag{} for k, v := range ipTagMap { - ipTag := network.IPTag{ + ipTag := &armnetwork.IPTag{ IPTagType: ptr.To(k), Tag: ptr.To(v), } outputTags = append(outputTags, ipTag) } - return &outputTags + return outputTags } -func getDomainNameLabel(pip *network.PublicIPAddress) string { - if pip == nil || pip.PublicIPAddressPropertiesFormat == nil || pip.PublicIPAddressPropertiesFormat.DNSSettings == nil { +func getDomainNameLabel(pip *armnetwork.PublicIPAddress) string { + if pip == nil || pip.Properties == nil || pip.Properties.DNSSettings == nil { return "" } - return ptr.Deref(pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel, "") + return ptr.Deref(pip.Properties.DNSSettings.DomainNameLabel, "") } // subnet is reused to reduce API calls when dualstack. func (az *Cloud) isFrontendIPChanged( ctx context.Context, clusterName string, - config network.FrontendIPConfiguration, + config *armnetwork.FrontendIPConfiguration, service *v1.Service, lbFrontendIPConfigName string, - subnet *network.Subnet, + subnet *armnetwork.Subnet, ) (bool, error) { isServiceOwnsFrontendIP, isPrimaryService, fipIPVersion := az.serviceOwnsFrontendIP(ctx, config, service) if isServiceOwnsFrontendIP && isPrimaryService && !strings.EqualFold(ptr.Deref(config.Name, ""), lbFrontendIPConfigName) { @@ -1502,10 +1504,10 @@ func (az *Cloud) isFrontendIPChanged( pipRG := az.getPublicIPAddressResourceGroup(service) var isIPv6 bool var err error - if fipIPVersion != "" { - isIPv6 = fipIPVersion == network.IPv6 + if fipIPVersion != nil { + isIPv6 = *fipIPVersion == armnetwork.IPVersionIPv6 } else { - if isIPv6, err = az.isFIPIPv6(service, &config); err != nil { + if isIPv6, err = az.isFIPIPv6(service, config); err != nil { return false, err } } @@ -1518,11 +1520,11 @@ func (az *Cloud) isFrontendIPChanged( if subnet == nil { return false, fmt.Errorf("isFrontendIPChanged: Unexpected nil subnet %q", ptr.Deref(subnetName, "")) } - if config.Subnet != nil && !strings.EqualFold(ptr.Deref(config.Subnet.ID, ""), ptr.Deref(subnet.ID, "")) { + if config.Properties.Subnet != nil && !strings.EqualFold(ptr.Deref(config.Properties.Subnet.ID, ""), ptr.Deref(subnet.ID, "")) { return true, nil } } - return loadBalancerIP != "" && !strings.EqualFold(loadBalancerIP, ptr.Deref(config.PrivateIPAddress, "")), nil + return loadBalancerIP != "" && !strings.EqualFold(loadBalancerIP, ptr.Deref(config.Properties.PrivateIPAddress, "")), nil } pipName, _, err := az.determinePublicIPName(ctx, clusterName, service, isIPv6) if err != nil { @@ -1535,7 +1537,7 @@ func (az *Cloud) isFrontendIPChanged( if !existsPip { return true, nil } - return config.PublicIPAddress != nil && !strings.EqualFold(ptr.Deref(pip.ID, ""), ptr.Deref(config.PublicIPAddress.ID, "")), nil + return config.Properties.PublicIPAddress != nil && !strings.EqualFold(ptr.Deref(pip.ID, ""), ptr.Deref(config.Properties.PublicIPAddress.ID, "")), nil } // isFrontendIPConfigUnsafeToDelete checks if a frontend IP config is safe to be deleted. @@ -1543,7 +1545,7 @@ func (az *Cloud) isFrontendIPChanged( // loadBalancing resources, including loadBalancing rules, outbound rules, inbound NAT rules // and inbound NAT pools. func (az *Cloud) isFrontendIPConfigUnsafeToDelete( - lb *network.LoadBalancer, + lb *armnetwork.LoadBalancer, service *v1.Service, fipConfigID *string, ) (bool, error) { @@ -1552,35 +1554,35 @@ func (az *Cloud) isFrontendIPConfigUnsafeToDelete( } var ( - lbRules []network.LoadBalancingRule - outboundRules []network.OutboundRule - inboundNatRules []network.InboundNatRule - inboundNatPools []network.InboundNatPool + lbRules []*armnetwork.LoadBalancingRule + outboundRules []*armnetwork.OutboundRule + inboundNatRules []*armnetwork.InboundNatRule + inboundNatPools []*armnetwork.InboundNatPool unsafe bool ) - if lb.LoadBalancerPropertiesFormat != nil { - if lb.LoadBalancingRules != nil { - lbRules = *lb.LoadBalancingRules + if lb.Properties != nil { + if lb.Properties.LoadBalancingRules != nil { + lbRules = lb.Properties.LoadBalancingRules } - if lb.OutboundRules != nil { - outboundRules = *lb.OutboundRules + if lb.Properties.OutboundRules != nil { + outboundRules = lb.Properties.OutboundRules } - if lb.InboundNatRules != nil { - inboundNatRules = *lb.InboundNatRules + if lb.Properties.InboundNatRules != nil { + inboundNatRules = lb.Properties.InboundNatRules } - if lb.InboundNatPools != nil { - inboundNatPools = *lb.InboundNatPools + if lb.Properties.InboundNatPools != nil { + inboundNatPools = lb.Properties.InboundNatPools } } // check if there are load balancing rules from other services // referencing this frontend IP configuration for _, lbRule := range lbRules { - if lbRule.LoadBalancingRulePropertiesFormat != nil && - lbRule.FrontendIPConfiguration != nil && - lbRule.FrontendIPConfiguration.ID != nil && - strings.EqualFold(*lbRule.FrontendIPConfiguration.ID, *fipConfigID) { + if lbRule.Properties != nil && + lbRule.Properties.FrontendIPConfiguration != nil && + lbRule.Properties.FrontendIPConfiguration.ID != nil && + strings.EqualFold(*lbRule.Properties.FrontendIPConfiguration.ID, *fipConfigID) { if !az.serviceOwnsRule(service, *lbRule.Name) { warningMsg := fmt.Sprintf("isFrontendIPConfigUnsafeToDelete: frontend IP configuration with ID %s on LB %s cannot be deleted because it is being referenced by load balancing rules of other services", *fipConfigID, *lb.Name) klog.Warning(warningMsg) @@ -1594,8 +1596,8 @@ func (az *Cloud) isFrontendIPConfigUnsafeToDelete( // check if there are outbound rules // referencing this frontend IP configuration for _, outboundRule := range outboundRules { - if outboundRule.OutboundRulePropertiesFormat != nil && outboundRule.FrontendIPConfigurations != nil { - outboundRuleFIPConfigs := *outboundRule.FrontendIPConfigurations + if outboundRule.Properties != nil && outboundRule.Properties.FrontendIPConfigurations != nil { + outboundRuleFIPConfigs := outboundRule.Properties.FrontendIPConfigurations if found := findMatchedOutboundRuleFIPConfig(fipConfigID, outboundRuleFIPConfigs); found { warningMsg := fmt.Sprintf("isFrontendIPConfigUnsafeToDelete: frontend IP configuration with ID %s on LB %s cannot be deleted because it is being referenced by the outbound rule %s", *fipConfigID, *lb.Name, *outboundRule.Name) klog.Warning(warningMsg) @@ -1609,10 +1611,10 @@ func (az *Cloud) isFrontendIPConfigUnsafeToDelete( // check if there are inbound NAT rules // referencing this frontend IP configuration for _, inboundNatRule := range inboundNatRules { - if inboundNatRule.InboundNatRulePropertiesFormat != nil && - inboundNatRule.FrontendIPConfiguration != nil && - inboundNatRule.FrontendIPConfiguration.ID != nil && - strings.EqualFold(*inboundNatRule.FrontendIPConfiguration.ID, *fipConfigID) { + if inboundNatRule.Properties != nil && + inboundNatRule.Properties.FrontendIPConfiguration != nil && + inboundNatRule.Properties.FrontendIPConfiguration.ID != nil && + strings.EqualFold(*inboundNatRule.Properties.FrontendIPConfiguration.ID, *fipConfigID) { warningMsg := fmt.Sprintf("isFrontendIPConfigUnsafeToDelete: frontend IP configuration with ID %s on LB %s cannot be deleted because it is being referenced by the inbound NAT rule %s", *fipConfigID, *lb.Name, *inboundNatRule.Name) klog.Warning(warningMsg) az.Event(service, v1.EventTypeWarning, "DeletingFrontendIPConfiguration", warningMsg) @@ -1624,10 +1626,10 @@ func (az *Cloud) isFrontendIPConfigUnsafeToDelete( // check if there are inbound NAT pools // referencing this frontend IP configuration for _, inboundNatPool := range inboundNatPools { - if inboundNatPool.InboundNatPoolPropertiesFormat != nil && - inboundNatPool.FrontendIPConfiguration != nil && - inboundNatPool.FrontendIPConfiguration.ID != nil && - strings.EqualFold(*inboundNatPool.FrontendIPConfiguration.ID, *fipConfigID) { + if inboundNatPool.Properties != nil && + inboundNatPool.Properties.FrontendIPConfiguration != nil && + inboundNatPool.Properties.FrontendIPConfiguration.ID != nil && + strings.EqualFold(*inboundNatPool.Properties.FrontendIPConfiguration.ID, *fipConfigID) { warningMsg := fmt.Sprintf("isFrontendIPConfigUnsafeToDelete: frontend IP configuration with ID %s on LB %s cannot be deleted because it is being referenced by the inbound NAT pool %s", *fipConfigID, *lb.Name, *inboundNatPool.Name) klog.Warning(warningMsg) az.Event(service, v1.EventTypeWarning, "DeletingFrontendIPConfiguration", warningMsg) @@ -1639,7 +1641,7 @@ func (az *Cloud) isFrontendIPConfigUnsafeToDelete( return unsafe, nil } -func findMatchedOutboundRuleFIPConfig(fipConfigID *string, outboundRuleFIPConfigs []network.SubResource) bool { +func findMatchedOutboundRuleFIPConfig(fipConfigID *string, outboundRuleFIPConfigs []*armnetwork.SubResource) bool { var found bool for _, config := range outboundRuleFIPConfigs { if config.ID != nil && strings.EqualFold(*config.ID, *fipConfigID) { @@ -1651,25 +1653,25 @@ func findMatchedOutboundRuleFIPConfig(fipConfigID *string, outboundRuleFIPConfig func (az *Cloud) findFrontendIPConfigsOfService( ctx context.Context, - fipConfigs *[]network.FrontendIPConfiguration, + fipConfigs []*armnetwork.FrontendIPConfiguration, service *v1.Service, -) (map[bool]*network.FrontendIPConfiguration, error) { - fipsOfServiceMap := map[bool]*network.FrontendIPConfiguration{} - for _, config := range *fipConfigs { +) (map[bool]*armnetwork.FrontendIPConfiguration, error) { + fipsOfServiceMap := map[bool]*armnetwork.FrontendIPConfiguration{} + for _, config := range fipConfigs { config := config owns, _, fipIPVersion := az.serviceOwnsFrontendIP(ctx, config, service) if owns { var fipIsIPv6 bool var err error - if fipIPVersion != "" { - fipIsIPv6 = fipIPVersion == network.IPv6 + if fipIPVersion != nil { + fipIsIPv6 = fipIPVersion == to.Ptr(armnetwork.IPVersionIPv6) } else { - if fipIsIPv6, err = az.isFIPIPv6(service, &config); err != nil { + if fipIsIPv6, err = az.isFIPIPv6(service, config); err != nil { return nil, err } } - fipsOfServiceMap[fipIsIPv6] = &config + fipsOfServiceMap[fipIsIPv6] = config } } @@ -1683,10 +1685,10 @@ func (az *Cloud) findFrontendIPConfigsOfService( // named . If not, an error will be reported. func (az *Cloud) reconcileMultipleStandardLoadBalancerConfigurations( ctx context.Context, - lbs *[]network.LoadBalancer, + lbs []*armnetwork.LoadBalancer, service *v1.Service, clusterName string, - existingLBs *[]network.LoadBalancer, + existingLBs []*armnetwork.LoadBalancer, nodes []*v1.Node, ) (err error) { if !az.UseMultipleStandardLoadBalancers() { @@ -1729,11 +1731,11 @@ func (az *Cloud) reconcileMultipleStandardLoadBalancerConfigurations( } } - for _, existingLB := range *existingLBs { + for _, existingLB := range existingLBs { lbName := ptr.Deref(existingLB.Name, "") - if existingLB.LoadBalancerPropertiesFormat != nil && - existingLB.LoadBalancingRules != nil { - for _, rule := range *existingLB.LoadBalancingRules { + if existingLB.Properties != nil && + existingLB.Properties.LoadBalancingRules != nil { + for _, rule := range existingLB.Properties.LoadBalancingRules { ruleName := ptr.Deref(rule.Name, "") rulePrefix := strings.Split(ruleName, "-")[0] if rulePrefix == "" { @@ -1765,7 +1767,7 @@ func (az *Cloud) reconcileMultipleStandardLoadBalancerConfigurations( // This also reconciles the Service's Ports with the LoadBalancer config. // This entails adding rules/probes for expected Ports and removing stale rules/ports. // nodes only used if wantLb is true -func (az *Cloud) reconcileLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, nodes []*v1.Node, wantLb bool) (*network.LoadBalancer, error) { +func (az *Cloud) reconcileLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, nodes []*v1.Node, wantLb bool) (*armnetwork.LoadBalancer, error) { isBackendPoolPreConfigured := az.isBackendPoolPreConfigured(service) serviceName := getServiceName(service) klog.V(2).Infof("reconcileLoadBalancer for service(%s) - wantLb(%t): started", serviceName, wantLb) @@ -1827,7 +1829,7 @@ func (az *Cloud) reconcileLoadBalancer(ctx context.Context, clusterName string, // If the LB is changed, refresh it to avoid etag mismatch error // later when create or update the LB. - addOrUpdateLBInList(existingLBs, lb) + addOrUpdateLBInList(&existingLBs, lb) } // reconcile the load balancer's frontend IP configurations. @@ -1850,9 +1852,9 @@ func (az *Cloud) reconcileLoadBalancer(ctx context.Context, clusterName string, var isIPv6 bool var err error - _, _, fipIPVersion := az.serviceOwnsFrontendIP(ctx, *ownedFIPConfig, service) - if fipIPVersion != "" { - isIPv6 = fipIPVersion == network.IPv6 + _, _, fipIPVersion := az.serviceOwnsFrontendIP(ctx, ownedFIPConfig, service) + if fipIPVersion != nil { + isIPv6 = fipIPVersion == to.Ptr(armnetwork.IPVersionIPv6) } else { if isIPv6, err = az.isFIPIPv6(service, ownedFIPConfig); err != nil { return nil, err @@ -1861,8 +1863,8 @@ func (az *Cloud) reconcileLoadBalancer(ctx context.Context, clusterName string, lbFrontendIPConfigIDs[isIPv6] = *ownedFIPConfig.ID } - var expectedProbes []network.Probe - var expectedRules []network.LoadBalancingRule + var expectedProbes []*armnetwork.Probe + var expectedRules []*armnetwork.LoadBalancingRule getExpectedLBRule := func(isIPv6 bool) error { expectedProbesSingleStack, expectedRulesSingleStack, err := az.getExpectedLBRules(service, lbFrontendIPConfigIDs[isIPv6], lbBackendPoolIDs[isIPv6], lbName, isIPv6) if err != nil { @@ -1908,7 +1910,7 @@ func (az *Cloud) reconcileLoadBalancer(ctx context.Context, clusterName string, if len(toDeleteConfigs) > 0 { for i := range toDeleteConfigs { fipConfigToDel := toDeleteConfigs[i] - err := az.reconcilePrivateLinkService(ctx, clusterName, service, &fipConfigToDel, false /* wantPLS */) + err := az.reconcilePrivateLinkService(ctx, clusterName, service, fipConfigToDel, false /* wantPLS */) if err != nil { klog.Errorf( "reconcileLoadBalancer for service(%s): lb(%s) - failed to clean up PrivateLinkService for frontEnd(%s): %v", @@ -1921,8 +1923,8 @@ func (az *Cloud) reconcileLoadBalancer(ctx context.Context, clusterName string, } } - if lb.FrontendIPConfigurations == nil || len(*lb.FrontendIPConfigurations) == 0 { - err := az.cleanOrphanedLoadBalancer(ctx, lb, *existingLBs, service, clusterName) + if lb.Properties == nil || len(lb.Properties.FrontendIPConfigurations) == 0 { + err := az.cleanOrphanedLoadBalancer(ctx, lb, existingLBs, service, clusterName) if err != nil { klog.Errorf("reconcileLoadBalancer for service(%s): lb(%s) - failed to cleanOrphanedLoadBalancer: %v", serviceName, lbName, err) return nil, err @@ -1936,7 +1938,7 @@ func (az *Cloud) reconcileLoadBalancer(ctx context.Context, clusterName string, } // Refresh updated lb which will be used later in other places. - newLB, exist, err := az.getAzureLoadBalancer(ctx, lbName, azcache.CacheReadTypeDefault) + newLB, exist, err := az.getAzureLoadBalancer(ctx, lbName, azcache.CacheReadTypeForceRefresh) if err != nil { klog.Errorf("reconcileLoadBalancer for service(%s): getAzureLoadBalancer(%s) failed: %v", serviceName, lbName, err) return nil, err @@ -1946,7 +1948,7 @@ func (az *Cloud) reconcileLoadBalancer(ctx context.Context, clusterName string, } lb = newLB - addOrUpdateLBInList(existingLBs, newLB) + addOrUpdateLBInList(&existingLBs, newLB) } } @@ -1969,10 +1971,10 @@ func (az *Cloud) reconcileLoadBalancer(ctx context.Context, clusterName string, // the cluster when using multiple standard load balancers. // This is because there are chances for backend pools from more than one load balancers // change in one reconciliation loop. - var lbToReconcile []network.LoadBalancer - lbToReconcile = append(lbToReconcile, *lb) + var lbToReconcile []*armnetwork.LoadBalancer + lbToReconcile = append(lbToReconcile, lb) if az.UseMultipleStandardLoadBalancers() { - lbToReconcile = *existingLBs + lbToReconcile = existingLBs } lb, err = az.reconcileBackendPoolHosts(ctx, lb, lbToReconcile, service, nodes, clusterName, vmSetName, lbBackendPoolIDs) if err != nil { @@ -1990,20 +1992,20 @@ func (az *Cloud) reconcileLoadBalancer(ctx context.Context, clusterName string, func (az *Cloud) reconcileBackendPoolHosts( ctx context.Context, - currentLB *network.LoadBalancer, - lbs []network.LoadBalancer, + currentLB *armnetwork.LoadBalancer, + lbs []*armnetwork.LoadBalancer, service *v1.Service, nodes []*v1.Node, clusterName, vmSetName string, lbBackendPoolIDs map[bool]string, -) (*network.LoadBalancer, error) { - var res *network.LoadBalancer +) (*armnetwork.LoadBalancer, error) { + var res *armnetwork.LoadBalancer res = currentLB for _, lb := range lbs { lb := lb lbName := ptr.Deref(lb.Name, "") - if lb.LoadBalancerPropertiesFormat != nil && lb.LoadBalancerPropertiesFormat.BackendAddressPools != nil { - for i, backendPool := range *lb.LoadBalancerPropertiesFormat.BackendAddressPools { + if lb.Properties != nil && lb.Properties.BackendAddressPools != nil { + for i, backendPool := range lb.Properties.BackendAddressPools { isIPv6 := isBackendPoolIPv6(ptr.Deref(backendPool.Name, "")) if strings.EqualFold(ptr.Deref(backendPool.Name, ""), az.getBackendPoolNameForService(service, clusterName, isIPv6)) { if err := az.LoadBalancerBackendPool.EnsureHostsInPool( @@ -2014,7 +2016,7 @@ func (az *Cloud) reconcileBackendPoolHosts( vmSetName, clusterName, lbName, - (*lb.LoadBalancerPropertiesFormat.BackendAddressPools)[i], + (lb.Properties.BackendAddressPools)[i], ); err != nil { return nil, err } @@ -2022,25 +2024,27 @@ func (az *Cloud) reconcileBackendPoolHosts( } } if strings.EqualFold(lbName, *currentLB.Name) { - res = &lb + res = lb } } return res, nil } // addOrUpdateLBInList adds or updates the given lb in the list -func addOrUpdateLBInList(lbs *[]network.LoadBalancer, targetLB *network.LoadBalancer) { - for i, lb := range *lbs { - if strings.EqualFold(ptr.Deref(lb.Name, ""), ptr.Deref(targetLB.Name, "")) { - (*lbs)[i] = *targetLB - return +func addOrUpdateLBInList(lbs *[]*armnetwork.LoadBalancer, targetLB *armnetwork.LoadBalancer) { + if lbs != nil { + for i, lb := range *lbs { + if strings.EqualFold(ptr.Deref(lb.Name, ""), ptr.Deref(targetLB.Name, "")) { + (*lbs)[i] = targetLB + return + } } + *lbs = append(*lbs, targetLB) } - *lbs = append(*lbs, *targetLB) } // removeLBFromList removes the given lb from the list -func removeLBFromList(lbs *[]network.LoadBalancer, lbName string) { +func removeLBFromList(lbs *[]*armnetwork.LoadBalancer, lbName string) { if lbs != nil { for i := len(*lbs) - 1; i >= 0; i-- { if strings.EqualFold(ptr.Deref((*lbs)[i].Name, ""), lbName) { @@ -2095,7 +2099,7 @@ func (az *Cloud) removeDeletedNodesFromLoadBalancerConfigurations(nodes []*v1.No func (az *Cloud) accommodateNodesByPrimaryVMSet( ctx context.Context, lbName string, - lbs *[]network.LoadBalancer, + lbs []*armnetwork.LoadBalancer, nodes []*v1.Node, nodeNameToLBConfigIDXMap map[string]int, ) error { @@ -2140,7 +2144,7 @@ func (az *Cloud) accommodateNodesByPrimaryVMSet( // accommodateNodesByNodeSelector decides which load balancer configuration the node should be added to by node selector func (az *Cloud) accommodateNodesByNodeSelector( lbName string, - lbs *[]network.LoadBalancer, + lbs []*armnetwork.LoadBalancer, service *v1.Service, nodes []*v1.Node, nodeNameToLBConfigIDXMap map[string]int, @@ -2233,14 +2237,13 @@ func (az *Cloud) accommodateNodesByNodeSelector( } // isLBInList checks if the lb is in the list by multipleStandardLoadBalancerConfig name -func isLBInList(lbs *[]network.LoadBalancer, lbConfigName string) bool { - if lbs != nil { - for _, lb := range *lbs { - if strings.EqualFold(trimSuffixIgnoreCase(ptr.Deref(lb.Name, ""), consts.InternalLoadBalancerNameSuffix), lbConfigName) { - return true - } +func isLBInList(lbs []*armnetwork.LoadBalancer, lbConfigName string) bool { + for _, lb := range lbs { + if strings.EqualFold(trimSuffixIgnoreCase(ptr.Deref(lb.Name, ""), consts.InternalLoadBalancerNameSuffix), lbConfigName) { + return true } } + return false } @@ -2264,7 +2267,7 @@ func (az *Cloud) reconcileMultipleStandardLoadBalancerBackendNodes( ctx context.Context, clusterName string, lbName string, - lbs *[]network.LoadBalancer, + lbs []*armnetwork.LoadBalancer, service *v1.Service, nodes []*v1.Node, init bool, @@ -2301,22 +2304,22 @@ func (az *Cloud) reconcileMultipleStandardLoadBalancerBackendNodes( // recordExistingNodesOnLoadBalancers restores the node distribution // across multiple load balancers each time the cloud provider restarts. -func (az *Cloud) recordExistingNodesOnLoadBalancers(clusterName string, lbs *[]network.LoadBalancer) error { +func (az *Cloud) recordExistingNodesOnLoadBalancers(clusterName string, lbs []*armnetwork.LoadBalancer) error { bi, ok := az.LoadBalancerBackendPool.(*backendPoolTypeNodeIP) if !ok { return errors.New("must use backend pool type nodeIP") } bpNames := getBackendPoolNames(clusterName) - for _, lb := range *lbs { - if lb.LoadBalancerPropertiesFormat == nil || - lb.LoadBalancerPropertiesFormat.BackendAddressPools == nil { + for _, lb := range lbs { + if lb.Properties == nil || + lb.Properties.BackendAddressPools == nil { continue } lbName := ptr.Deref(lb.Name, "") - for _, backendPool := range *lb.LoadBalancerPropertiesFormat.BackendAddressPools { + for _, backendPool := range lb.Properties.BackendAddressPools { backendPool := backendPool if found, _ := isLBBackendPoolsExisting(bpNames, backendPool.Name); found { - nodeNames := bi.getBackendPoolNodeNames(&backendPool) + nodeNames := bi.getBackendPoolNodeNames(backendPool) for i, multiSLBConfig := range az.MultipleStandardLoadBalancerConfigurations { if strings.EqualFold(trimSuffixIgnoreCase( lbName, consts.InternalLoadBalancerNameSuffix, @@ -2349,14 +2352,14 @@ func (az *Cloud) reconcileMultipleStandardLoadBalancerConfigurationStatus(wantLb } } -func (az *Cloud) reconcileLBProbes(lb *network.LoadBalancer, service *v1.Service, serviceName string, wantLb bool, expectedProbes []network.Probe) bool { +func (az *Cloud) reconcileLBProbes(lb *armnetwork.LoadBalancer, service *v1.Service, serviceName string, wantLb bool, expectedProbes []*armnetwork.Probe) bool { expectedProbes, _ = az.keepSharedProbe(service, *lb, expectedProbes, wantLb) // remove unwanted probes dirtyProbes := false - var updatedProbes []network.Probe - if lb.Probes != nil { - updatedProbes = *lb.Probes + var updatedProbes []*armnetwork.Probe + if lb.Properties.Probes != nil { + updatedProbes = lb.Properties.Probes } for i := len(updatedProbes) - 1; i >= 0; i-- { existingProbe := updatedProbes[i] @@ -2390,17 +2393,17 @@ func (az *Cloud) reconcileLBProbes(lb *network.LoadBalancer, service *v1.Service if dirtyProbes { probesJSON, _ := json.Marshal(expectedProbes) klog.V(2).Infof("reconcileLoadBalancer for service (%s)(%t): lb probes updated: %s", serviceName, wantLb, string(probesJSON)) - lb.Probes = &updatedProbes + lb.Properties.Probes = updatedProbes } return dirtyProbes } -func (az *Cloud) reconcileLBRules(lb *network.LoadBalancer, service *v1.Service, serviceName string, wantLb bool, expectedRules []network.LoadBalancingRule) bool { +func (az *Cloud) reconcileLBRules(lb *armnetwork.LoadBalancer, service *v1.Service, serviceName string, wantLb bool, expectedRules []*armnetwork.LoadBalancingRule) bool { // update rules dirtyRules := false - var updatedRules []network.LoadBalancingRule - if lb.LoadBalancingRules != nil { - updatedRules = *lb.LoadBalancingRules + var updatedRules []*armnetwork.LoadBalancingRule + if lb.Properties.LoadBalancingRules != nil { + updatedRules = lb.Properties.LoadBalancingRules } // update rules: remove unwanted @@ -2436,7 +2439,7 @@ func (az *Cloud) reconcileLBRules(lb *network.LoadBalancer, service *v1.Service, if dirtyRules { ruleJSON, _ := json.Marshal(expectedRules) klog.V(2).Infof("reconcileLoadBalancer for service (%s)(%t): lb rules updated: %s", serviceName, wantLb, string(ruleJSON)) - lb.LoadBalancingRules = &updatedRules + lb.Properties.LoadBalancingRules = updatedRules } return dirtyRules } @@ -2445,23 +2448,23 @@ func (az *Cloud) reconcileFrontendIPConfigs( ctx context.Context, clusterName string, service *v1.Service, - lb *network.LoadBalancer, + lb *armnetwork.LoadBalancer, status *v1.LoadBalancerStatus, wantLb bool, lbFrontendIPConfigNames map[bool]string, -) ([]*network.FrontendIPConfiguration, []network.FrontendIPConfiguration, bool, error) { +) ([]*armnetwork.FrontendIPConfiguration, []*armnetwork.FrontendIPConfiguration, bool, error) { var err error lbName := *lb.Name serviceName := getServiceName(service) isInternal := requiresInternalLoadBalancer(service) dirtyConfigs := false - var newConfigs []network.FrontendIPConfiguration - var toDeleteConfigs []network.FrontendIPConfiguration - if lb.FrontendIPConfigurations != nil { - newConfigs = *lb.FrontendIPConfigurations + var newConfigs []*armnetwork.FrontendIPConfiguration + var toDeleteConfigs []*armnetwork.FrontendIPConfiguration + if lb.Properties.FrontendIPConfigurations != nil { + newConfigs = lb.Properties.FrontendIPConfigurations } - var ownedFIPConfigs []*network.FrontendIPConfiguration + var ownedFIPConfigs []*armnetwork.FrontendIPConfiguration if !wantLb { for i := len(newConfigs) - 1; i >= 0; i-- { config := newConfigs[i] @@ -2495,9 +2498,9 @@ func (az *Cloud) reconcileFrontendIPConfigs( } } else { var ( - previousZone *[]string + previousZone []*string isFipChanged bool - subnet network.Subnet + subnet *armnetwork.Subnet existsSubnet bool ) @@ -2506,11 +2509,18 @@ func (az *Cloud) reconcileFrontendIPConfigs( if subnetName == nil { subnetName = &az.SubnetName } - subnet, existsSubnet, err = az.getSubnet("", az.VnetName, *subnetName) - if err != nil { - return nil, toDeleteConfigs, false, err + + vnetResourceGroup := "" + if len(az.VnetResourceGroup) > 0 { + vnetResourceGroup = az.VnetResourceGroup + } else { + vnetResourceGroup = az.ResourceGroup } - if !existsSubnet { + + subnet, err = az.subnetRepo.Get(ctx, vnetResourceGroup, az.VnetName, *subnetName) + if existsSubnet, err = errutils.CheckResourceExistsFromAzcoreError(err); !existsSubnet && err != nil { + return nil, toDeleteConfigs, false, err + } else if !existsSubnet { return nil, toDeleteConfigs, false, fmt.Errorf("ensure(%s): lb(%s) - failed to get subnet: %s/%s", serviceName, lbName, az.VnetName, *subnetName) } } @@ -2525,15 +2535,15 @@ func (az *Cloud) reconcileFrontendIPConfigs( klog.V(4).Infof("reconcileFrontendIPConfigs for service (%s): checking owned frontend IP configuration %s", serviceName, ptr.Deref(config.Name, "")) var isIPv6 bool var err error - if fipIPVersion != "" { - isIPv6 = fipIPVersion == network.IPv6 + if fipIPVersion != nil { + isIPv6 = fipIPVersion == to.Ptr(armnetwork.IPVersionIPv6) } else { - if isIPv6, err = az.isFIPIPv6(service, &config); err != nil { + if isIPv6, err = az.isFIPIPv6(service, config); err != nil { return nil, toDeleteConfigs, false, err } } - isFipChanged, err = az.isFrontendIPChanged(ctx, clusterName, config, service, lbFrontendIPConfigNames[isIPv6], &subnet) + isFipChanged, err = az.isFrontendIPChanged(ctx, clusterName, config, service, lbFrontendIPConfigNames[isIPv6], subnet) if err != nil { return nil, toDeleteConfigs, false, err } @@ -2546,7 +2556,7 @@ func (az *Cloud) reconcileFrontendIPConfigs( } } - ownedFIPConfigMap, err := az.findFrontendIPConfigsOfService(ctx, &newConfigs, service) + ownedFIPConfigMap, err := az.findFrontendIPConfigsOfService(ctx, newConfigs, service) if err != nil { return nil, toDeleteConfigs, false, err } @@ -2559,14 +2569,14 @@ func (az *Cloud) reconcileFrontendIPConfigs( serviceName, lbName, lbFrontendIPConfigNames[isIPv6], isIPv6) // construct FrontendIPConfigurationPropertiesFormat - var fipConfigurationProperties *network.FrontendIPConfigurationPropertiesFormat + var fipConfigurationProperties *armnetwork.FrontendIPConfigurationPropertiesFormat if isInternal { - configProperties := network.FrontendIPConfigurationPropertiesFormat{ - Subnet: &subnet, + configProperties := &armnetwork.FrontendIPConfigurationPropertiesFormat{ + Subnet: subnet, } if isIPv6 { - configProperties.PrivateIPAddressVersion = network.IPv6 + configProperties.PrivateIPAddressVersion = to.Ptr(armnetwork.IPVersionIPv6) } loadBalancerIP := getServiceLoadBalancerIP(service, isIPv6) @@ -2574,7 +2584,7 @@ func (az *Cloud) reconcileFrontendIPConfigs( ingressIPInSubnet := func(ingresses []v1.LoadBalancerIngress) bool { for _, ingress := range ingresses { ingressIP := ingress.IP - if (net.ParseIP(ingressIP).To4() == nil) == isIPv6 && ipInSubnet(ingressIP, &subnet) { + if (net.ParseIP(ingressIP).To4() == nil) == isIPv6 && ipInSubnet(ingressIP, subnet) { privateIP = ingressIP break } @@ -2583,19 +2593,19 @@ func (az *Cloud) reconcileFrontendIPConfigs( } if loadBalancerIP != "" { klog.V(4).Infof("reconcileFrontendIPConfigs for service (%s): use loadBalancerIP %q from Service spec", serviceName, loadBalancerIP) - configProperties.PrivateIPAllocationMethod = network.Static + configProperties.PrivateIPAllocationMethod = to.Ptr(armnetwork.IPAllocationMethodStatic) configProperties.PrivateIPAddress = &loadBalancerIP } else if status != nil && len(status.Ingress) > 0 && ingressIPInSubnet(status.Ingress) { klog.V(4).Infof("reconcileFrontendIPConfigs for service (%s): keep the original private IP %s", serviceName, privateIP) - configProperties.PrivateIPAllocationMethod = network.Static + configProperties.PrivateIPAllocationMethod = to.Ptr(armnetwork.IPAllocationMethodStatic) configProperties.PrivateIPAddress = ptr.To(privateIP) } else { // We'll need to call GetLoadBalancer later to retrieve allocated IP. klog.V(4).Infof("reconcileFrontendIPConfigs for service (%s): dynamically allocate the private IP", serviceName) - configProperties.PrivateIPAllocationMethod = network.Dynamic + configProperties.PrivateIPAllocationMethod = to.Ptr(armnetwork.IPAllocationMethodDynamic) } - fipConfigurationProperties = &configProperties + fipConfigurationProperties = configProperties } else { pipName, shouldPIPExisted, err := az.determinePublicIPName(ctx, clusterName, service, isIPv6) if err != nil { @@ -2606,19 +2616,19 @@ func (az *Cloud) reconcileFrontendIPConfigs( if err != nil { return err } - fipConfigurationProperties = &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: pip.ID}, + fipConfigurationProperties = &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: pip.ID}, } } - newConfig := network.FrontendIPConfiguration{ - Name: ptr.To(lbFrontendIPConfigNames[isIPv6]), - ID: ptr.To(fmt.Sprintf(consts.FrontendIPConfigIDTemplate, az.getNetworkResourceSubscriptionID(), az.ResourceGroup, ptr.Deref(lb.Name, ""), lbFrontendIPConfigNames[isIPv6])), - FrontendIPConfigurationPropertiesFormat: fipConfigurationProperties, + newConfig := &armnetwork.FrontendIPConfiguration{ + Name: ptr.To(lbFrontendIPConfigNames[isIPv6]), + ID: ptr.To(fmt.Sprintf(consts.FrontendIPConfigIDTemplate, az.getNetworkResourceSubscriptionID(), az.ResourceGroup, ptr.Deref(lb.Name, ""), lbFrontendIPConfigNames[isIPv6])), + Properties: fipConfigurationProperties, } if isInternal { - if err := az.getFrontendZones(ctx, &newConfig, previousZone, isFipChanged, serviceName, lbFrontendIPConfigNames[isIPv6]); err != nil { + if err := az.getFrontendZones(ctx, newConfig, previousZone, isFipChanged, serviceName, lbFrontendIPConfigNames[isIPv6]); err != nil { klog.Errorf("reconcileLoadBalancer for service (%s)(%t): failed to getFrontendZones: %s", serviceName, wantLb, err.Error()) return err } @@ -2643,7 +2653,7 @@ func (az *Cloud) reconcileFrontendIPConfigs( } if dirtyConfigs { - lb.FrontendIPConfigurations = &newConfigs + lb.Properties.FrontendIPConfigurations = newConfigs } return ownedFIPConfigs, toDeleteConfigs, dirtyConfigs, err @@ -2651,8 +2661,8 @@ func (az *Cloud) reconcileFrontendIPConfigs( func (az *Cloud) getFrontendZones( ctx context.Context, - fipConfig *network.FrontendIPConfiguration, - previousZone *[]string, + fipConfig *armnetwork.FrontendIPConfiguration, + previousZone []*string, isFipChanged bool, serviceName, lbFrontendIPConfigName string, ) error { @@ -2664,13 +2674,13 @@ func (az *Cloud) getFrontendZones( return err } if az.UseStandardLoadBalancer() && len(zones) > 0 && !az.HasExtendedLocation() { - fipConfig.Zones = &zones + fipConfig.Zones = zones } } else { if previousZone == nil { // keep the existing zone information for existing frontends klog.V(2).Infof("getFrontendZones for service (%s): lb frontendconfig(%s): setting zone to nil", serviceName, lbFrontendIPConfigName) } else { - zoneStr := strings.Join(*previousZone, ",") + zoneStr := strings.Join(lo.FromSlicePtr(previousZone), ",") klog.V(2).Infof("getFrontendZones for service (%s): lb frontendconfig(%s): setting zone to %s", serviceName, lbFrontendIPConfigName, zoneStr) } fipConfig.Zones = previousZone @@ -2682,7 +2692,7 @@ func (az *Cloud) getFrontendZones( // ports which conflict with the existing loadBalancer resources, // including inbound NAT rule, inbound NAT pools and loadBalancing rules func (az *Cloud) checkLoadBalancerResourcesConflicts( - lb *network.LoadBalancer, + lb *armnetwork.LoadBalancer, frontendIPConfigID string, service *v1.Service, ) error { @@ -2692,8 +2702,8 @@ func (az *Cloud) checkLoadBalancerResourcesConflicts( ports := service.Spec.Ports for _, port := range ports { - if lb.LoadBalancingRules != nil { - for _, rule := range *lb.LoadBalancingRules { + if lb.Properties.LoadBalancingRules != nil { + for _, rule := range lb.Properties.LoadBalancingRules { if lbRuleConflictsWithPort(rule, frontendIPConfigID, port) { // ignore self-owned rules for unit test if rule.Name != nil && az.serviceOwnsRule(service, *rule.Name) { @@ -2703,42 +2713,42 @@ func (az *Cloud) checkLoadBalancerResourcesConflicts( "consume the port %d which is being referenced by an existing loadBalancing rule %s with "+ "the same protocol %s and frontend IP config with ID %s", port.Name, - *rule.FrontendPort, + *rule.Properties.FrontendPort, *rule.Name, - rule.Protocol, - *rule.FrontendIPConfiguration.ID) + *rule.Properties.Protocol, + *rule.Properties.FrontendIPConfiguration.ID) } } } - if lb.InboundNatRules != nil { - for _, inboundNatRule := range *lb.InboundNatRules { + if lb.Properties.InboundNatRules != nil { + for _, inboundNatRule := range lb.Properties.InboundNatRules { if inboundNatRuleConflictsWithPort(inboundNatRule, frontendIPConfigID, port) { return fmt.Errorf("checkLoadBalancerResourcesConflicts: service port %s is trying to "+ "consume the port %d which is being referenced by an existing inbound NAT rule %s with "+ "the same protocol %s and frontend IP config with ID %s", port.Name, - *inboundNatRule.FrontendPort, + *inboundNatRule.Properties.FrontendPort, *inboundNatRule.Name, - inboundNatRule.Protocol, - *inboundNatRule.FrontendIPConfiguration.ID) + *inboundNatRule.Properties.Protocol, + *inboundNatRule.Properties.FrontendIPConfiguration.ID) } } } - if lb.InboundNatPools != nil { - for _, pool := range *lb.InboundNatPools { + if lb.Properties.InboundNatPools != nil { + for _, pool := range lb.Properties.InboundNatPools { if inboundNatPoolConflictsWithPort(pool, frontendIPConfigID, port) { return fmt.Errorf("checkLoadBalancerResourcesConflicts: service port %s is trying to "+ "consume the port %d which is being in the range (%d-%d) of an existing "+ "inbound NAT pool %s with the same protocol %s and frontend IP config with ID %s", port.Name, port.Port, - *pool.FrontendPortRangeStart, - *pool.FrontendPortRangeEnd, + *pool.Properties.FrontendPortRangeStart, + *pool.Properties.FrontendPortRangeEnd, *pool.Name, - pool.Protocol, - *pool.FrontendIPConfiguration.ID) + *pool.Properties.Protocol, + *pool.Properties.FrontendIPConfiguration.ID) } } } @@ -2747,40 +2757,40 @@ func (az *Cloud) checkLoadBalancerResourcesConflicts( return nil } -func inboundNatPoolConflictsWithPort(pool network.InboundNatPool, frontendIPConfigID string, port v1.ServicePort) bool { - return pool.InboundNatPoolPropertiesFormat != nil && - pool.FrontendIPConfiguration != nil && - pool.FrontendIPConfiguration.ID != nil && - strings.EqualFold(*pool.FrontendIPConfiguration.ID, frontendIPConfigID) && - strings.EqualFold(string(pool.Protocol), string(port.Protocol)) && - pool.FrontendPortRangeStart != nil && - pool.FrontendPortRangeEnd != nil && - *pool.FrontendPortRangeStart <= port.Port && - *pool.FrontendPortRangeEnd >= port.Port +func inboundNatPoolConflictsWithPort(pool *armnetwork.InboundNatPool, frontendIPConfigID string, port v1.ServicePort) bool { + return pool.Properties != nil && + pool.Properties.FrontendIPConfiguration != nil && + pool.Properties.FrontendIPConfiguration.ID != nil && + strings.EqualFold(*pool.Properties.FrontendIPConfiguration.ID, frontendIPConfigID) && + strings.EqualFold(string(*pool.Properties.Protocol), string(port.Protocol)) && + pool.Properties.FrontendPortRangeStart != nil && + pool.Properties.FrontendPortRangeEnd != nil && + *pool.Properties.FrontendPortRangeStart <= port.Port && + *pool.Properties.FrontendPortRangeEnd >= port.Port } -func inboundNatRuleConflictsWithPort(inboundNatRule network.InboundNatRule, frontendIPConfigID string, port v1.ServicePort) bool { - return inboundNatRule.InboundNatRulePropertiesFormat != nil && - inboundNatRule.FrontendIPConfiguration != nil && - inboundNatRule.FrontendIPConfiguration.ID != nil && - strings.EqualFold(*inboundNatRule.FrontendIPConfiguration.ID, frontendIPConfigID) && - strings.EqualFold(string(inboundNatRule.Protocol), string(port.Protocol)) && - inboundNatRule.FrontendPort != nil && - *inboundNatRule.FrontendPort == port.Port +func inboundNatRuleConflictsWithPort(inboundNatRule *armnetwork.InboundNatRule, frontendIPConfigID string, port v1.ServicePort) bool { + return inboundNatRule.Properties != nil && + inboundNatRule.Properties.FrontendIPConfiguration != nil && + inboundNatRule.Properties.FrontendIPConfiguration.ID != nil && + strings.EqualFold(*inboundNatRule.Properties.FrontendIPConfiguration.ID, frontendIPConfigID) && + strings.EqualFold(string(*inboundNatRule.Properties.Protocol), string(port.Protocol)) && + inboundNatRule.Properties.FrontendPort != nil && + *inboundNatRule.Properties.FrontendPort == port.Port } -func lbRuleConflictsWithPort(rule network.LoadBalancingRule, frontendIPConfigID string, port v1.ServicePort) bool { - return rule.LoadBalancingRulePropertiesFormat != nil && - rule.FrontendIPConfiguration != nil && - rule.FrontendIPConfiguration.ID != nil && - strings.EqualFold(*rule.FrontendIPConfiguration.ID, frontendIPConfigID) && - strings.EqualFold(string(rule.Protocol), string(port.Protocol)) && - rule.FrontendPort != nil && - *rule.FrontendPort == port.Port +func lbRuleConflictsWithPort(rule *armnetwork.LoadBalancingRule, frontendIPConfigID string, port v1.ServicePort) bool { + return rule.Properties != nil && + rule.Properties.FrontendIPConfiguration != nil && + rule.Properties.FrontendIPConfiguration.ID != nil && + strings.EqualFold(*rule.Properties.FrontendIPConfiguration.ID, frontendIPConfigID) && + strings.EqualFold(string(*rule.Properties.Protocol), string(port.Protocol)) && + rule.Properties.FrontendPort != nil && + *rule.Properties.FrontendPort == port.Port } // buildLBRules -// for following sku: basic loadbalancer vs standard load balancer +// for following SKU: basic loadbalancer vs standard load balancer // for following scenario: internal vs external func (az *Cloud) getExpectedLBRules( service *v1.Service, @@ -2788,15 +2798,15 @@ func (az *Cloud) getExpectedLBRules( lbBackendPoolID string, lbName string, isIPv6 bool, -) ([]network.Probe, []network.LoadBalancingRule, error) { - var expectedRules []network.LoadBalancingRule - var expectedProbes []network.Probe +) ([]*armnetwork.Probe, []*armnetwork.LoadBalancingRule, error) { + var expectedRules []*armnetwork.LoadBalancingRule + var expectedProbes []*armnetwork.Probe // support podPresence health check when External Traffic Policy is local // take precedence over user defined probe configuration // healthcheck proxy server serves http requests // https://github.com/kubernetes/kubernetes/blob/7c013c3f64db33cf19f38bb2fc8d9182e42b0b7b/pkg/proxy/healthcheck/service_health.go#L236 - var nodeEndpointHealthprobe *network.Probe + var nodeEndpointHealthprobe *armnetwork.Probe var nodeEndpointHealthprobeAdded bool if servicehelpers.NeedsHealthCheck(service) && !(consts.IsPLSEnabled(service.Annotations) && consts.IsPLSProxyProtocolEnabled(service.Annotations)) { podPresencePath, podPresencePort := servicehelpers.GetServiceHealthCheckPathPort(service) @@ -2805,11 +2815,11 @@ func (az *Cloud) getExpectedLBRules( if err != nil { return nil, nil, err } - nodeEndpointHealthprobe = &network.Probe{ + nodeEndpointHealthprobe = &armnetwork.Probe{ Name: &lbRuleName, - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ RequestPath: ptr.To(podPresencePath), - Protocol: network.ProbeProtocolHTTP, + Protocol: to.Ptr(armnetwork.ProbeProtocolHTTP), Port: ptr.To(podPresencePort), IntervalInSeconds: probeInterval, ProbeThreshold: numberOfProbes, @@ -2848,23 +2858,23 @@ func (az *Cloud) getExpectedLBRules( // ignore error because we only need one correct rule } if portprobe != nil { - props.Probe = &network.SubResource{ + props.Probe = &armnetwork.SubResource{ ID: ptr.To(az.getLoadBalancerProbeID(lbName, *portprobe.Name)), } - expectedProbes = append(expectedProbes, *portprobe) + expectedProbes = append(expectedProbes, portprobe) break } } } else { - props.Probe = &network.SubResource{ + props.Probe = &armnetwork.SubResource{ ID: ptr.To(az.getLoadBalancerProbeID(lbName, *nodeEndpointHealthprobe.Name)), } - expectedProbes = append(expectedProbes, *nodeEndpointHealthprobe) + expectedProbes = append(expectedProbes, nodeEndpointHealthprobe) } - expectedRules = append(expectedRules, network.LoadBalancingRule{ - Name: &lbRuleName, - LoadBalancingRulePropertiesFormat: props, + expectedRules = append(expectedRules, &armnetwork.LoadBalancingRule{ + Name: &lbRuleName, + Properties: props, }) // end of HA mode handling } else { @@ -2891,7 +2901,7 @@ func (az *Cloud) getExpectedLBRules( if err != nil { return expectedProbes, expectedRules, fmt.Errorf("failed to parse transport protocol: %w", err) } - props, err := az.getExpectedLoadBalancingRulePropertiesForPort(service, lbFrontendIPConfigID, lbBackendPoolID, port, *transportProto) + props, err := az.getExpectedLoadBalancingRulePropertiesForPort(service, lbFrontendIPConfigID, lbBackendPoolID, port, transportProto) if err != nil { return expectedProbes, expectedRules, fmt.Errorf("error generate lb rule for ha mod loadbalancer. err: %w", err) } @@ -2910,16 +2920,16 @@ func (az *Cloud) getExpectedLBRules( return expectedProbes, expectedRules, err } if portprobe != nil { - props.Probe = &network.SubResource{ + props.Probe = &armnetwork.SubResource{ ID: ptr.To(az.getLoadBalancerProbeID(lbName, *portprobe.Name)), } - expectedProbes = append(expectedProbes, *portprobe) + expectedProbes = append(expectedProbes, portprobe) } else if nodeEndpointHealthprobe != nil { - props.Probe = &network.SubResource{ + props.Probe = &armnetwork.SubResource{ ID: ptr.To(az.getLoadBalancerProbeID(lbName, *nodeEndpointHealthprobe.Name)), } if !nodeEndpointHealthprobeAdded { - expectedProbes = append(expectedProbes, *nodeEndpointHealthprobe) + expectedProbes = append(expectedProbes, nodeEndpointHealthprobe) nodeEndpointHealthprobeAdded = true } } @@ -2928,9 +2938,9 @@ func (az *Cloud) getExpectedLBRules( props.BackendPort = ptr.To(port.NodePort) props.EnableFloatingIP = ptr.To(false) } - expectedRules = append(expectedRules, network.LoadBalancingRule{ - Name: &lbRuleName, - LoadBalancingRulePropertiesFormat: props, + expectedRules = append(expectedRules, &armnetwork.LoadBalancingRule{ + Name: &lbRuleName, + Properties: props, }) } } @@ -2942,13 +2952,13 @@ func (az *Cloud) getExpectedLBRules( func (az *Cloud) getExpectedLoadBalancingRulePropertiesForPort( service *v1.Service, lbFrontendIPConfigID string, - lbBackendPoolID string, servicePort v1.ServicePort, transportProto network.TransportProtocol, -) (*network.LoadBalancingRulePropertiesFormat, error) { + lbBackendPoolID string, servicePort v1.ServicePort, transportProto *armnetwork.TransportProtocol, +) (*armnetwork.LoadBalancingRulePropertiesFormat, error) { var err error - loadDistribution := network.LoadDistributionDefault + loadDistribution := to.Ptr(armnetwork.LoadDistributionDefault) if service.Spec.SessionAffinity == v1.ServiceAffinityClientIP { - loadDistribution = network.LoadDistributionSourceIP + loadDistribution = to.Ptr(armnetwork.LoadDistributionSourceIP) } var lbIdleTimeout *int32 @@ -2967,22 +2977,22 @@ func (az *Cloud) getExpectedLoadBalancingRulePropertiesForPort( lbIdleTimeout = ptr.To(int32(4)) } - props := &network.LoadBalancingRulePropertiesFormat{ + props := &armnetwork.LoadBalancingRulePropertiesFormat{ Protocol: transportProto, FrontendPort: ptr.To(servicePort.Port), BackendPort: ptr.To(servicePort.Port), DisableOutboundSnat: ptr.To(az.DisableLoadBalancerOutboundSNAT()), EnableFloatingIP: ptr.To(true), LoadDistribution: loadDistribution, - FrontendIPConfiguration: &network.SubResource{ + FrontendIPConfiguration: &armnetwork.SubResource{ ID: ptr.To(lbFrontendIPConfigID), }, - BackendAddressPool: &network.SubResource{ + BackendAddressPool: &armnetwork.SubResource{ ID: ptr.To(lbBackendPoolID), }, IdleTimeoutInMinutes: lbIdleTimeout, } - if strings.EqualFold(string(transportProto), string(network.TransportProtocolTCP)) && az.UseStandardLoadBalancer() { + if strings.EqualFold(string(*transportProto), string(armnetwork.TransportProtocolTCP)) && az.UseStandardLoadBalancer() { props.EnableTCPReset = ptr.To(!consts.IsTCPResetDisabled(service.Annotations)) } @@ -3000,8 +3010,8 @@ func (az *Cloud) getExpectedHAModeLoadBalancingRuleProperties( service *v1.Service, lbFrontendIPConfigID string, lbBackendPoolID string, -) (*network.LoadBalancingRulePropertiesFormat, error) { - props, err := az.getExpectedLoadBalancingRulePropertiesForPort(service, lbFrontendIPConfigID, lbBackendPoolID, v1.ServicePort{}, network.TransportProtocolAll) +) (*armnetwork.LoadBalancingRulePropertiesFormat, error) { + props, err := az.getExpectedLoadBalancingRulePropertiesForPort(service, lbFrontendIPConfigID, lbBackendPoolID, v1.ServicePort{}, to.Ptr(armnetwork.TransportProtocolAll)) if err != nil { return nil, fmt.Errorf("error generate lb rule for ha mod loadbalancer. err: %w", err) } @@ -3151,7 +3161,7 @@ func (az *Cloud) shouldUpdateLoadBalancer(ctx context.Context, clusterName strin // Determine if we should release existing owned public IPs // FIXME: This function is a bit of a mess, and could use some refactoring. func shouldReleaseExistingOwnedPublicIP( - existingPip *network.PublicIPAddress, + existingPip *armnetwork.PublicIPAddress, serviceReferences []string, lbShouldExist, lbIsInternal, isUserAssignedPIP bool, desiredPipName string, @@ -3163,13 +3173,12 @@ func shouldReleaseExistingOwnedPublicIP( } // Latch some variables for readability purposes. - pipName := *(*existingPip).Name + pipName := *existingPip.Name // Assume the current IP Tags are empty by default unless properties specify otherwise. - currentIPTags := &[]network.IPTag{} - pipPropertiesFormat := (*existingPip).PublicIPAddressPropertiesFormat - if pipPropertiesFormat != nil { - currentIPTags = (*pipPropertiesFormat).IPTags + currentIPTags := []*armnetwork.IPTag{} + if existingPip != nil && existingPip.Properties != nil { + currentIPTags = existingPip.Properties.IPTags } // Check whether the public IP is being referenced by other service. @@ -3198,7 +3207,7 @@ func shouldReleaseExistingOwnedPublicIP( } // ensurePIPTagged ensures the public IP of the service is tagged as configured -func (az *Cloud) ensurePIPTagged(service *v1.Service, pip *network.PublicIPAddress) bool { +func (az *Cloud) ensurePIPTagged(service *v1.Service, pip *armnetwork.PublicIPAddress) bool { configTags := parseTags(az.Tags, az.TagsMap) annotationTags := make(map[string]*string) if _, ok := service.Annotations[consts.ServiceAnnotationAzurePIPTags]; ok { @@ -3242,19 +3251,19 @@ func (az *Cloud) ensurePIPTagged(service *v1.Service, pip *network.PublicIPAddre } // reconcilePublicIPs reconciles the PublicIP resources similar to how the LB is reconciled. -func (az *Cloud) reconcilePublicIPs(ctx context.Context, clusterName string, service *v1.Service, lbName string, wantLb bool) ([]*network.PublicIPAddress, error) { +func (az *Cloud) reconcilePublicIPs(ctx context.Context, clusterName string, service *v1.Service, lbName string, wantLb bool) ([]*armnetwork.PublicIPAddress, error) { pipResourceGroup := az.getPublicIPAddressResourceGroup(service) - reconciledPIPs := []*network.PublicIPAddress{} + reconciledPIPs := []*armnetwork.PublicIPAddress{} pips, err := az.listPIP(ctx, pipResourceGroup, azcache.CacheReadTypeDefault) if err != nil { return nil, err } - pipsV4, pipsV6 := []network.PublicIPAddress{}, []network.PublicIPAddress{} + pipsV4, pipsV6 := []*armnetwork.PublicIPAddress{}, []*armnetwork.PublicIPAddress{} for _, pip := range pips { - if pip.PublicIPAddressPropertiesFormat == nil || pip.PublicIPAddressPropertiesFormat.PublicIPAddressVersion == "" || - pip.PublicIPAddressPropertiesFormat.PublicIPAddressVersion == network.IPv4 { + if pip.Properties == nil || pip.Properties.PublicIPAddressVersion == nil || + *pip.Properties.PublicIPAddressVersion == armnetwork.IPVersionIPv4 { pipsV4 = append(pipsV4, pip) } else { pipsV6 = append(pipsV6, pip) @@ -3284,14 +3293,14 @@ func (az *Cloud) reconcilePublicIPs(ctx context.Context, clusterName string, ser } // reconcilePublicIP reconciles the PublicIP resources similar to how the LB is reconciled with the specified IP family. -func (az *Cloud) reconcilePublicIP(ctx context.Context, pips []network.PublicIPAddress, clusterName string, service *v1.Service, lbName string, wantLb, isIPv6 bool) (*network.PublicIPAddress, error) { +func (az *Cloud) reconcilePublicIP(ctx context.Context, pips []*armnetwork.PublicIPAddress, clusterName string, service *v1.Service, lbName string, wantLb, isIPv6 bool) (*armnetwork.PublicIPAddress, error) { isInternal := requiresInternalLoadBalancer(service) serviceName := getServiceName(service) serviceIPTagRequest := getServiceIPTagRequestForPublicIP(service) pipResourceGroup := az.getPublicIPAddressResourceGroup(service) var ( - lb *network.LoadBalancer + lb *armnetwork.LoadBalancer desiredPipName string err error shouldPIPExisted bool @@ -3322,7 +3331,7 @@ func (az *Cloud) reconcilePublicIP(ctx context.Context, pips []network.PublicIPA pipCopy := *pip updateFuncs = append(updateFuncs, func() error { klog.V(2).Infof("reconcilePublicIP for service(%s): pip(%s), isIPv6(%v) - updating", serviceName, *pip.Name, isIPv6) - return az.CreateOrUpdatePIP(service, pipResourceGroup, pipCopy) + return az.CreateOrUpdatePIP(service, pipResourceGroup, &pipCopy) }) } errs := utilerrors.AggregateGoroutines(updateFuncs...) @@ -3344,7 +3353,7 @@ func (az *Cloud) reconcilePublicIP(ctx context.Context, pips []network.PublicIPA if !isInternal && wantLb { // Confirm desired public ip resource exists - var pip *network.PublicIPAddress + var pip *armnetwork.PublicIPAddress domainNameLabel, found := getPublicIPDomainNameLabel(service) errorIfPublicIPDoesNotExist := shouldPIPExisted && discoveredDesiredPublicIP && !deletedDesiredPublicIP if pip, err = az.ensurePublicIPExists(ctx, service, desiredPipName, domainNameLabel, clusterName, errorIfPublicIPDoesNotExist, found, isIPv6); err != nil { @@ -3359,7 +3368,7 @@ func (az *Cloud) reconcilePublicIP(ctx context.Context, pips []network.PublicIPA func (az *Cloud) getPublicIPUpdates( clusterName string, service *v1.Service, - pips []network.PublicIPAddress, + pips []*armnetwork.PublicIPAddress, wantLb bool, isInternal bool, desiredPipName string, @@ -3367,19 +3376,19 @@ func (az *Cloud) getPublicIPUpdates( serviceIPTagRequest serviceIPTagRequest, serviceAnnotationRequestsNamedPublicIP, isIPv6 bool, -) (bool, []*network.PublicIPAddress, bool, []*network.PublicIPAddress, error) { +) (bool, []*armnetwork.PublicIPAddress, bool, []*armnetwork.PublicIPAddress, error) { var ( err error discoveredDesiredPublicIP bool deletedDesiredPublicIP bool - pipsToBeDeleted []*network.PublicIPAddress - pipsToBeUpdated []*network.PublicIPAddress + pipsToBeDeleted []*armnetwork.PublicIPAddress + pipsToBeUpdated []*armnetwork.PublicIPAddress ) for i := range pips { pip := pips[i] - if pip.PublicIPAddressPropertiesFormat != nil && pip.PublicIPAddressPropertiesFormat.PublicIPAddressVersion != "" { - if (pip.PublicIPAddressPropertiesFormat.PublicIPAddressVersion == network.IPv4 && isIPv6) || - (pip.PublicIPAddressPropertiesFormat.PublicIPAddressVersion == network.IPv6 && !isIPv6) { + if pip.Properties != nil && pip.Properties.PublicIPAddressVersion != nil { + if (*pip.Properties.PublicIPAddressVersion == armnetwork.IPVersionIPv4 && isIPv6) || + (*pip.Properties.PublicIPAddressVersion == armnetwork.IPVersionIPv6 && !isIPv6) { continue } } @@ -3395,7 +3404,7 @@ func (az *Cloud) getPublicIPUpdates( // Now, let's perform additional analysis to determine if we should release the public ips we have found. // We can only let them go if (a) they are owned by this service and (b) they meet the criteria for deletion. - owns, isUserAssignedPIP := serviceOwnsPublicIP(service, &pip, clusterName) + owns, isUserAssignedPIP := serviceOwnsPublicIP(service, pip, clusterName) if owns { var ( serviceReferences = parsePIPServiceTag(ptr.To(getServiceFromPIPServiceTags(pip.Tags))) @@ -3403,19 +3412,19 @@ func (az *Cloud) getPublicIPUpdates( ) if !wantLb && !isUserAssignedPIP { klog.V(2).Infof("reconcilePublicIP for service(%s): unbinding the service from pip %s", serviceName, *pip.Name) - if serviceReferences, err = unbindServiceFromPIP(&pip, serviceName, isUserAssignedPIP); err != nil { + if serviceReferences, err = unbindServiceFromPIP(pip, serviceName, isUserAssignedPIP); err != nil { return false, nil, false, nil, err } dirtyPIP = true } if !isUserAssignedPIP { - if az.ensurePIPTagged(service, &pip) { + if az.ensurePIPTagged(service, pip) { dirtyPIP = true } } - if shouldReleaseExistingOwnedPublicIP(&pip, serviceReferences, wantLb, isInternal, isUserAssignedPIP, desiredPipName, serviceIPTagRequest) { + if shouldReleaseExistingOwnedPublicIP(pip, serviceReferences, wantLb, isInternal, isUserAssignedPIP, desiredPipName, serviceIPTagRequest) { // Then, release the public ip - pipsToBeDeleted = append(pipsToBeDeleted, &pip) + pipsToBeDeleted = append(pipsToBeDeleted, pip) // Flag if we deleted the desired public ip deletedDesiredPublicIP = deletedDesiredPublicIP || pipName == desiredPipName @@ -3430,7 +3439,7 @@ func (az *Cloud) getPublicIPUpdates( // Update tags of PIP only instead of deleting it. if !toBeDeleted && dirtyPIP { - pipsToBeUpdated = append(pipsToBeUpdated, &pip) + pipsToBeUpdated = append(pipsToBeUpdated, pip) } } } @@ -3442,10 +3451,10 @@ func (az *Cloud) getPublicIPUpdates( } // safeDeletePublicIP deletes public IP by removing its reference first. -func (az *Cloud) safeDeletePublicIP(ctx context.Context, service *v1.Service, pipResourceGroup string, pip *network.PublicIPAddress, lb *network.LoadBalancer) error { +func (az *Cloud) safeDeletePublicIP(ctx context.Context, service *v1.Service, pipResourceGroup string, pip *armnetwork.PublicIPAddress, lb *armnetwork.LoadBalancer) error { // Remove references if pip.IPConfiguration is not nil. - if pip.PublicIPAddressPropertiesFormat != nil && - pip.PublicIPAddressPropertiesFormat.IPConfiguration != nil { + if pip.Properties != nil && + pip.Properties.IPConfiguration != nil { // Fetch latest pip to check if the pip in the cache is stale. // In some cases the public IP to be deleted is still referencing // the frontend IP config on the LB. This is because the pip is @@ -3455,24 +3464,24 @@ func (az *Cloud) safeDeletePublicIP(ctx context.Context, service *v1.Service, pi klog.Errorf("safeDeletePublicIP: failed to get latest public IP %s/%s: %s", pipResourceGroup, *pip.Name, err.Error()) return err } - if ok && latestPIP.PublicIPAddressPropertiesFormat != nil && - latestPIP.PublicIPAddressPropertiesFormat.IPConfiguration != nil && - lb != nil && lb.LoadBalancerPropertiesFormat != nil && - lb.LoadBalancerPropertiesFormat.FrontendIPConfigurations != nil { - referencedLBRules := []network.SubResource{} + if ok && latestPIP.Properties != nil && + latestPIP.Properties.IPConfiguration != nil && + lb != nil && lb.Properties != nil && + lb.Properties.FrontendIPConfigurations != nil { + referencedLBRules := []*armnetwork.SubResource{} frontendIPConfigUpdated := false loadBalancerRuleUpdated := false // Check whether there are still frontend IP configurations referring to it. - ipConfigurationID := ptr.Deref(pip.PublicIPAddressPropertiesFormat.IPConfiguration.ID, "") + ipConfigurationID := ptr.Deref(pip.Properties.IPConfiguration.ID, "") if ipConfigurationID != "" { - lbFrontendIPConfigs := *lb.LoadBalancerPropertiesFormat.FrontendIPConfigurations + lbFrontendIPConfigs := lb.Properties.FrontendIPConfigurations for i := len(lbFrontendIPConfigs) - 1; i >= 0; i-- { config := lbFrontendIPConfigs[i] if strings.EqualFold(ipConfigurationID, ptr.Deref(config.ID, "")) { - if config.FrontendIPConfigurationPropertiesFormat != nil && - config.FrontendIPConfigurationPropertiesFormat.LoadBalancingRules != nil { - referencedLBRules = *config.FrontendIPConfigurationPropertiesFormat.LoadBalancingRules + if config.Properties != nil && + config.Properties.LoadBalancingRules != nil { + referencedLBRules = config.Properties.LoadBalancingRules } frontendIPConfigUpdated = true @@ -3482,7 +3491,7 @@ func (az *Cloud) safeDeletePublicIP(ctx context.Context, service *v1.Service, pi } if frontendIPConfigUpdated { - lb.LoadBalancerPropertiesFormat.FrontendIPConfigurations = &lbFrontendIPConfigs + lb.Properties.FrontendIPConfigurations = lbFrontendIPConfigs } } @@ -3493,8 +3502,8 @@ func (az *Cloud) safeDeletePublicIP(ctx context.Context, service *v1.Service, pi referencedLBRuleIDs.Insert(ptr.Deref(refer.ID, "")) } - if lb.LoadBalancerPropertiesFormat.LoadBalancingRules != nil { - lbRules := *lb.LoadBalancerPropertiesFormat.LoadBalancingRules + if lb.Properties.LoadBalancingRules != nil { + lbRules := lb.Properties.LoadBalancingRules for i := len(lbRules) - 1; i >= 0; i-- { ruleID := ptr.Deref(lbRules[i].ID, "") if ruleID != "" && referencedLBRuleIDs.Has(ruleID) { @@ -3504,7 +3513,7 @@ func (az *Cloud) safeDeletePublicIP(ctx context.Context, service *v1.Service, pi } if loadBalancerRuleUpdated { - lb.LoadBalancerPropertiesFormat.LoadBalancingRules = &lbRules + lb.Properties.LoadBalancingRules = lbRules } } } @@ -3531,10 +3540,10 @@ func (az *Cloud) safeDeletePublicIP(ctx context.Context, service *v1.Service, pi return nil } -func findRule(rules []network.LoadBalancingRule, rule network.LoadBalancingRule, wantLB bool) bool { +func findRule(rules []*armnetwork.LoadBalancingRule, rule *armnetwork.LoadBalancingRule, wantLB bool) bool { for _, existingRule := range rules { if strings.EqualFold(ptr.Deref(existingRule.Name, ""), ptr.Deref(rule.Name, "")) && - equalLoadBalancingRulePropertiesFormat(existingRule.LoadBalancingRulePropertiesFormat, rule.LoadBalancingRulePropertiesFormat, wantLB) { + equalLoadBalancingRulePropertiesFormat(existingRule.Properties, rule.Properties, wantLB) { return true } } @@ -3544,7 +3553,7 @@ func findRule(rules []network.LoadBalancingRule, rule network.LoadBalancingRule, // equalLoadBalancingRulePropertiesFormat checks whether the provided LoadBalancingRulePropertiesFormat are equal. // Note: only fields used in reconcileLoadBalancer are considered. // s: existing, t: target -func equalLoadBalancingRulePropertiesFormat(s *network.LoadBalancingRulePropertiesFormat, t *network.LoadBalancingRulePropertiesFormat, wantLB bool) bool { +func equalLoadBalancingRulePropertiesFormat(s *armnetwork.LoadBalancingRulePropertiesFormat, t *armnetwork.LoadBalancingRulePropertiesFormat, wantLB bool) bool { if s == nil || t == nil { return false } @@ -3554,7 +3563,7 @@ func equalLoadBalancingRulePropertiesFormat(s *network.LoadBalancingRuleProperti return false } - if reflect.DeepEqual(s.Protocol, network.TransportProtocolTCP) { + if reflect.DeepEqual(s.Protocol, to.Ptr(armnetwork.TransportProtocolTCP)) { properties = properties && reflect.DeepEqual(ptr.Deref(s.EnableTCPReset, false), ptr.Deref(t.EnableTCPReset, false)) } @@ -3573,7 +3582,7 @@ func equalLoadBalancingRulePropertiesFormat(s *network.LoadBalancingRuleProperti return properties } -func equalSubResource(s *network.SubResource, t *network.SubResource) bool { +func equalSubResource(s *armnetwork.SubResource, t *armnetwork.SubResource) bool { if s == nil && t == nil { return true } @@ -3630,8 +3639,8 @@ func getInternalSubnet(service *v1.Service) *string { return nil } -func ipInSubnet(ip string, subnet *network.Subnet) bool { - if subnet == nil || subnet.SubnetPropertiesFormat == nil { +func ipInSubnet(ip string, subnet *armnetwork.Subnet) bool { + if subnet == nil || subnet.Properties == nil { return false } netIP, err := netip.ParseAddr(ip) @@ -3639,17 +3648,17 @@ func ipInSubnet(ip string, subnet *network.Subnet) bool { klog.Errorf("ipInSubnet: failed to parse ip %s: %v", netIP, err) return false } - cidrs := make([]string, 0) - if subnet.AddressPrefix != nil { - cidrs = append(cidrs, *subnet.AddressPrefix) + cidrs := make([]*string, 0) + if subnet.Properties.AddressPrefix != nil { + cidrs = append(cidrs, subnet.Properties.AddressPrefix) } - if subnet.AddressPrefixes != nil { - cidrs = append(cidrs, *subnet.AddressPrefixes...) + if subnet.Properties.AddressPrefixes != nil { + cidrs = append(cidrs, subnet.Properties.AddressPrefixes...) } for _, cidr := range cidrs { - network, err := netip.ParsePrefix(cidr) + network, err := netip.ParsePrefix(*cidr) if err != nil { - klog.Errorf("ipInSubnet: failed to parse ip cidr %s: %v", cidr, err) + klog.Errorf("ipInSubnet: failed to parse ip cidr %s: %v", *cidr, err) continue } if network.Contains(netIP) { @@ -3686,20 +3695,20 @@ func useSharedSecurityRule(service *v1.Service) bool { // The service owns the pip if: // 1. The serviceName is included in the service tags of a system-created pip. // 2. The service LoadBalancerIP matches the IP address of a user-created pip. -func serviceOwnsPublicIP(service *v1.Service, pip *network.PublicIPAddress, clusterName string) (bool, bool) { +func serviceOwnsPublicIP(service *v1.Service, pip *armnetwork.PublicIPAddress, clusterName string) (bool, bool) { if service == nil || pip == nil { klog.Warningf("serviceOwnsPublicIP: nil service or public IP") return false, false } - if pip.PublicIPAddressPropertiesFormat == nil || ptr.Deref(pip.IPAddress, "") == "" { - klog.Warningf("serviceOwnsPublicIP: empty pip.IPAddress") + if pip.Properties == nil || ptr.Deref(pip.Properties.IPAddress, "") == "" { + klog.Warningf("serviceOwnsPublicIP: empty pip.Properties.IPAddress") return false, false } serviceName := getServiceName(service) - isIPv6 := pip.PublicIPAddressVersion == network.IPv6 + isIPv6 := ptr.Deref(pip.Properties.PublicIPAddressVersion, "") == armnetwork.IPVersionIPv6 if pip.Tags != nil { serviceTag := getServiceFromPIPServiceTags(pip.Tags) clusterTag := getClusterFromPIPClusterTags(pip.Tags) @@ -3730,15 +3739,15 @@ func serviceOwnsPublicIP(service *v1.Service, pip *network.PublicIPAddress, clus return isServiceSelectPIP(service, pip, isIPv6), true } -func isServiceLoadBalancerIPMatchesPIP(service *v1.Service, pip *network.PublicIPAddress, isIPV6 bool) bool { - return strings.EqualFold(ptr.Deref(pip.IPAddress, ""), getServiceLoadBalancerIP(service, isIPV6)) +func isServiceLoadBalancerIPMatchesPIP(service *v1.Service, pip *armnetwork.PublicIPAddress, isIPV6 bool) bool { + return strings.EqualFold(ptr.Deref(pip.Properties.IPAddress, ""), getServiceLoadBalancerIP(service, isIPV6)) } -func isServicePIPNameMatchesPIP(service *v1.Service, pip *network.PublicIPAddress, isIPV6 bool) bool { +func isServicePIPNameMatchesPIP(service *v1.Service, pip *armnetwork.PublicIPAddress, isIPV6 bool) bool { return strings.EqualFold(ptr.Deref(pip.Name, ""), getServicePIPName(service, isIPV6)) } -func isServiceSelectPIP(service *v1.Service, pip *network.PublicIPAddress, isIPV6 bool) bool { +func isServiceSelectPIP(service *v1.Service, pip *armnetwork.PublicIPAddress, isIPV6 bool) bool { return isServiceLoadBalancerIPMatchesPIP(service, pip, isIPV6) || isServicePIPNameMatchesPIP(service, pip, isIPV6) } @@ -3776,7 +3785,7 @@ func parsePIPServiceTag(serviceTag *string) []string { // 2. an error when the pip is nil // example: // "ns1/svc1" + ["ns1/svc1", "ns2/svc2"] = "ns1/svc1,ns2/svc2" -func bindServicesToPIP(pip *network.PublicIPAddress, incomingServiceNames []string, replace bool) (bool, error) { +func bindServicesToPIP(pip *armnetwork.PublicIPAddress, incomingServiceNames []string, replace bool) (bool, error) { if pip == nil { return false, fmt.Errorf("nil public IP") } @@ -3826,7 +3835,7 @@ func bindServicesToPIP(pip *network.PublicIPAddress, incomingServiceNames []stri // unbindServiceFromPIP removes the service name from the PIP's tag. // And returns the updated service names. func unbindServiceFromPIP( - pip *network.PublicIPAddress, + pip *armnetwork.PublicIPAddress, serviceName string, isUserAssignedPIP bool, ) ([]string, error) { @@ -3861,7 +3870,7 @@ func unbindServiceFromPIP( } // ensureLoadBalancerTagged ensures every load balancer in the resource group is tagged as configured -func (az *Cloud) ensureLoadBalancerTagged(lb *network.LoadBalancer) bool { +func (az *Cloud) ensureLoadBalancerTagged(lb *armnetwork.LoadBalancer) bool { if az.Tags == "" && len(az.TagsMap) == 0 { return false } @@ -3899,7 +3908,7 @@ func (az *Cloud) ensureSecurityGroupTagged(sg *armnetwork.SecurityGroup) bool { func (az *Cloud) getAzureLoadBalancerName( ctx context.Context, service *v1.Service, - existingLBs *[]network.LoadBalancer, + existingLBs []*armnetwork.LoadBalancer, clusterName, vmSetName string, isInternal bool, ) (string, error) { @@ -3936,7 +3945,7 @@ func (az *Cloud) getAzureLoadBalancerName( func getMostEligibleLBForService( currentLBName string, eligibleLBs []string, - existingLBs *[]network.LoadBalancer, + existingLBs []*armnetwork.LoadBalancer, isInternal bool, ) string { // 1. If the LB is eligible and being used, choose it. @@ -3948,16 +3957,15 @@ func getMostEligibleLBForService( // 2. If the LB is eligible and not created yet, choose it because it has the fewest rules. for _, eligibleLB := range eligibleLBs { var found bool - if existingLBs != nil { - for i := range *existingLBs { - existingLB := (*existingLBs)[i] - if strings.EqualFold(trimSuffixIgnoreCase(ptr.Deref(existingLB.Name, ""), consts.InternalLoadBalancerNameSuffix), eligibleLB) && - isInternalLoadBalancer(&existingLB) == isInternal { - found = true - break - } + for i := range existingLBs { + existingLB := (existingLBs)[i] + if strings.EqualFold(trimSuffixIgnoreCase(ptr.Deref(existingLB.Name, ""), consts.InternalLoadBalancerNameSuffix), eligibleLB) && + isInternalLoadBalancer(existingLB) == isInternal { + found = true + break } } + if !found { klog.V(4).Infof("getMostEligibleLBForService: choose %s as it is eligible and not existing", eligibleLB) return eligibleLB @@ -3967,17 +3975,15 @@ func getMostEligibleLBForService( // 3. If all eligible LBs are existing, choose the one with the fewest rules. var expectedLBName string ruleCount := 301 - if existingLBs != nil { - for i := range *existingLBs { - existingLB := (*existingLBs)[i] - if StringInSlice(trimSuffixIgnoreCase(ptr.Deref(existingLB.Name, ""), consts.InternalLoadBalancerNameSuffix), eligibleLBs) && - isInternalLoadBalancer(&existingLB) == isInternal { - if existingLB.LoadBalancerPropertiesFormat != nil && - existingLB.LoadBalancingRules != nil { - if len(*existingLB.LoadBalancingRules) < ruleCount { - ruleCount = len(*existingLB.LoadBalancingRules) - expectedLBName = ptr.Deref(existingLB.Name, "") - } + for i := range existingLBs { + existingLB := existingLBs[i] + if StringInSlice(trimSuffixIgnoreCase(ptr.Deref(existingLB.Name, ""), consts.InternalLoadBalancerNameSuffix), eligibleLBs) && + isInternalLoadBalancer(existingLB) == isInternal { + if existingLB.Properties != nil && + existingLB.Properties.LoadBalancingRules != nil { + if len(existingLB.Properties.LoadBalancingRules) < ruleCount { + ruleCount = len(existingLB.Properties.LoadBalancingRules) + expectedLBName = ptr.Deref(existingLB.Name, "") } } } @@ -4174,13 +4180,13 @@ func (az *Cloud) isLoadBalancerInUseByService(service *v1.Service, lbConfig conf // 2. The secondary services must have their loadBalancer IP set if they want to share the same config as the primary // service. Hence, it can be tracked by the loadBalancer IP. // If the IP version is not empty, which means it is the secondary Service, it returns IP version of the Service FIP. -func (az *Cloud) serviceOwnsFrontendIP(ctx context.Context, fip network.FrontendIPConfiguration, service *v1.Service) (bool, bool, network.IPVersion) { +func (az *Cloud) serviceOwnsFrontendIP(ctx context.Context, fip *armnetwork.FrontendIPConfiguration, service *v1.Service) (bool, bool, *armnetwork.IPVersion) { var isPrimaryService bool baseName := az.GetLoadBalancerName(ctx, "", service) - if strings.HasPrefix(ptr.Deref(fip.Name, ""), baseName) { + if fip != nil && strings.HasPrefix(ptr.Deref(fip.Name, ""), baseName) { klog.V(6).Infof("serviceOwnsFrontendIP: found primary service %s of the frontend IP config %s", service.Name, *fip.Name) isPrimaryService = true - return true, isPrimaryService, "" + return true, isPrimaryService, nil } loadBalancerIPs := getServiceLoadBalancerIPs(service) @@ -4194,16 +4200,16 @@ func (az *Cloud) serviceOwnsFrontendIP(ctx context.Context, fip network.Frontend pip, err := az.findMatchedPIP(ctx, "", pipName, pipResourceGroup) if err != nil { klog.Warningf("serviceOwnsFrontendIP: unexpected error when finding match public IP of the service %s with name %s: %v", service.Name, pipName, err) - return false, isPrimaryService, "" + return false, isPrimaryService, nil } - if publicIPOwnsFrontendIP(service, &fip, pip) { - return true, isPrimaryService, pip.PublicIPAddressPropertiesFormat.PublicIPAddressVersion + if publicIPOwnsFrontendIP(service, fip, pip) { + return true, isPrimaryService, pip.Properties.PublicIPAddressVersion } } } } // it is a must that the secondary services set the loadBalancer IP or pip name - return false, isPrimaryService, "" + return false, isPrimaryService, nil } // for external secondary service the public IP address should be checked @@ -4212,31 +4218,31 @@ func (az *Cloud) serviceOwnsFrontendIP(ctx context.Context, fip network.Frontend pip, err := az.findMatchedPIP(ctx, loadBalancerIP, "", pipResourceGroup) if err != nil { klog.Warningf("serviceOwnsFrontendIP: unexpected error when finding match public IP of the service %s with loadBalancerIP %s: %v", service.Name, loadBalancerIP, err) - return false, isPrimaryService, "" + return false, isPrimaryService, nil } - if publicIPOwnsFrontendIP(service, &fip, pip) { - return true, isPrimaryService, pip.PublicIPAddressPropertiesFormat.PublicIPAddressVersion + if publicIPOwnsFrontendIP(service, fip, pip) { + return true, isPrimaryService, pip.Properties.PublicIPAddressVersion } klog.V(6).Infof("serviceOwnsFrontendIP: the public IP with ID %s is being referenced by other service with public IP address %s "+ - "OR it is of incorrect IP version", *pip.ID, *pip.IPAddress) + "OR it is of incorrect IP version", *pip.ID, *pip.Properties.IPAddress) } - return false, isPrimaryService, "" + return false, isPrimaryService, nil } // for internal secondary service the private IP address on the frontend IP config should be checked - if fip.PrivateIPAddress == nil { - return false, isPrimaryService, "" + if fip.Properties.PrivateIPAddress == nil { + return false, isPrimaryService, nil } - privateIPAddrVersion := network.IPv4 - if net.ParseIP(*fip.PrivateIPAddress).To4() == nil { - privateIPAddrVersion = network.IPv6 + privateIPAddrVersion := to.Ptr(armnetwork.IPVersionIPv4) + if net.ParseIP(*fip.Properties.PrivateIPAddress).To4() == nil { + privateIPAddrVersion = to.Ptr(armnetwork.IPVersionIPv6) } privateIPEquals := false for _, loadBalancerIP := range loadBalancerIPs { - if strings.EqualFold(*fip.PrivateIPAddress, loadBalancerIP) { + if strings.EqualFold(*fip.Properties.PrivateIPAddress, loadBalancerIP) { privateIPEquals = true break } diff --git a/pkg/provider/azure_loadbalancer_accesscontrol_test.go b/pkg/provider/azure_loadbalancer_accesscontrol_test.go index cd853b50e7..c83d2da12c 100644 --- a/pkg/provider/azure_loadbalancer_accesscontrol_test.go +++ b/pkg/provider/azure_loadbalancer_accesscontrol_test.go @@ -18,7 +18,6 @@ package provider import ( "context" - "fmt" "io" "net/http" "strings" @@ -37,13 +36,12 @@ import ( "sigs.k8s.io/cloud-provider-azure/internal/testutil" "sigs.k8s.io/cloud-provider-azure/internal/testutil/fixture" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/loadbalancerclient/mock_loadbalancerclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/securitygroupclient/mock_securitygroupclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient/mockloadbalancerclient" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/log" "sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer" "sigs.k8s.io/cloud-provider-azure/pkg/provider/securitygroup" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" "sigs.k8s.io/cloud-provider-azure/pkg/util/iputil" ) @@ -66,7 +64,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) securityGroup = azureFx.SecurityGroup().Build() loadBalancer = azureFx.LoadBalancer().Build() @@ -84,7 +82,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -101,7 +99,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) securityGroup = azureFx.SecurityGroup().Build() loadBalancer = azureFx.LoadBalancer().Build() @@ -170,7 +168,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -186,7 +184,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) securityGroup = azureFx.SecurityGroup().Build() loadBalancer = azureFx.LoadBalancer().Build() @@ -255,7 +253,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -273,7 +271,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() securityGroup = azureFx.SecurityGroup().Build() @@ -329,7 +327,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -347,7 +345,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() securityGroup = azureFx.SecurityGroup().Build() @@ -410,7 +408,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -426,7 +424,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() securityGroup = azureFx.SecurityGroup().Build() @@ -484,7 +482,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -500,7 +498,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() securityGroup = azureFx.SecurityGroup().Build() @@ -567,7 +565,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -583,7 +581,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() securityGroup = azureFx.SecurityGroup().Build() @@ -664,7 +662,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -680,7 +678,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() securityGroup = azureFx.SecurityGroup().Build() @@ -746,7 +744,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -762,7 +760,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() securityGroup = azureFx.SecurityGroup().Build() @@ -838,7 +836,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -856,7 +854,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() loadBalancer = azureFx.LoadBalancer().Build() @@ -905,7 +903,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -921,7 +919,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() loadBalancer = azureFx.LoadBalancer().Build() @@ -967,7 +965,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -983,7 +981,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() loadBalancer = azureFx.LoadBalancer().Build() @@ -1033,7 +1031,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -1049,7 +1047,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() loadBalancer = azureFx.LoadBalancer().Build() @@ -1117,7 +1115,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -1133,7 +1131,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() loadBalancer = azureFx.LoadBalancer().Build() @@ -1184,7 +1182,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -1200,7 +1198,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() loadBalancer = azureFx.LoadBalancer().Build() @@ -1263,7 +1261,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -1279,7 +1277,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) loadBalancer = azureFx.LoadBalancer().Build() @@ -1360,7 +1358,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -1377,7 +1375,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) loadBalancer = azureFx.LoadBalancer().Build() @@ -1543,7 +1541,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -1559,7 +1557,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) loadBalancer = azureFx.LoadBalancer().Build() @@ -1673,7 +1671,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -1689,7 +1687,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) loadBalancer = azureFx.LoadBalancer().Build() @@ -1873,7 +1871,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -2119,7 +2117,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) kubeClient = fake.NewSimpleClientset(&sharedIPSvc, &svc) @@ -2153,7 +2151,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -2401,7 +2399,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) kubeClient = fake.NewSimpleClientset(&sharedIPSvc, &svc) @@ -2435,7 +2433,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -2453,7 +2451,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) loadBalancer = azureFx.LoadBalancer().Build() @@ -2623,7 +2621,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -2639,7 +2637,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) loadBalancer = azureFx.LoadBalancer().Build() @@ -2805,7 +2803,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -2821,7 +2819,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancer = azureFx.LoadBalancer().Build() allowedServiceTag = azureFx.ServiceTag() @@ -2931,7 +2929,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Times(1) loadBalancerClient.EXPECT(). Get(gomock.Any(), az.ResourceGroup, *loadBalancer.Name, gomock.Any()). - Return(loadBalancer, &retry.Error{HTTPStatusCode: http.StatusNotFound}). + Return(loadBalancer, &azcore.ResponseError{StatusCode: http.StatusNotFound}). Times(1) _, err := az.reconcileSecurityGroup(ctx, ClusterName, &svc, *loadBalancer.Name, nil, false) // deleting @@ -2994,21 +2992,19 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { assert.ErrorIs(t, err, expectedErr) }) - t.Run("when LoadBalancerClient.Get returns error", func(t *testing.T) { + t.Run("when NetworkClientFactory.GetLoadBalancerClient().Get returns error", func(t *testing.T) { var ( ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) svc = k8sFx.Service().Build() securityGroup = azureFx.SecurityGroup().Build() loadBalancer = azureFx.LoadBalancer().Build() ) defer ctrl.Finish() - expectedErr := &retry.Error{ - RawError: fmt.Errorf("foo"), - } + expectedErr := &azcore.ResponseError{ErrorCode: "foo"} securityGroupClient.EXPECT(). Get(gomock.Any(), az.ResourceGroup, az.SecurityGroupName). @@ -3021,7 +3017,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { _, err := az.reconcileSecurityGroup(ctx, ClusterName, &svc, *loadBalancer.Name, azureFx.LoadBalancer().Addresses(), EnsureLB) assert.Error(t, err) - assert.ErrorIs(t, err, expectedErr.RawError) + assert.ErrorIs(t, err, expectedErr) }) t.Run("when SecurityGroupClient.CreateOrUpdate returns error", func(t *testing.T) { @@ -3030,7 +3026,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() securityGroup = azureFx.SecurityGroup().Build() @@ -3057,7 +3053,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), @@ -3075,7 +3071,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { ctrl = gomock.NewController(t) az = GetTestCloud(ctrl) securityGroupClient = az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) - loadBalancerClient = az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + loadBalancerClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) loadBalancerBackendPool = az.LoadBalancerBackendPool.(*MockBackendPool) svc = k8sFx.Service().Build() securityGroup = azureFx.SecurityGroup().WithRules(azureFx.NNoiseSecurityRules(securitygroup.MaxSecurityRulesPerGroup)).Build() @@ -3092,7 +3088,7 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Return(loadBalancer, nil). Times(1) loadBalancerBackendPool.EXPECT(). - GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, &loadBalancer). + GetBackendPrivateIPs(gomock.Any(), ClusterName, &svc, loadBalancer). Return( azureFx.LoadBalancer().BackendPoolIPv4Addresses(), azureFx.LoadBalancer().BackendPoolIPv6Addresses(), diff --git a/pkg/provider/azure_loadbalancer_backendpool.go b/pkg/provider/azure_loadbalancer_backendpool.go index 38364f0f64..0bbbad0555 100644 --- a/pkg/provider/azure_loadbalancer_backendpool.go +++ b/pkg/provider/azure_loadbalancer_backendpool.go @@ -24,8 +24,7 @@ import ( "fmt" "strings" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" v1 "k8s.io/api/core/v1" cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" @@ -40,7 +39,7 @@ import ( type BackendPool interface { // EnsureHostsInPool ensures the nodes join the backend pool of the load balancer - EnsureHostsInPool(ctx context.Context, service *v1.Service, nodes []*v1.Node, backendPoolID, vmSetName, clusterName, lbName string, backendPool network.BackendAddressPool) error + EnsureHostsInPool(ctx context.Context, service *v1.Service, nodes []*v1.Node, backendPoolID, vmSetName, clusterName, lbName string, backendPool *armnetwork.BackendAddressPool) error // CleanupVMSetFromBackendPoolByCondition removes nodes of the unwanted vmSet from the lb backend pool. // This is needed in two scenarios: @@ -49,14 +48,14 @@ type BackendPool interface { // nodes from the primary agent pool to join the backend pool. // 2. When migrating from dedicated SLB to shared SLB (or vice versa), we should move the vmSet from // one SLB to another one. - CleanupVMSetFromBackendPoolByCondition(ctx context.Context, slb *network.LoadBalancer, service *v1.Service, nodes []*v1.Node, clusterName string, shouldRemoveVMSetFromSLB func(string) bool) (*network.LoadBalancer, error) + CleanupVMSetFromBackendPoolByCondition(ctx context.Context, slb *armnetwork.LoadBalancer, service *v1.Service, nodes []*v1.Node, clusterName string, shouldRemoveVMSetFromSLB func(string) bool) (*armnetwork.LoadBalancer, error) // ReconcileBackendPools creates the inbound backend pool if it is not existed, and removes nodes that are supposed to be // excluded from the load balancers. - ReconcileBackendPools(ctx context.Context, clusterName string, service *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) + ReconcileBackendPools(ctx context.Context, clusterName string, service *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) // GetBackendPrivateIPs returns the private IPs of LoadBalancer's backend pool - GetBackendPrivateIPs(ctx context.Context, clusterName string, service *v1.Service, lb *network.LoadBalancer) ([]string, []string) + GetBackendPrivateIPs(ctx context.Context, clusterName string, service *v1.Service, lb *armnetwork.LoadBalancer) ([]string, []string) } type backendPoolTypeNodeIPConfig struct { @@ -67,7 +66,7 @@ func newBackendPoolTypeNodeIPConfig(c *Cloud) BackendPool { return &backendPoolTypeNodeIPConfig{c} } -func (bc *backendPoolTypeNodeIPConfig) EnsureHostsInPool(ctx context.Context, service *v1.Service, nodes []*v1.Node, backendPoolID, vmSetName, _, _ string, _ network.BackendAddressPool) error { +func (bc *backendPoolTypeNodeIPConfig) EnsureHostsInPool(ctx context.Context, service *v1.Service, nodes []*v1.Node, backendPoolID, vmSetName, _, _ string, _ *armnetwork.BackendAddressPool) error { return bc.VMSet.EnsureHostsInPool(ctx, service, nodes, backendPoolID, vmSetName) } @@ -83,23 +82,23 @@ func isLBBackendPoolsExisting(lbBackendPoolNames map[bool]string, bpName *string return found, isIPv6 } -func (bc *backendPoolTypeNodeIPConfig) CleanupVMSetFromBackendPoolByCondition(ctx context.Context, slb *network.LoadBalancer, service *v1.Service, _ []*v1.Node, clusterName string, shouldRemoveVMSetFromSLB func(string) bool) (*network.LoadBalancer, error) { +func (bc *backendPoolTypeNodeIPConfig) CleanupVMSetFromBackendPoolByCondition(ctx context.Context, slb *armnetwork.LoadBalancer, service *v1.Service, _ []*v1.Node, clusterName string, shouldRemoveVMSetFromSLB func(string) bool) (*armnetwork.LoadBalancer, error) { v4Enabled, v6Enabled := getIPFamiliesEnabled(service) lbBackendPoolNames := getBackendPoolNames(clusterName) lbBackendPoolIDs := bc.getBackendPoolIDs(clusterName, ptr.Deref(slb.Name, "")) - newBackendPools := make([]network.BackendAddressPool, 0) - if slb.LoadBalancerPropertiesFormat != nil && slb.BackendAddressPools != nil { - newBackendPools = *slb.BackendAddressPools + newBackendPools := make([]*armnetwork.BackendAddressPool, 0) + if slb.Properties != nil && slb.Properties.BackendAddressPools != nil { + newBackendPools = slb.Properties.BackendAddressPools } - vmSetNameToBackendIPConfigurationsToBeDeleted := make(map[string][]network.InterfaceIPConfiguration) + vmSetNameToBackendIPConfigurationsToBeDeleted := make(map[string][]*armnetwork.InterfaceIPConfiguration) for j, bp := range newBackendPools { if found, _ := isLBBackendPoolsExisting(lbBackendPoolNames, bp.Name); found { klog.V(2).Infof("bc.CleanupVMSetFromBackendPoolByCondition: checking the backend pool %s from standard load balancer %s", ptr.Deref(bp.Name, ""), ptr.Deref(slb.Name, "")) - if bp.BackendAddressPoolPropertiesFormat != nil && bp.BackendIPConfigurations != nil { - for i := len(*bp.BackendIPConfigurations) - 1; i >= 0; i-- { - ipConf := (*bp.BackendIPConfigurations)[i] + if bp.Properties != nil && bp.Properties.BackendIPConfigurations != nil { + for i := len(bp.Properties.BackendIPConfigurations) - 1; i >= 0; i-- { + ipConf := (bp.Properties.BackendIPConfigurations)[i] ipConfigID := ptr.Deref(ipConf.ID, "") _, vmSetName, err := bc.VMSet.GetNodeNameByIPConfigurationID(ctx, ipConfigID) if err != nil && !errors.Is(err, cloudprovider.InstanceNotFound) { @@ -109,11 +108,11 @@ func (bc *backendPoolTypeNodeIPConfig) CleanupVMSetFromBackendPoolByCondition(ct if shouldRemoveVMSetFromSLB(vmSetName) { klog.V(2).Infof("bc.CleanupVMSetFromBackendPoolByCondition: found unwanted vmSet %s, decouple it from the LB", vmSetName) // construct a backendPool that only contains the IP config of the node to be deleted - interfaceIPConfigToBeDeleted := network.InterfaceIPConfiguration{ + interfaceIPConfigToBeDeleted := &armnetwork.InterfaceIPConfiguration{ ID: ptr.To(ipConfigID), } vmSetNameToBackendIPConfigurationsToBeDeleted[vmSetName] = append(vmSetNameToBackendIPConfigurationsToBeDeleted[vmSetName], interfaceIPConfigToBeDeleted) - *bp.BackendIPConfigurations = append((*bp.BackendIPConfigurations)[:i], (*bp.BackendIPConfigurations)[i+1:]...) + bp.Properties.BackendIPConfigurations = append((bp.Properties.BackendIPConfigurations)[:i], (bp.Properties.BackendIPConfigurations)[i+1:]...) } } } @@ -125,14 +124,14 @@ func (bc *backendPoolTypeNodeIPConfig) CleanupVMSetFromBackendPoolByCondition(ct for vmSetName := range vmSetNameToBackendIPConfigurationsToBeDeleted { shouldRefreshLB := false backendIPConfigurationsToBeDeleted := vmSetNameToBackendIPConfigurationsToBeDeleted[vmSetName] - backendpoolToBeDeleted := []network.BackendAddressPool{} + backendpoolToBeDeleted := []*armnetwork.BackendAddressPool{} lbBackendPoolIDsSlice := []string{} findBackendpoolToBeDeleted := func(isIPv6 bool) { lbBackendPoolIDsSlice = append(lbBackendPoolIDsSlice, lbBackendPoolIDs[isIPv6]) - backendpoolToBeDeleted = append(backendpoolToBeDeleted, network.BackendAddressPool{ + backendpoolToBeDeleted = append(backendpoolToBeDeleted, &armnetwork.BackendAddressPool{ ID: ptr.To(lbBackendPoolIDs[isIPv6]), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &backendIPConfigurationsToBeDeleted, + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: backendIPConfigurationsToBeDeleted, }, }) } @@ -143,7 +142,7 @@ func (bc *backendPoolTypeNodeIPConfig) CleanupVMSetFromBackendPoolByCondition(ct findBackendpoolToBeDeleted(consts.IPVersionIPv6) } // decouple the backendPool from the node - shouldRefreshLB, err := bc.VMSet.EnsureBackendPoolDeleted(ctx, service, lbBackendPoolIDsSlice, vmSetName, &backendpoolToBeDeleted, true) + shouldRefreshLB, err := bc.VMSet.EnsureBackendPoolDeleted(ctx, service, lbBackendPoolIDsSlice, vmSetName, backendpoolToBeDeleted, true) if err != nil { return nil, err } @@ -162,12 +161,12 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools( ctx context.Context, clusterName string, service *v1.Service, - lb *network.LoadBalancer, -) (bool, bool, *network.LoadBalancer, error) { - var newBackendPools []network.BackendAddressPool + lb *armnetwork.LoadBalancer, +) (bool, bool, *armnetwork.LoadBalancer, error) { + var newBackendPools []*armnetwork.BackendAddressPool var err error - if lb.BackendAddressPools != nil { - newBackendPools = *lb.BackendAddressPools + if lb.Properties.BackendAddressPools != nil { + newBackendPools = lb.Properties.BackendAddressPools } var backendPoolsCreated, backendPoolsUpdated, isOperationSucceeded, isMigration bool @@ -182,7 +181,7 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools( mc := metrics.NewMetricContext("services", "migrate_to_nic_based_backend_pool", bc.ResourceGroup, bc.getNetworkResourceSubscriptionID(), serviceName) - backendpoolToBeDeleted := []network.BackendAddressPool{} + backendpoolToBeDeleted := []*armnetwork.BackendAddressPool{} lbBackendPoolIDsSlice := []string{} for i := len(newBackendPools) - 1; i >= 0; i-- { bp := newBackendPools[i] @@ -199,25 +198,25 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools( // If the LB backend pool type is configured from nodeIP or podIP // to nodeIPConfiguration, we need to decouple the VM NICs from the LB // before attaching nodeIPs/podIPs to the LB backend pool. - if bp.BackendAddressPoolPropertiesFormat != nil && - bp.LoadBalancerBackendAddresses != nil && - len(*bp.LoadBalancerBackendAddresses) > 0 { + if bp.Properties != nil && + bp.Properties.LoadBalancerBackendAddresses != nil && + len(bp.Properties.LoadBalancerBackendAddresses) > 0 { if removeNodeIPAddressesFromBackendPool(bp, []string{}, true, false, false) { isMigration = true - bp.VirtualNetwork = nil + bp.Properties.VirtualNetwork = nil if err := bc.CreateOrUpdateLBBackendPool(ctx, lbName, bp); err != nil { klog.Errorf("bc.ReconcileBackendPools for service (%s): failed to cleanup IP based backend pool %s: %s", serviceName, lbBackendPoolNames[isIPv6], err.Error()) return false, false, nil, fmt.Errorf("bc.ReconcileBackendPools for service (%s): failed to cleanup IP based backend pool %s: %w", serviceName, lbBackendPoolNames[isIPv6], err) } newBackendPools[i] = bp - lb.BackendAddressPools = &newBackendPools + lb.Properties.BackendAddressPools = newBackendPools backendPoolsUpdated = true } } - var backendIPConfigurationsToBeDeleted, bipConfigNotFound, bipConfigExclude []network.InterfaceIPConfiguration - if bp.BackendAddressPoolPropertiesFormat != nil && bp.BackendIPConfigurations != nil { - for _, ipConf := range *bp.BackendIPConfigurations { + var backendIPConfigurationsToBeDeleted, bipConfigNotFound, bipConfigExclude []*armnetwork.InterfaceIPConfiguration + if bp.Properties != nil && bp.Properties.BackendIPConfigurations != nil { + for _, ipConf := range bp.Properties.BackendIPConfigurations { ipConfID := ptr.Deref(ipConf.ID, "") nodeName, _, err := bc.VMSet.GetNodeNameByIPConfigurationID(ctx, ipConfID) if err != nil { @@ -241,16 +240,16 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools( if shouldExcludeLoadBalancer { klog.V(2).Infof("bc.ReconcileBackendPools for service (%s): lb backendpool - found unwanted node %s, decouple it from the LB %s", serviceName, nodeName, lbName) // construct a backendPool that only contains the IP config of the node to be deleted - bipConfigExclude = append(bipConfigExclude, network.InterfaceIPConfiguration{ID: ptr.To(ipConfID)}) + bipConfigExclude = append(bipConfigExclude, &armnetwork.InterfaceIPConfiguration{ID: ptr.To(ipConfID)}) } } } - backendIPConfigurationsToBeDeleted = getBackendIPConfigurationsToBeDeleted(bp, bipConfigNotFound, bipConfigExclude) + backendIPConfigurationsToBeDeleted = getBackendIPConfigurationsToBeDeleted(*bp, bipConfigNotFound, bipConfigExclude) if len(backendIPConfigurationsToBeDeleted) > 0 { - backendpoolToBeDeleted = append(backendpoolToBeDeleted, network.BackendAddressPool{ + backendpoolToBeDeleted = append(backendpoolToBeDeleted, &armnetwork.BackendAddressPool{ ID: ptr.To(lbBackendPoolIDs[isIPv6]), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &backendIPConfigurationsToBeDeleted, + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: backendIPConfigurationsToBeDeleted, }, }) lbBackendPoolIDsSlice = append(lbBackendPoolIDsSlice, lbBackendPoolIDs[isIPv6]) @@ -261,7 +260,7 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools( } if len(backendpoolToBeDeleted) > 0 { // decouple the backendPool from the node - updated, err := bc.VMSet.EnsureBackendPoolDeleted(ctx, service, lbBackendPoolIDsSlice, vmSetName, &backendpoolToBeDeleted, false) + updated, err := bc.VMSet.EnsureBackendPoolDeleted(ctx, service, lbBackendPoolIDsSlice, vmSetName, backendpoolToBeDeleted, false) if err != nil { return false, false, nil, err } @@ -299,11 +298,11 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools( } func getBackendIPConfigurationsToBeDeleted( - bp network.BackendAddressPool, - bipConfigNotFound, bipConfigExclude []network.InterfaceIPConfiguration, -) []network.InterfaceIPConfiguration { - if bp.BackendAddressPoolPropertiesFormat == nil || bp.BackendIPConfigurations == nil { - return []network.InterfaceIPConfiguration{} + bp armnetwork.BackendAddressPool, + bipConfigNotFound, bipConfigExclude []*armnetwork.InterfaceIPConfiguration, +) []*armnetwork.InterfaceIPConfiguration { + if bp.Properties == nil || bp.Properties.BackendIPConfigurations == nil { + return []*armnetwork.InterfaceIPConfiguration{} } bipConfigNotFoundIDSet := utilsets.NewString() @@ -315,8 +314,8 @@ func getBackendIPConfigurationsToBeDeleted( bipConfigExcludeIDSet.Insert(ptr.Deref(ipConfig.ID, "")) } - var bipConfigToBeDeleted []network.InterfaceIPConfiguration - ipConfigs := *bp.BackendIPConfigurations + var bipConfigToBeDeleted []*armnetwork.InterfaceIPConfiguration + ipConfigs := bp.Properties.BackendIPConfigurations for i := len(ipConfigs) - 1; i >= 0; i-- { ipConfigID := ptr.Deref(ipConfigs[i].ID, "") if bipConfigNotFoundIDSet.Has(ipConfigID) { @@ -325,7 +324,7 @@ func getBackendIPConfigurationsToBeDeleted( } } - var unwantedIPConfigs []network.InterfaceIPConfiguration + var unwantedIPConfigs []*armnetwork.InterfaceIPConfiguration for _, ipConfig := range ipConfigs { ipConfigID := ptr.Deref(ipConfig.ID, "") if bipConfigExcludeIDSet.Has(ipConfigID) { @@ -339,20 +338,20 @@ func getBackendIPConfigurationsToBeDeleted( return append(bipConfigToBeDeleted, unwantedIPConfigs...) } -func (bc *backendPoolTypeNodeIPConfig) GetBackendPrivateIPs(ctx context.Context, clusterName string, service *v1.Service, lb *network.LoadBalancer) ([]string, []string) { +func (bc *backendPoolTypeNodeIPConfig) GetBackendPrivateIPs(ctx context.Context, clusterName string, service *v1.Service, lb *armnetwork.LoadBalancer) ([]string, []string) { serviceName := getServiceName(service) lbBackendPoolNames := getBackendPoolNames(clusterName) - if lb.LoadBalancerPropertiesFormat == nil || lb.LoadBalancerPropertiesFormat.BackendAddressPools == nil { + if lb.Properties == nil || lb.Properties.BackendAddressPools == nil { return nil, nil } backendPrivateIPv4s, backendPrivateIPv6s := utilsets.NewString(), utilsets.NewString() - for _, bp := range *lb.BackendAddressPools { + for _, bp := range lb.Properties.BackendAddressPools { found, _ := isLBBackendPoolsExisting(lbBackendPoolNames, bp.Name) if found { klog.V(10).Infof("bc.GetBackendPrivateIPs for service (%s): found wanted backendpool %s", serviceName, ptr.Deref(bp.Name, "")) - if bp.BackendAddressPoolPropertiesFormat != nil && bp.BackendIPConfigurations != nil { - for _, backendIPConfig := range *bp.BackendIPConfigurations { + if bp.Properties != nil && bp.Properties.BackendIPConfigurations != nil { + for _, backendIPConfig := range bp.Properties.BackendIPConfigurations { ipConfigID := ptr.Deref(backendIPConfig.ID, "") nodeName, _, err := bc.VMSet.GetNodeNameByIPConfigurationID(ctx, ipConfigID) if err != nil { @@ -403,7 +402,10 @@ func (az *Cloud) getVnetResourceID() string { ) } -func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(ctx context.Context, service *v1.Service, nodes []*v1.Node, _, _, clusterName, lbName string, backendPool network.BackendAddressPool) error { +func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(ctx context.Context, service *v1.Service, nodes []*v1.Node, _, _, clusterName, lbName string, backendPool *armnetwork.BackendAddressPool) error { + if backendPool == nil { + backendPool = &armnetwork.BackendAddressPool{} + } isIPv6 := isBackendPoolIPv6(ptr.Deref(backendPool.Name, "")) var ( @@ -435,18 +437,18 @@ func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(ctx context.Context, service lbBackendPoolName := bi.getBackendPoolNameForService(service, clusterName, isIPv6) if strings.EqualFold(ptr.Deref(backendPool.Name, ""), lbBackendPoolName) && - backendPool.BackendAddressPoolPropertiesFormat != nil { - if backendPool.LoadBalancerBackendAddresses == nil { - lbBackendPoolAddresses := make([]network.LoadBalancerBackendAddress, 0) - backendPool.LoadBalancerBackendAddresses = &lbBackendPoolAddresses + backendPool.Properties != nil { + if backendPool.Properties.LoadBalancerBackendAddresses == nil { + lbBackendPoolAddresses := make([]*armnetwork.LoadBalancerBackendAddress, 0) + backendPool.Properties.LoadBalancerBackendAddresses = lbBackendPoolAddresses } existingIPs := utilsets.NewString() - for _, loadBalancerBackendAddress := range *backendPool.LoadBalancerBackendAddresses { - if loadBalancerBackendAddress.LoadBalancerBackendAddressPropertiesFormat != nil && - loadBalancerBackendAddress.IPAddress != nil { - klog.V(4).Infof("bi.EnsureHostsInPool: found existing IP %s in the backend pool %s", ptr.Deref(loadBalancerBackendAddress.IPAddress, ""), lbBackendPoolName) - existingIPs.Insert(ptr.Deref(loadBalancerBackendAddress.IPAddress, "")) + for _, loadBalancerBackendAddress := range backendPool.Properties.LoadBalancerBackendAddresses { + if loadBalancerBackendAddress.Properties != nil && + loadBalancerBackendAddress.Properties.IPAddress != nil { + klog.V(4).Infof("bi.EnsureHostsInPool: found existing IP %s in the backend pool %s", ptr.Deref(loadBalancerBackendAddress.Properties.IPAddress, ""), lbBackendPoolName) + existingIPs.Insert(ptr.Deref(loadBalancerBackendAddress.Properties.IPAddress, "")) } } @@ -477,11 +479,11 @@ func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(ctx context.Context, service numOfAdd++ } } - changed = bi.addNodeIPAddressesToBackendPool(&backendPool, nodeIPsToBeAdded) + changed = bi.addNodeIPAddressesToBackendPool(backendPool, nodeIPsToBeAdded) var nodeIPsToBeDeleted []string - for _, loadBalancerBackendAddress := range *backendPool.LoadBalancerBackendAddresses { - ip := ptr.Deref(loadBalancerBackendAddress.IPAddress, "") + for _, loadBalancerBackendAddress := range backendPool.Properties.LoadBalancerBackendAddresses { + ip := ptr.Deref(loadBalancerBackendAddress.Properties.IPAddress, "") if !nodePrivateIPsSet.Has(ip) { klog.V(4).Infof("bi.EnsureHostsInPool: removing IP %s because it is deleted or should be excluded", ip) nodeIPsToBeDeleted = append(nodeIPsToBeDeleted, ip) @@ -513,11 +515,11 @@ func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(ctx context.Context, service return nil } -func (bi *backendPoolTypeNodeIP) CleanupVMSetFromBackendPoolByCondition(ctx context.Context, slb *network.LoadBalancer, _ *v1.Service, nodes []*v1.Node, clusterName string, shouldRemoveVMSetFromSLB func(string) bool) (*network.LoadBalancer, error) { +func (bi *backendPoolTypeNodeIP) CleanupVMSetFromBackendPoolByCondition(ctx context.Context, slb *armnetwork.LoadBalancer, _ *v1.Service, nodes []*v1.Node, clusterName string, shouldRemoveVMSetFromSLB func(string) bool) (*armnetwork.LoadBalancer, error) { lbBackendPoolNames := getBackendPoolNames(clusterName) - newBackendPools := make([]network.BackendAddressPool, 0) - if slb.LoadBalancerPropertiesFormat != nil && slb.BackendAddressPools != nil { - newBackendPools = *slb.BackendAddressPools + newBackendPools := make([]*armnetwork.BackendAddressPool, 0) + if slb.Properties != nil && slb.Properties.BackendAddressPools != nil { + newBackendPools = slb.Properties.BackendAddressPools } updatedPrivateIPs := map[bool]bool{} @@ -539,11 +541,11 @@ func (bi *backendPoolTypeNodeIP) CleanupVMSetFromBackendPoolByCondition(ctx cont } } - if bp.BackendAddressPoolPropertiesFormat != nil && bp.LoadBalancerBackendAddresses != nil { - for i := len(*bp.LoadBalancerBackendAddresses) - 1; i >= 0; i-- { - if (*bp.LoadBalancerBackendAddresses)[i].LoadBalancerBackendAddressPropertiesFormat != nil && - vmIPsToBeDeleted.Has(ptr.Deref((*bp.LoadBalancerBackendAddresses)[i].IPAddress, "")) { - *bp.LoadBalancerBackendAddresses = append((*bp.LoadBalancerBackendAddresses)[:i], (*bp.LoadBalancerBackendAddresses)[i+1:]...) + if bp.Properties != nil && bp.Properties.LoadBalancerBackendAddresses != nil { + for i := len(bp.Properties.LoadBalancerBackendAddresses) - 1; i >= 0; i-- { + if (bp.Properties.LoadBalancerBackendAddresses)[i].Properties != nil && + vmIPsToBeDeleted.Has(ptr.Deref((bp.Properties.LoadBalancerBackendAddresses)[i].Properties.IPAddress, "")) { + bp.Properties.LoadBalancerBackendAddresses = append((bp.Properties.LoadBalancerBackendAddresses)[:i], (bp.Properties.LoadBalancerBackendAddresses)[i+1:]...) updatedPrivateIPs[isIPv6] = true } } @@ -557,9 +559,9 @@ func (bi *backendPoolTypeNodeIP) CleanupVMSetFromBackendPoolByCondition(ctx cont } for isIPv6 := range updatedPrivateIPs { klog.V(2).Infof("bi.CleanupVMSetFromBackendPoolByCondition: updating lb %s since there are private IP updates", ptr.Deref(slb.Name, "")) - slb.BackendAddressPools = &newBackendPools + slb.Properties.BackendAddressPools = newBackendPools - for _, backendAddressPool := range *slb.BackendAddressPools { + for _, backendAddressPool := range slb.Properties.BackendAddressPools { if strings.EqualFold(lbBackendPoolNames[isIPv6], ptr.Deref(backendAddressPool.Name, "")) { if err := bi.CreateOrUpdateLBBackendPool(ctx, ptr.Deref(slb.Name, ""), backendAddressPool); err != nil { return nil, fmt.Errorf("bi.CleanupVMSetFromBackendPoolByCondition: "+ @@ -572,10 +574,10 @@ func (bi *backendPoolTypeNodeIP) CleanupVMSetFromBackendPoolByCondition(ctx cont return slb, nil } -func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(ctx context.Context, clusterName string, service *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { - var newBackendPools []network.BackendAddressPool - if lb.BackendAddressPools != nil { - newBackendPools = *lb.BackendAddressPools +func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(ctx context.Context, clusterName string, service *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { + var newBackendPools []*armnetwork.BackendAddressPool + if lb.Properties.BackendAddressPools != nil { + newBackendPools = lb.Properties.BackendAddressPools } var backendPoolsUpdated, shouldRefreshLB, isOperationSucceeded, isMigration, updated bool @@ -659,7 +661,7 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(ctx context.Context, clus // 3. Decouple vmss from the lb if the backend pool is empty when using // ip-based LB. Ref: https://github.com/kubernetes-sigs/cloud-provider-azure/pull/2829. klog.V(2).Infof("bi.ReconcileBackendPools for service (%s) and vmSet (%s): ensuring the LB is decoupled from the VMSet", serviceName, vmSetName) - shouldRefreshLB, err = bi.VMSet.EnsureBackendPoolDeleted(ctx, service, lbBackendPoolIDsSlice, vmSetName, lb.BackendAddressPools, true) + shouldRefreshLB, err = bi.VMSet.EnsureBackendPoolDeleted(ctx, service, lbBackendPoolIDsSlice, vmSetName, lb.Properties.BackendAddressPools, true) if err != nil { klog.Errorf("bi.ReconcileBackendPools for service (%s): failed to EnsureBackendPoolDeleted: %s", serviceName, err.Error()) return false, false, nil, err @@ -681,22 +683,22 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(ctx context.Context, clus } // delete the vnet in LoadBalancerBackendAddresses and ensure it is in the backend pool level var vnet string - if bp.BackendAddressPoolPropertiesFormat != nil { - if bp.VirtualNetwork == nil || - ptr.Deref(bp.VirtualNetwork.ID, "") == "" { - if bp.LoadBalancerBackendAddresses != nil { - for _, a := range *bp.LoadBalancerBackendAddresses { - if a.LoadBalancerBackendAddressPropertiesFormat != nil && - a.VirtualNetwork != nil { + if bp.Properties != nil { + if bp.Properties.VirtualNetwork == nil || + ptr.Deref(bp.Properties.VirtualNetwork.ID, "") == "" { + if bp.Properties.LoadBalancerBackendAddresses != nil { + for _, a := range bp.Properties.LoadBalancerBackendAddresses { + if a.Properties != nil && + a.Properties.VirtualNetwork != nil { if vnet == "" { - vnet = ptr.Deref(a.VirtualNetwork.ID, "") + vnet = ptr.Deref(a.Properties.VirtualNetwork.ID, "") } - a.VirtualNetwork = nil + a.Properties.VirtualNetwork = nil } } } if vnet != "" { - bp.VirtualNetwork = &network.SubResource{ + bp.Properties.VirtualNetwork = &armnetwork.SubResource{ ID: ptr.To(vnet), } updated = true @@ -705,7 +707,7 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(ctx context.Context, clus } if updated { - (*lb.BackendAddressPools)[i] = bp + (lb.Properties.BackendAddressPools)[i] = bp if err := bi.CreateOrUpdateLBBackendPool(ctx, lbName, bp); err != nil { return false, false, nil, fmt.Errorf("bi.ReconcileBackendPools for service (%s): lb backendpool - failed to update backend pool %s for load balancer %s: %w", serviceName, ptr.Deref(bp.Name, ""), lbName, err) } @@ -743,21 +745,21 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(ctx context.Context, clus return isBackendPoolPreConfigured, backendPoolsUpdated, lb, nil } -func (bi *backendPoolTypeNodeIP) GetBackendPrivateIPs(_ context.Context, clusterName string, service *v1.Service, lb *network.LoadBalancer) ([]string, []string) { +func (bi *backendPoolTypeNodeIP) GetBackendPrivateIPs(_ context.Context, clusterName string, service *v1.Service, lb *armnetwork.LoadBalancer) ([]string, []string) { serviceName := getServiceName(service) lbBackendPoolNames := bi.getBackendPoolNamesForService(service, clusterName) - if lb.LoadBalancerPropertiesFormat == nil || lb.LoadBalancerPropertiesFormat.BackendAddressPools == nil { + if lb.Properties == nil || lb.Properties.BackendAddressPools == nil { return nil, nil } backendPrivateIPv4s, backendPrivateIPv6s := utilsets.NewString(), utilsets.NewString() - for _, bp := range *lb.BackendAddressPools { + for _, bp := range lb.Properties.BackendAddressPools { found, _ := isLBBackendPoolsExisting(lbBackendPoolNames, bp.Name) if found { klog.V(10).Infof("bi.GetBackendPrivateIPs for service (%s): found wanted backendpool %s", serviceName, ptr.Deref(bp.Name, "")) - if bp.BackendAddressPoolPropertiesFormat != nil && bp.LoadBalancerBackendAddresses != nil { - for _, backendAddress := range *bp.LoadBalancerBackendAddresses { - ipAddress := backendAddress.IPAddress + if bp.Properties != nil && bp.Properties.LoadBalancerBackendAddresses != nil { + for _, backendAddress := range bp.Properties.LoadBalancerBackendAddresses { + ipAddress := backendAddress.Properties.IPAddress if ipAddress != nil { klog.V(2).Infof("bi.GetBackendPrivateIPs for service (%s): lb backendpool - found private IP %q", serviceName, *ipAddress) if utilnet.IsIPv4String(*ipAddress) { @@ -778,12 +780,12 @@ func (bi *backendPoolTypeNodeIP) GetBackendPrivateIPs(_ context.Context, cluster } // getBackendPoolNameForService returns all node names in the backend pool. -func (bi *backendPoolTypeNodeIP) getBackendPoolNodeNames(bp *network.BackendAddressPool) []string { +func (bi *backendPoolTypeNodeIP) getBackendPoolNodeNames(bp *armnetwork.BackendAddressPool) []string { nodeNames := utilsets.NewString() - if bp.BackendAddressPoolPropertiesFormat != nil && bp.LoadBalancerBackendAddresses != nil { - for _, backendAddress := range *bp.LoadBalancerBackendAddresses { - if backendAddress.LoadBalancerBackendAddressPropertiesFormat != nil { - ip := ptr.Deref(backendAddress.IPAddress, "") + if bp.Properties != nil && bp.Properties.LoadBalancerBackendAddresses != nil { + for _, backendAddress := range bp.Properties.LoadBalancerBackendAddresses { + if backendAddress.Properties != nil { + ip := ptr.Deref(backendAddress.Properties.IPAddress, "") nodeNames.Insert(bi.nodePrivateIPToNodeNameMap[ip]) } } @@ -791,7 +793,7 @@ func (bi *backendPoolTypeNodeIP) getBackendPoolNodeNames(bp *network.BackendAddr return nodeNames.UnsortedList() } -func newBackendPool(lb *network.LoadBalancer, isBackendPoolPreConfigured bool, preConfiguredBackendPoolLoadBalancerTypes, serviceName, lbBackendPoolName string) bool { +func newBackendPool(lb *armnetwork.LoadBalancer, isBackendPoolPreConfigured bool, preConfiguredBackendPoolLoadBalancerTypes, serviceName, lbBackendPoolName string) bool { if isBackendPoolPreConfigured { klog.V(2).Infof("newBackendPool for service (%s)(true): lb backendpool - PreConfiguredBackendPoolLoadBalancerTypes %s has been set but can not find corresponding backend pool %q, ignoring it", serviceName, @@ -800,68 +802,68 @@ func newBackendPool(lb *network.LoadBalancer, isBackendPoolPreConfigured bool, p isBackendPoolPreConfigured = false } - if lb.BackendAddressPools == nil { - lb.BackendAddressPools = &[]network.BackendAddressPool{} + if lb.Properties.BackendAddressPools == nil { + lb.Properties.BackendAddressPools = []*armnetwork.BackendAddressPool{} } - *lb.BackendAddressPools = append(*lb.BackendAddressPools, network.BackendAddressPool{ - Name: ptr.To(lbBackendPoolName), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{}, + lb.Properties.BackendAddressPools = append(lb.Properties.BackendAddressPools, &armnetwork.BackendAddressPool{ + Name: ptr.To(lbBackendPoolName), + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{}, }) // Always returns false return isBackendPoolPreConfigured } -func (az *Cloud) addNodeIPAddressesToBackendPool(backendPool *network.BackendAddressPool, nodeIPAddresses []string) bool { +func (az *Cloud) addNodeIPAddressesToBackendPool(backendPool *armnetwork.BackendAddressPool, nodeIPAddresses []string) bool { vnetID := az.getVnetResourceID() - if backendPool.BackendAddressPoolPropertiesFormat != nil { - if backendPool.VirtualNetwork == nil || - backendPool.VirtualNetwork.ID == nil { - backendPool.VirtualNetwork = &network.SubResource{ + if backendPool.Properties != nil { + if backendPool.Properties.VirtualNetwork == nil || + backendPool.Properties.VirtualNetwork.ID == nil { + backendPool.Properties.VirtualNetwork = &armnetwork.SubResource{ ID: &vnetID, } } } else { - backendPool.BackendAddressPoolPropertiesFormat = &network.BackendAddressPoolPropertiesFormat{ - VirtualNetwork: &network.SubResource{ + backendPool.Properties = &armnetwork.BackendAddressPoolPropertiesFormat{ + VirtualNetwork: &armnetwork.SubResource{ ID: &vnetID, }, } } - if backendPool.LoadBalancerBackendAddresses == nil { - lbBackendPoolAddresses := make([]network.LoadBalancerBackendAddress, 0) - backendPool.LoadBalancerBackendAddresses = &lbBackendPoolAddresses + if backendPool.Properties.LoadBalancerBackendAddresses == nil { + lbBackendPoolAddresses := make([]*armnetwork.LoadBalancerBackendAddress, 0) + backendPool.Properties.LoadBalancerBackendAddresses = lbBackendPoolAddresses } var changed bool - addresses := *backendPool.LoadBalancerBackendAddresses + addresses := backendPool.Properties.LoadBalancerBackendAddresses for _, ipAddress := range nodeIPAddresses { if !hasIPAddressInBackendPool(backendPool, ipAddress) { name := az.nodePrivateIPToNodeNameMap[ipAddress] klog.V(4).Infof("bi.addNodeIPAddressesToBackendPool: adding %s to the backend pool %s", ipAddress, ptr.Deref(backendPool.Name, "")) - addresses = append(addresses, network.LoadBalancerBackendAddress{ + addresses = append(addresses, &armnetwork.LoadBalancerBackendAddress{ Name: ptr.To(name), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To(ipAddress), }, }) changed = true } } - backendPool.LoadBalancerBackendAddresses = &addresses + backendPool.Properties.LoadBalancerBackendAddresses = addresses return changed } -func hasIPAddressInBackendPool(backendPool *network.BackendAddressPool, ipAddress string) bool { - if backendPool.LoadBalancerBackendAddresses == nil { +func hasIPAddressInBackendPool(backendPool *armnetwork.BackendAddressPool, ipAddress string) bool { + if backendPool.Properties.LoadBalancerBackendAddresses == nil { return false } - addresses := *backendPool.LoadBalancerBackendAddresses + addresses := backendPool.Properties.LoadBalancerBackendAddresses for _, address := range addresses { - if address.LoadBalancerBackendAddressPropertiesFormat != nil && - ptr.Deref(address.IPAddress, "") == ipAddress { + if address.Properties != nil && + ptr.Deref(address.Properties.IPAddress, "") == ipAddress { return true } } @@ -870,7 +872,7 @@ func hasIPAddressInBackendPool(backendPool *network.BackendAddressPool, ipAddres } func removeNodeIPAddressesFromBackendPool( - backendPool network.BackendAddressPool, + backendPool *armnetwork.BackendAddressPool, nodeIPAddresses []string, removeAll, UseMultipleStandardLoadBalancers, isNodeIP bool, ) bool { @@ -879,15 +881,15 @@ func removeNodeIPAddressesFromBackendPool( logger := klog.Background().WithName("removeNodeIPAddressFromBackendPool") - if backendPool.BackendAddressPoolPropertiesFormat == nil || - backendPool.LoadBalancerBackendAddresses == nil { + if backendPool.Properties == nil || + backendPool.Properties.LoadBalancerBackendAddresses == nil { return false } - addresses := *backendPool.LoadBalancerBackendAddresses + addresses := backendPool.Properties.LoadBalancerBackendAddresses for i := len(addresses) - 1; i >= 0; i-- { - if addresses[i].LoadBalancerBackendAddressPropertiesFormat != nil { - ipAddress := ptr.Deref((*backendPool.LoadBalancerBackendAddresses)[i].IPAddress, "") + if addresses[i].Properties != nil { + ipAddress := ptr.Deref((backendPool.Properties.LoadBalancerBackendAddresses)[i].Properties.IPAddress, "") if ipAddress == "" { if isNodeIP { logger.V(4).Info("LoadBalancerBackendAddress is not IP-based, removing", "LoadBalancerBackendAddress", ptr.Deref(addresses[i].Name, "")) @@ -907,7 +909,7 @@ func removeNodeIPAddressesFromBackendPool( } if removeAll { - backendPool.LoadBalancerBackendAddresses = &addresses + backendPool.Properties.LoadBalancerBackendAddresses = addresses return changed } @@ -917,7 +919,7 @@ func removeNodeIPAddressesFromBackendPool( klog.V(2).Info("removeNodeIPAddressFromBackendPool: the pool is empty or will be empty after removing the unwanted IP addresses, skipping the removal") changed = false } else if changed { - backendPool.LoadBalancerBackendAddresses = &addresses + backendPool.Properties.LoadBalancerBackendAddresses = addresses } return changed diff --git a/pkg/provider/azure_loadbalancer_backendpool_test.go b/pkg/provider/azure_loadbalancer_backendpool_test.go index 2675786e4a..fc7059dbf1 100644 --- a/pkg/provider/azure_loadbalancer_backendpool_test.go +++ b/pkg/provider/azure_loadbalancer_backendpool_test.go @@ -23,7 +23,9 @@ import ( "strings" "testing" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -34,10 +36,10 @@ import ( cloudprovider "k8s.io/cloud-provider" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient/mockloadbalancerclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/backendaddresspoolclient/mock_backendaddresspoolclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/loadbalancerclient/mock_loadbalancerclient" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) @@ -107,53 +109,53 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { testcases := []struct { desc string - backendPool network.BackendAddressPool + backendPool *armnetwork.BackendAddressPool multiSLBConfigs []config.MultipleStandardLoadBalancerConfiguration local bool notFound bool skip bool cache bool namespace string - expectedBackendPool network.BackendAddressPool + expectedBackendPool *armnetwork.BackendAddressPool }{ { desc: "IPv4", - backendPool: network.BackendAddressPool{ + backendPool: &armnetwork.BackendAddressPool{ Name: ptr.To("kubernetes"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.1"), }, }, { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.3"), }, }, }, }, }, - expectedBackendPool: network.BackendAddressPool{ + expectedBackendPool: &armnetwork.BackendAddressPool{ Name: ptr.To("kubernetes"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - VirtualNetwork: &network.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + VirtualNetwork: &armnetwork.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.1"), }, }, { Name: ptr.To("vmss-0"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.2"), }, }, { Name: ptr.To("vmss-2"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.4"), }, }, @@ -163,37 +165,37 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { }, { desc: "IPv6", - backendPool: network.BackendAddressPool{ + backendPool: &armnetwork.BackendAddressPool{ Name: ptr.To("kubernetes-IPv6"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("2001::1"), }, }, }, }, }, - expectedBackendPool: network.BackendAddressPool{ + expectedBackendPool: &armnetwork.BackendAddressPool{ Name: ptr.To("kubernetes-IPv6"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - VirtualNetwork: &network.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + VirtualNetwork: &armnetwork.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("2001::1"), }, }, { Name: ptr.To("vmss-0"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("2001::2"), }, }, { Name: ptr.To("vmss-2"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("2001::4"), }, }, @@ -203,12 +205,12 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { }, { desc: "should skip NIC-based backend pool when using multi-slb", - backendPool: network.BackendAddressPool{ + backendPool: &armnetwork.BackendAddressPool{ Name: ptr.To("kubernetes"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To(""), }, }, @@ -223,12 +225,12 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { }, }, }, - expectedBackendPool: network.BackendAddressPool{ + expectedBackendPool: &armnetwork.BackendAddressPool{ Name: ptr.To("kubernetes"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To(""), }, }, @@ -239,17 +241,17 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { }, { desc: "should add correct nodes to the pool and remove unwanted ones when using multi-slb", - backendPool: network.BackendAddressPool{ + backendPool: &armnetwork.BackendAddressPool{ Name: ptr.To("kubernetes"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.1"), }, }, { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.3"), }, }, @@ -264,14 +266,14 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { }, }, }, - expectedBackendPool: network.BackendAddressPool{ + expectedBackendPool: &armnetwork.BackendAddressPool{ Name: ptr.To("kubernetes"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - VirtualNetwork: &network.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + VirtualNetwork: &armnetwork.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { Name: ptr.To("vmss-2"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.4"), }, }, @@ -302,10 +304,10 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { { desc: "local service with its endpoint slice in cache", local: true, - backendPool: network.BackendAddressPool{ + backendPool: &armnetwork.BackendAddressPool{ Name: ptr.To("default-svc-1"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{}, + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{}, }, }, multiSLBConfigs: []config.MultipleStandardLoadBalancerConfiguration{ @@ -313,20 +315,20 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { Name: "kubernetes", }, }, - expectedBackendPool: network.BackendAddressPool{ + expectedBackendPool: &armnetwork.BackendAddressPool{ Name: ptr.To("default-svc-1"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - VirtualNetwork: &network.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + VirtualNetwork: &armnetwork.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { Name: ptr.To("vmss-0"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.2"), }, }, { Name: ptr.To("vmss-1"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.1"), }, }, @@ -338,10 +340,10 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { { desc: "local service in another namespace", local: true, - backendPool: network.BackendAddressPool{ + backendPool: &armnetwork.BackendAddressPool{ Name: ptr.To("another-svc-1"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{}, + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{}, }, }, multiSLBConfigs: []config.MultipleStandardLoadBalancerConfiguration{ @@ -349,20 +351,20 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { Name: "kubernetes", }, }, - expectedBackendPool: network.BackendAddressPool{ + expectedBackendPool: &armnetwork.BackendAddressPool{ Name: ptr.To("another-svc-1"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - VirtualNetwork: &network.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + VirtualNetwork: &armnetwork.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { Name: ptr.To("vmss-0"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.2"), }, }, { Name: ptr.To("vmss-2"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.4"), }, }, @@ -377,7 +379,7 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { for _, tc := range testcases { t.Run(tc.desc, func(t *testing.T) { az := GetTestCloud(ctrl) - az.LoadBalancerSku = consts.LoadBalancerSkuStandard + az.LoadBalancerSKU = consts.LoadBalancerSKUStandard az.nodePrivateIPToNodeNameMap = map[string]string{ "10.0.0.2": "vmss-0", "2001::2": "vmss-0", @@ -390,7 +392,7 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { if len(tc.multiSLBConfigs) > 0 { az.MultipleStandardLoadBalancerConfigurations = tc.multiSLBConfigs - az.LoadBalancerSku = consts.LoadBalancerSkuStandard + az.LoadBalancerSKU = consts.LoadBalancerSKUStandard az.nodePrivateIPToNodeNameMap = map[string]string{ "10.0.0.2": "vmss-0", "2001::2": "vmss-0", @@ -401,11 +403,10 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { } } - lbClient := mockloadbalancerclient.NewMockInterface(ctrl) + backendpoolClient := az.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) if !tc.notFound && !tc.skip { - lbClient.EXPECT().CreateOrUpdateBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) + backendpoolClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil) } - az.LoadBalancerClient = lbClient if !tc.notFound { az.localServiceNameToServiceInfoMap.Store("default/svc-1", &serviceInfo{lbName: "kubernetes"}) } @@ -438,7 +439,11 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { } err := bi.EnsureHostsInPool(context.Background(), &service, nodes, "", "", "kubernetes", "kubernetes", tc.backendPool) assert.NoError(t, err) - assert.Equal(t, tc.expectedBackendPool, tc.backendPool) + if tc.expectedBackendPool != nil { + assert.Equal(t, *tc.expectedBackendPool, *tc.backendPool) + } else { + assert.Nil(t, tc.backendPool) + } }) } } @@ -493,9 +498,9 @@ func TestIsLBBackendPoolsExisting(t *testing.T) { func TestCleanupVMSetFromBackendPoolByConditionNodeIPConfig(t *testing.T) { ctrl := gomock.NewController(t) - defer ctrl.Finish() + ctrl.Finish() cloud := GetTestCloud(ctrl) - cloud.LoadBalancerSku = consts.LoadBalancerSkuStandard + cloud.LoadBalancerSKU = consts.LoadBalancerSKUStandard service := getTestService("test", v1.ProtocolTCP, nil, false, 80) lb := buildDefaultTestLB("testCluster", []string{ "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1", @@ -509,14 +514,14 @@ func TestCleanupVMSetFromBackendPoolByConditionNodeIPConfig(t *testing.T) { mockVMSet.EXPECT().GetPrimaryVMSetName().Return("agentpool1-availabilitySet-00000000").AnyTimes() cloud.VMSet = mockVMSet - expectedLB := network.LoadBalancer{ + expectedLB := &armnetwork.LoadBalancer{ Name: ptr.To("testCluster"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("testCluster"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1"), }, @@ -527,9 +532,8 @@ func TestCleanupVMSetFromBackendPoolByConditionNodeIPConfig(t *testing.T) { }, } - mockLBClient := mockloadbalancerclient.NewMockInterface(ctrl) + mockLBClient := cloud.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedLB, nil) - cloud.LoadBalancerClient = mockLBClient bc := newBackendPoolTypeNodeIPConfig(cloud) @@ -538,14 +542,14 @@ func TestCleanupVMSetFromBackendPoolByConditionNodeIPConfig(t *testing.T) { } cleanedLB, err := bc.CleanupVMSetFromBackendPoolByCondition(context.TODO(), &lb, &service, nil, testClusterName, shouldRemoveVMSetFromSLB) assert.NoError(t, err) - assert.Equal(t, expectedLB, *cleanedLB) + assert.Equal(t, *expectedLB, *cleanedLB) } func TestCleanupVMSetFromBackendPoolByConditionNodeIP(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() cloud := GetTestCloud(ctrl) - cloud.LoadBalancerSku = consts.LoadBalancerSkuStandard + cloud.LoadBalancerSKU = consts.LoadBalancerSKUStandard cloud.LoadBalancerBackendPoolConfigurationType = consts.LoadBalancerBackendPoolConfigurationTypeNodeIP service := getTestService("test", v1.ProtocolTCP, nil, false, 80) clusterName := "testCluster" @@ -566,9 +570,8 @@ func TestCleanupVMSetFromBackendPoolByConditionNodeIP(t *testing.T) { }, } - lbClient := mockloadbalancerclient.NewMockInterface(ctrl) - lbClient.EXPECT().CreateOrUpdateBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) - cloud.LoadBalancerClient = lbClient + backendpoolClient := cloud.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) + backendpoolClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil) bi := newBackendPoolTypeNodeIP(cloud) @@ -585,7 +588,7 @@ func TestCleanupVMSetFromBackendPoolForInstanceNotFound(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() cloud := GetTestCloud(ctrl) - cloud.LoadBalancerSku = consts.LoadBalancerSkuStandard + cloud.LoadBalancerSKU = consts.LoadBalancerSKUStandard cloud.PrimaryAvailabilitySetName = "agentpool1-availabilitySet-00000000" clusterName := "testCluster" service := getTestService("test", v1.ProtocolTCP, nil, false, 80) @@ -601,14 +604,14 @@ func TestCleanupVMSetFromBackendPoolForInstanceNotFound(t *testing.T) { mockVMSet.EXPECT().GetPrimaryVMSetName().Return("agentpool1-availabilitySet-00000000").AnyTimes() cloud.VMSet = mockVMSet - expectedLB := network.LoadBalancer{ + expectedLB := armnetwork.LoadBalancer{ Name: ptr.To("testCluster"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("testCluster"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1"), }, @@ -631,7 +634,7 @@ func TestCleanupVMSetFromBackendPoolForInstanceNotFound(t *testing.T) { func TestReconcileBackendPoolsNodeIPConfig(t *testing.T) { ctrl := gomock.NewController(t) - defer ctrl.Finish() + az := GetTestCloud(ctrl) lb := buildDefaultTestLB(testClusterName, []string{ "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1", @@ -644,12 +647,10 @@ func TestReconcileBackendPoolsNodeIPConfig(t *testing.T) { mockVMSet.EXPECT().EnsureBackendPoolDeleted(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(true, nil) mockVMSet.EXPECT().GetPrimaryVMSetName().Return("k8s-agentpool1-00000000") - mockLBClient := mockloadbalancerclient.NewMockInterface(ctrl) - mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(network.LoadBalancer{}, nil) + mockLBClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.LoadBalancer{}, nil) - az := GetTestCloud(ctrl) az.VMSet = mockVMSet - az.LoadBalancerClient = mockLBClient az.nodeInformerSynced = func() bool { return true } az.excludeLoadBalancerNodes = utilsets.NewString("k8s-agentpool1-00000000") @@ -657,10 +658,12 @@ func TestReconcileBackendPoolsNodeIPConfig(t *testing.T) { svc := getTestService("test", v1.ProtocolTCP, nil, false, 80) _, _, _, err := bc.ReconcileBackendPools(context.TODO(), testClusterName, &svc, &lb) assert.NoError(t, err) + ctrl.Finish() - lb = network.LoadBalancer{ - Name: ptr.To(testClusterName), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, + ctrl = gomock.NewController(t) + lb = armnetwork.LoadBalancer{ + Name: ptr.To(testClusterName), + Properties: &armnetwork.LoadBalancerPropertiesFormat{}, } az = GetTestCloud(ctrl) az.PreConfiguredBackendPoolLoadBalancerTypes = consts.PreConfiguredBackendPoolLoadBalancerTypesAll @@ -670,6 +673,7 @@ func TestReconcileBackendPoolsNodeIPConfig(t *testing.T) { assert.False(t, preConfigured) assert.Equal(t, lb, *updatedLB) assert.True(t, changed) + ctrl.Finish() } func TestReconcileBackendPoolsNodeIPConfigRemoveIPConfig(t *testing.T) { @@ -735,14 +739,13 @@ func TestReconcileBackendPoolsNodeIPConfigPreConfigured(t *testing.T) { func TestReconcileBackendPoolsNodeIPToIPConfig(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() + az := GetTestCloud(ctrl) lb := buildLBWithVMIPs(testClusterName, []string{"10.0.0.1", "10.0.0.2"}) - mockLBClient := mockloadbalancerclient.NewMockInterface(ctrl) - mockLBClient.EXPECT().CreateOrUpdateBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(retry.NewError(false, fmt.Errorf("create or update LB backend pool error"))) - mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(network.LoadBalancer{}, nil) - - az := GetTestCloud(ctrl) - az.LoadBalancerClient = mockLBClient + mockBPClient := az.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) + mockBPClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, fmt.Errorf("create or update LB backend pool error")) + mockLBClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil) bc := newBackendPoolTypeNodeIPConfig(az) svc := getTestService("test", v1.ProtocolTCP, nil, false, 80) @@ -750,11 +753,11 @@ func TestReconcileBackendPoolsNodeIPToIPConfig(t *testing.T) { assert.Contains(t, err.Error(), "create or update LB backend pool error") lb = buildLBWithVMIPs(testClusterName, []string{"10.0.0.1", "10.0.0.2"}) - mockLBClient.EXPECT().CreateOrUpdateBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) + mockBPClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil) _, _, updatedLB, err := bc.ReconcileBackendPools(context.TODO(), testClusterName, &svc, lb) assert.NoError(t, err) - assert.Equal(t, network.LoadBalancer{}, *updatedLB) - assert.Empty(t, (*lb.BackendAddressPools)[0].LoadBalancerBackendAddresses) + assert.Nil(t, updatedLB) + assert.Empty(t, (lb.Properties.BackendAddressPools)[0].Properties.LoadBalancerBackendAddresses) } func TestReconcileBackendPoolsNodeIP(t *testing.T) { @@ -791,15 +794,15 @@ func TestReconcileBackendPoolsNodeIP(t *testing.T) { }, } - bp := network.BackendAddressPool{ + bp := armnetwork.BackendAddressPool{ Name: ptr.To("kubernetes"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - VirtualNetwork: &network.SubResource{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + VirtualNetwork: &armnetwork.SubResource{ ID: ptr.To("vnet"), }, - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.2"), }, }, @@ -813,22 +816,22 @@ func TestReconcileBackendPoolsNodeIP(t *testing.T) { az.excludeLoadBalancerNodes = utilsets.NewString("vmss-0") az.nodePrivateIPs["vmss-0"] = utilsets.NewString("10.0.0.1") - lbClient := mockloadbalancerclient.NewMockInterface(ctrl) - lbClient.EXPECT().CreateOrUpdateBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), bp, gomock.Any()).Return(nil) - lbClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(network.LoadBalancer{}, nil) - az.LoadBalancerClient = lbClient + lbClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + bpClient := az.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) + bpClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), bp).Return(nil, nil) + lbClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.LoadBalancer{}, nil) bi := newBackendPoolTypeNodeIP(az) service := getTestService("test", v1.ProtocolTCP, nil, false, 80) _, _, updatedLB, err := bi.ReconcileBackendPools(context.TODO(), "kubernetes", &service, lb) - assert.Equal(t, network.LoadBalancer{}, *updatedLB) + assert.Equal(t, armnetwork.LoadBalancer{}, *updatedLB) assert.NoError(t, err) - lb = &network.LoadBalancer{ - Name: ptr.To(testClusterName), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, + lb = &armnetwork.LoadBalancer{ + Name: ptr.To(testClusterName), + Properties: &armnetwork.LoadBalancerPropertiesFormat{}, } az = GetTestCloud(ctrl) az.PreConfiguredBackendPoolLoadBalancerTypes = consts.PreConfiguredBackendPoolLoadBalancerTypesAll @@ -843,6 +846,7 @@ func TestReconcileBackendPoolsNodeIP(t *testing.T) { func TestReconcileBackendPoolsNodeIPEmptyPool(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() + az := GetTestCloud(ctrl) lb := buildLBWithVMIPs("kubernetes", []string{}) @@ -850,19 +854,17 @@ func TestReconcileBackendPoolsNodeIPEmptyPool(t *testing.T) { mockVMSet.EXPECT().EnsureBackendPoolDeleted(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(true, nil) mockVMSet.EXPECT().GetPrimaryVMSetName().Return("k8s-agentpool1-00000000") - mockLBClient := mockloadbalancerclient.NewMockInterface(ctrl) - mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(network.LoadBalancer{}, nil) + mockLBClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.LoadBalancer{}, nil) - az := GetTestCloud(ctrl) az.LoadBalancerBackendPoolConfigurationType = consts.LoadBalancerBackendPoolConfigurationTypeNodeIP az.VMSet = mockVMSet - az.LoadBalancerClient = mockLBClient bi := newBackendPoolTypeNodeIP(az) service := getTestService("test", v1.ProtocolTCP, nil, false, 80) _, _, updatedLB, err := bi.ReconcileBackendPools(context.TODO(), "kubernetes", &service, lb) - assert.Equal(t, network.LoadBalancer{}, *updatedLB) + assert.Equal(t, armnetwork.LoadBalancer{}, *updatedLB) assert.NoError(t, err) } @@ -913,18 +915,18 @@ func TestReconcileBackendPoolsNodeIPConfigToIP(t *testing.T) { "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool2-00000000-nic-1/ipConfigurations/ipconfig1", }) mockVMSet.EXPECT().EnsureBackendPoolDeleted(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(false, nil) - mockLBClient := mockloadbalancerclient.NewMockInterface(ctrl) - mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(network.LoadBalancer{}, nil) - az.LoadBalancerClient = mockLBClient + mockLBClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.LoadBalancer{}, nil) _, _, updatedLB, err := bi.ReconcileBackendPools(context.TODO(), testClusterName, &svc, &lb) assert.NoError(t, err) - assert.Equal(t, network.LoadBalancer{}, *updatedLB) - assert.Empty(t, (*lb.BackendAddressPools)[0].LoadBalancerBackendAddresses) + assert.Equal(t, armnetwork.LoadBalancer{}, *updatedLB) + assert.Empty(t, (lb.Properties.BackendAddressPools)[0].Properties.LoadBalancerBackendAddresses) } func TestReconcileBackendPoolsNodeIPConfigToIPWithMigrationAPI(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() + az := GetTestCloud(ctrl) lb := buildDefaultTestLB(testClusterName, []string{ "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1", @@ -935,14 +937,15 @@ func TestReconcileBackendPoolsNodeIPConfigToIPWithMigrationAPI(t *testing.T) { mockVMSet.EXPECT().EnsureBackendPoolDeleted(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(true, nil) mockVMSet.EXPECT().GetPrimaryVMSetName().Return("k8s-agentpool1-00000000").AnyTimes() - mockLBClient := mockloadbalancerclient.NewMockInterface(ctrl) - mockLBClient.EXPECT().MigrateToIPBasedBackendPool(gomock.Any(), gomock.Any(), "testCluster", []string{"testCluster"}).Return(retry.NewError(false, errors.New("error"))) - - az := GetTestCloud(ctrl) + mockLBClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockBPClient := az.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) + mockLBClient.EXPECT().MigrateToIPBased(gomock.Any(), gomock.Any(), "testCluster", &armnetwork.LoadBalancersClientMigrateToIPBasedOptions{ + Parameters: &armnetwork.MigrateLoadBalancerToIPBasedRequest{ + Pools: to.SliceOfPtrs("testCluster")}, + }).Return(armnetwork.LoadBalancersClientMigrateToIPBasedResponse{}, &azcore.ResponseError{ErrorCode: "error"}) az.VMSet = mockVMSet - az.LoadBalancerClient = mockLBClient az.EnableMigrateToIPBasedBackendPoolAPI = true - az.LoadBalancerSku = "standard" + az.LoadBalancerSKU = "standard" az.MultipleStandardLoadBalancerConfigurations = []config.MultipleStandardLoadBalancerConfiguration{{Name: "kubernetes"}} bi := newBackendPoolTypeNodeIP(az) @@ -951,26 +954,29 @@ func TestReconcileBackendPoolsNodeIPConfigToIPWithMigrationAPI(t *testing.T) { assert.Error(t, err) assert.Contains(t, err.Error(), "error") - mockLBClient.EXPECT().MigrateToIPBasedBackendPool(gomock.Any(), gomock.Any(), "testCluster", []string{"testCluster"}).Return(nil) - bps := buildLBWithVMIPs(testClusterName, []string{"1.2.3.4", "2.3.4.5"}).BackendAddressPools - mockLBClient.EXPECT().GetLBBackendPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return((*bps)[0], nil) - mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(network.LoadBalancer{}, nil) + mockLBClient.EXPECT().MigrateToIPBased(gomock.Any(), gomock.Any(), "testCluster", &armnetwork.LoadBalancersClientMigrateToIPBasedOptions{ + Parameters: &armnetwork.MigrateLoadBalancerToIPBasedRequest{ + Pools: to.SliceOfPtrs("testCluster")}, + }).Return(armnetwork.LoadBalancersClientMigrateToIPBasedResponse{}, nil) + bps := buildLBWithVMIPs(testClusterName, []string{"1.2.3.4", "2.3.4.5"}).Properties.BackendAddressPools + mockBPClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return((bps)[0], nil) + mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.LoadBalancer{}, nil) _, _, updatedLB, err := bi.ReconcileBackendPools(context.TODO(), testClusterName, &svc, &lb) assert.NoError(t, err) - assert.Equal(t, network.LoadBalancer{}, *updatedLB) + assert.Equal(t, armnetwork.LoadBalancer{}, *updatedLB) } -func buildTestLoadBalancerBackendPoolWithIPs(name string, ips []string) network.BackendAddressPool { - backendPool := network.BackendAddressPool{ +func buildTestLoadBalancerBackendPoolWithIPs(name string, ips []string) *armnetwork.BackendAddressPool { + backendPool := &armnetwork.BackendAddressPool{ Name: &name, - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{}, + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{}, }, } for _, ip := range ips { ip := ip - *backendPool.LoadBalancerBackendAddresses = append(*backendPool.LoadBalancerBackendAddresses, network.LoadBalancerBackendAddress{ - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + backendPool.Properties.LoadBalancerBackendAddresses = append(backendPool.Properties.LoadBalancerBackendAddresses, &armnetwork.LoadBalancerBackendAddress{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: &ip, }, }) @@ -1065,7 +1071,7 @@ func TestGetBackendPrivateIPsNodeIP(t *testing.T) { svc := getTestService("svc1", "TCP", nil, false) // isIPv6 doesn't matter. testcases := []struct { desc string - lb *network.LoadBalancer + lb *armnetwork.LoadBalancer expectedIPv4 []string expectedIPv6 []string }{ @@ -1103,16 +1109,16 @@ func TestGetBackendPrivateIPsNodeIP(t *testing.T) { func TestGetBackendIPConfigurationsToBeDeleted(t *testing.T) { for _, tc := range []struct { description string - bipConfigNotFound, bipConfigExclude []network.InterfaceIPConfiguration + bipConfigNotFound, bipConfigExclude []*armnetwork.InterfaceIPConfiguration expected map[string]bool }{ { description: "should ignore excluded IP configurations if the backend pool will be empty after removing IP configurations of not found vms", - bipConfigNotFound: []network.InterfaceIPConfiguration{ + bipConfigNotFound: []*armnetwork.InterfaceIPConfiguration{ {ID: ptr.To("ipconfig1")}, {ID: ptr.To("ipconfig2")}, }, - bipConfigExclude: []network.InterfaceIPConfiguration{ + bipConfigExclude: []*armnetwork.InterfaceIPConfiguration{ {ID: ptr.To("ipconfig3")}, }, expected: map[string]bool{ @@ -1122,10 +1128,10 @@ func TestGetBackendIPConfigurationsToBeDeleted(t *testing.T) { }, { description: "should remove both not found and excluded vms", - bipConfigNotFound: []network.InterfaceIPConfiguration{ + bipConfigNotFound: []*armnetwork.InterfaceIPConfiguration{ {ID: ptr.To("ipconfig1")}, }, - bipConfigExclude: []network.InterfaceIPConfiguration{ + bipConfigExclude: []*armnetwork.InterfaceIPConfiguration{ {ID: ptr.To("ipconfig3")}, }, expected: map[string]bool{ @@ -1135,12 +1141,12 @@ func TestGetBackendIPConfigurationsToBeDeleted(t *testing.T) { }, { description: "should remove all not found vms even if the backend pool will be empty", - bipConfigNotFound: []network.InterfaceIPConfiguration{ + bipConfigNotFound: []*armnetwork.InterfaceIPConfiguration{ {ID: ptr.To("ipconfig1")}, {ID: ptr.To("ipconfig2")}, {ID: ptr.To("ipconfig3")}, }, - bipConfigExclude: []network.InterfaceIPConfiguration{ + bipConfigExclude: []*armnetwork.InterfaceIPConfiguration{ {ID: ptr.To("ipconfig4")}, }, expected: map[string]bool{ @@ -1150,9 +1156,9 @@ func TestGetBackendIPConfigurationsToBeDeleted(t *testing.T) { }, }, } { - bp := network.BackendAddressPool{ - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ + bp := armnetwork.BackendAddressPool{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: []*armnetwork.InterfaceIPConfiguration{ {ID: ptr.To("ipconfig1")}, {ID: ptr.To("ipconfig2")}, {ID: ptr.To("ipconfig3")}, diff --git a/pkg/provider/azure_loadbalancer_healthprobe.go b/pkg/provider/azure_loadbalancer_healthprobe.go index 281a8d94d9..277b528f70 100644 --- a/pkg/provider/azure_loadbalancer_healthprobe.go +++ b/pkg/provider/azure_loadbalancer_healthprobe.go @@ -21,8 +21,8 @@ import ( "strconv" "strings" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" "k8s.io/utils/ptr" @@ -30,11 +30,11 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/consts" ) -func (az *Cloud) buildClusterServiceSharedProbe() *network.Probe { - return &network.Probe{ +func (az *Cloud) buildClusterServiceSharedProbe() *armnetwork.Probe { + return &armnetwork.Probe{ Name: ptr.To(consts.SharedProbeName), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Protocol: network.ProbeProtocolHTTP, + Properties: &armnetwork.ProbePropertiesFormat{ + Protocol: to.Ptr(armnetwork.ProbeProtocolHTTP), Port: ptr.To(az.ClusterServiceSharedLoadBalancerHealthProbePort), RequestPath: ptr.To(az.ClusterServiceSharedLoadBalancerHealthProbePath), IntervalInSeconds: ptr.To(consts.HealthProbeDefaultProbeInterval), @@ -44,10 +44,10 @@ func (az *Cloud) buildClusterServiceSharedProbe() *network.Probe { } // buildHealthProbeRulesForPort -// for following sku: basic loadbalancer vs standard load balancer +// for following SKU: basic loadbalancer vs standard load balancer // for following protocols: TCP HTTP HTTPS(SLB only) // return nil if no new probe is added -func (az *Cloud) buildHealthProbeRulesForPort(serviceManifest *v1.Service, port v1.ServicePort, lbrule string, healthCheckNodePortProbe *network.Probe, useSharedProbe bool) (*network.Probe, error) { +func (az *Cloud) buildHealthProbeRulesForPort(serviceManifest *v1.Service, port v1.ServicePort, lbrule string, healthCheckNodePortProbe *armnetwork.Probe, useSharedProbe bool) (*armnetwork.Probe, error) { if useSharedProbe { klog.V(4).Infof("skip creating health probe for port %d because the shared probe is used", port.Port) return nil, nil @@ -58,7 +58,7 @@ func (az *Cloud) buildHealthProbeRulesForPort(serviceManifest *v1.Service, port } // protocol should be tcp, because sctp is handled in outer loop - properties := &network.ProbePropertiesFormat{} + properties := &armnetwork.ProbePropertiesFormat{} var err error // order - Specific Override @@ -150,30 +150,30 @@ func (az *Cloud) buildHealthProbeRulesForPort(serviceManifest *v1.Service, port // 4. Finally, if protocol is still nil, default to TCP if protocol == nil { - protocol = ptr.To(string(network.ProtocolTCP)) + protocol = ptr.To(string(armnetwork.ProtocolTCP)) } *protocol = strings.TrimSpace(*protocol) switch { - case strings.EqualFold(*protocol, string(network.ProtocolTCP)): - properties.Protocol = network.ProbeProtocolTCP - case strings.EqualFold(*protocol, string(network.ProtocolHTTPS)): + case strings.EqualFold(*protocol, string(armnetwork.ProtocolTCP)): + properties.Protocol = to.Ptr(armnetwork.ProbeProtocolTCP) + case strings.EqualFold(*protocol, string(armnetwork.ProtocolHTTPS)): //HTTPS probe is only supported in standard loadbalancer //For backward compatibility,when unsupported protocol is used, fall back to tcp protocol in basic lb mode instead if !az.UseStandardLoadBalancer() { - properties.Protocol = network.ProbeProtocolTCP + properties.Protocol = to.Ptr(armnetwork.ProbeProtocolTCP) } else { - properties.Protocol = network.ProbeProtocolHTTPS + properties.Protocol = to.Ptr(armnetwork.ProbeProtocolHTTPS) } - case strings.EqualFold(*protocol, string(network.ProtocolHTTP)): - properties.Protocol = network.ProbeProtocolHTTP + case strings.EqualFold(*protocol, string(armnetwork.ProtocolHTTP)): + properties.Protocol = to.Ptr(armnetwork.ProbeProtocolHTTP) default: //For backward compatibility,when unsupported protocol is used, fall back to tcp protocol in basic lb mode instead - properties.Protocol = network.ProbeProtocolTCP + properties.Protocol = to.Ptr(armnetwork.ProbeProtocolTCP) } // Select request path - if strings.EqualFold(string(properties.Protocol), string(network.ProtocolHTTPS)) || strings.EqualFold(string(properties.Protocol), string(network.ProtocolHTTP)) { + if strings.EqualFold(string(*properties.Protocol), string(armnetwork.ProtocolHTTPS)) || strings.EqualFold(string(*properties.Protocol), string(armnetwork.ProtocolHTTP)) { // get request path ,only used with http/https probe path, err := consts.GetHealthProbeConfigOfPortFromK8sSvcAnnotation(serviceManifest.Annotations, port.Port, consts.HealthProbeParamsRequestPath) if err != nil { @@ -194,9 +194,9 @@ func (az *Cloud) buildHealthProbeRulesForPort(serviceManifest *v1.Service, port if err != nil { return nil, fmt.Errorf("failed to parse health probe config for port %d: %w", port.Port, err) } - probe := &network.Probe{ - Name: &lbrule, - ProbePropertiesFormat: properties, + probe := &armnetwork.Probe{ + Name: &lbrule, + Properties: properties, } return probe, nil } @@ -278,14 +278,14 @@ func (*Cloud) getHealthProbeConfigNumOfProbe(serviceManifest *v1.Service, port i return numberOfProbes, nil } -func findProbe(probes []network.Probe, probe network.Probe) bool { +func findProbe(probes []*armnetwork.Probe, probe *armnetwork.Probe) bool { for _, existingProbe := range probes { if strings.EqualFold(ptr.Deref(existingProbe.Name, ""), ptr.Deref(probe.Name, "")) && - ptr.Deref(existingProbe.Port, 0) == ptr.Deref(probe.Port, 0) && - strings.EqualFold(string(existingProbe.Protocol), string(probe.Protocol)) && - strings.EqualFold(ptr.Deref(existingProbe.RequestPath, ""), ptr.Deref(probe.RequestPath, "")) && - ptr.Deref(existingProbe.IntervalInSeconds, 0) == ptr.Deref(probe.IntervalInSeconds, 0) && - ptr.Deref(existingProbe.ProbeThreshold, 0) == ptr.Deref(probe.ProbeThreshold, 0) { + ptr.Deref(existingProbe.Properties.Port, 0) == ptr.Deref(probe.Properties.Port, 0) && + strings.EqualFold(string(ptr.Deref(existingProbe.Properties.Protocol, "")), string(ptr.Deref(probe.Properties.Protocol, ""))) && + strings.EqualFold(ptr.Deref(existingProbe.Properties.RequestPath, ""), ptr.Deref(probe.Properties.RequestPath, "")) && + ptr.Deref(existingProbe.Properties.IntervalInSeconds, 0) == ptr.Deref(probe.Properties.IntervalInSeconds, 0) && + ptr.Deref(existingProbe.Properties.ProbeThreshold, 0) == ptr.Deref(probe.Properties.ProbeThreshold, 0) { return true } } @@ -295,32 +295,32 @@ func findProbe(probes []network.Probe, probe network.Probe) bool { // keepSharedProbe ensures the shared probe will not be removed if there are more than 1 service referencing it. func (az *Cloud) keepSharedProbe( service *v1.Service, - lb network.LoadBalancer, - expectedProbes []network.Probe, + lb armnetwork.LoadBalancer, + expectedProbes []*armnetwork.Probe, wantLB bool, -) ([]network.Probe, error) { +) ([]*armnetwork.Probe, error) { var shouldConsiderRemoveSharedProbe bool if !wantLB { shouldConsiderRemoveSharedProbe = true } - if lb.LoadBalancerPropertiesFormat != nil && lb.Probes != nil { - for _, probe := range *lb.Probes { + if lb.Properties != nil && lb.Properties.Probes != nil { + for _, probe := range lb.Properties.Probes { if strings.EqualFold(ptr.Deref(probe.Name, ""), consts.SharedProbeName) { if !az.useSharedLoadBalancerHealthProbeMode() { shouldConsiderRemoveSharedProbe = true } - if probe.ProbePropertiesFormat != nil && probe.LoadBalancingRules != nil { - for _, rule := range *probe.LoadBalancingRules { + if probe.Properties != nil && probe.Properties.LoadBalancingRules != nil { + for _, rule := range probe.Properties.LoadBalancingRules { ruleName, err := getLastSegment(*rule.ID, "/") if err != nil { klog.Errorf("failed to parse load balancing rule name %s attached to health probe %s", *rule.ID, *probe.ID) - return []network.Probe{}, err + return []*armnetwork.Probe{}, err } if !az.serviceOwnsRule(service, ruleName) && shouldConsiderRemoveSharedProbe { klog.V(4).Infof("there are load balancing rule %s of another service referencing the health probe %s, so the health probe should not be removed", *rule.ID, *probe.ID) sharedProbe := az.buildClusterServiceSharedProbe() - expectedProbes = append(expectedProbes, *sharedProbe) + expectedProbes = append(expectedProbes, sharedProbe) return expectedProbes, nil } } diff --git a/pkg/provider/azure_loadbalancer_healthprobe_test.go b/pkg/provider/azure_loadbalancer_healthprobe_test.go index b1e35c3b05..4d34b57fbf 100644 --- a/pkg/provider/azure_loadbalancer_healthprobe_test.go +++ b/pkg/provider/azure_loadbalancer_healthprobe_test.go @@ -21,7 +21,8 @@ import ( "strings" "testing" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -35,43 +36,43 @@ import ( ) // getTestProbes returns dualStack probes. -func getTestProbes(protocol, path string, interval, servicePort, probePort, numOfProbe *int32) map[bool][]network.Probe { - return map[bool][]network.Probe{ +func getTestProbes(protocol, path string, interval, servicePort, probePort, numOfProbe *int32) map[bool][]*armnetwork.Probe { + return map[bool][]*armnetwork.Probe{ consts.IPVersionIPv4: {getTestProbe(protocol, path, interval, servicePort, probePort, numOfProbe, consts.IPVersionIPv4)}, consts.IPVersionIPv6: {getTestProbe(protocol, path, interval, servicePort, probePort, numOfProbe, consts.IPVersionIPv6)}, } } -func getTestProbe(protocol, path string, interval, servicePort, probePort, numOfProbe *int32, isIPv6 bool) network.Probe { +func getTestProbe(protocol, path string, interval, servicePort, probePort, numOfProbe *int32, isIPv6 bool) *armnetwork.Probe { suffix := "" if isIPv6 { suffix = "-" + consts.IPVersionIPv6String } - expectedProbes := network.Probe{ + expectedProbes := &armnetwork.Probe{ Name: ptr.To(fmt.Sprintf("atest1-TCP-%d", *servicePort) + suffix), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Protocol: network.ProbeProtocol(protocol), + Properties: &armnetwork.ProbePropertiesFormat{ + Protocol: to.Ptr(armnetwork.ProbeProtocol(protocol)), Port: probePort, IntervalInSeconds: interval, ProbeThreshold: numOfProbe, }, } if (strings.EqualFold(protocol, "Http") || strings.EqualFold(protocol, "Https")) && len(strings.TrimSpace(path)) > 0 { - expectedProbes.RequestPath = ptr.To(path) + expectedProbes.Properties.RequestPath = ptr.To(path) } return expectedProbes } // getDefaultTestProbes returns dualStack probes. -func getDefaultTestProbes(protocol, path string) map[bool][]network.Probe { +func getDefaultTestProbes(protocol, path string) map[bool][]*armnetwork.Probe { return getTestProbes(protocol, path, ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2))) } func TestFindProbe(t *testing.T) { tests := []struct { msg string - existingProbe []network.Probe - curProbe network.Probe + existingProbe []*armnetwork.Probe + curProbe *armnetwork.Probe expected bool }{ { @@ -80,17 +81,17 @@ func TestFindProbe(t *testing.T) { }, { msg: "probe names match while ports don't should return false", - existingProbe: []network.Probe{ + existingProbe: []*armnetwork.Probe{ { Name: ptr.To("httpProbe"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(1)), }, }, }, - curProbe: network.Probe{ + curProbe: &armnetwork.Probe{ Name: ptr.To("httpProbe"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(2)), }, }, @@ -98,17 +99,17 @@ func TestFindProbe(t *testing.T) { }, { msg: "probe ports match while names don't should return false", - existingProbe: []network.Probe{ + existingProbe: []*armnetwork.Probe{ { Name: ptr.To("probe1"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(1)), }, }, }, - curProbe: network.Probe{ + curProbe: &armnetwork.Probe{ Name: ptr.To("probe2"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(1)), }, }, @@ -116,38 +117,38 @@ func TestFindProbe(t *testing.T) { }, { msg: "probe protocol don't match should return false", - existingProbe: []network.Probe{ + existingProbe: []*armnetwork.Probe{ { Name: ptr.To("probe1"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(1)), - Protocol: network.ProbeProtocolHTTP, + Protocol: to.Ptr(armnetwork.ProbeProtocolHTTP), }, }, }, - curProbe: network.Probe{ + curProbe: &armnetwork.Probe{ Name: ptr.To("probe1"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(1)), - Protocol: network.ProbeProtocolTCP, + Protocol: to.Ptr(armnetwork.ProbeProtocolTCP), }, }, expected: false, }, { msg: "probe path don't match should return false", - existingProbe: []network.Probe{ + existingProbe: []*armnetwork.Probe{ { Name: ptr.To("probe1"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(1)), RequestPath: ptr.To("/path1"), }, }, }, - curProbe: network.Probe{ + curProbe: &armnetwork.Probe{ Name: ptr.To("probe1"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(1)), RequestPath: ptr.To("/path2"), }, @@ -156,19 +157,19 @@ func TestFindProbe(t *testing.T) { }, { msg: "probe interval don't match should return false", - existingProbe: []network.Probe{ + existingProbe: []*armnetwork.Probe{ { Name: ptr.To("probe1"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(1)), RequestPath: ptr.To("/path"), IntervalInSeconds: ptr.To(int32(5)), }, }, }, - curProbe: network.Probe{ + curProbe: &armnetwork.Probe{ Name: ptr.To("probe1"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(1)), RequestPath: ptr.To("/path"), IntervalInSeconds: ptr.To(int32(10)), @@ -178,17 +179,17 @@ func TestFindProbe(t *testing.T) { }, { msg: "probe match should return true", - existingProbe: []network.Probe{ + existingProbe: []*armnetwork.Probe{ { Name: ptr.To("matchName"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(1)), }, }, }, - curProbe: network.Probe{ + curProbe: &armnetwork.Probe{ Name: ptr.To("matchName"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(1)), }, }, @@ -197,6 +198,7 @@ func TestFindProbe(t *testing.T) { } for _, test := range tests { + test := test t.Run(test.msg, func(t *testing.T) { findResult := findProbe(test.existingProbe, test.curProbe) assert.Equal(t, test.expected, findResult) @@ -208,23 +210,23 @@ func TestShouldKeepSharedProbe(t *testing.T) { testCases := []struct { desc string service *v1.Service - lb network.LoadBalancer + lb armnetwork.LoadBalancer wantLB bool expected bool expectedErr error }{ { - desc: "When the lb.Probes is nil", + desc: "When the lb.Properties.Probes is nil", service: &v1.Service{}, - lb: network.LoadBalancer{}, + lb: armnetwork.LoadBalancer{}, expected: false, }, { - desc: "When the lb.Probes is not nil but does not contain a probe with the name consts.SharedProbeName", + desc: "When the lb.Properties.Probes is not nil but does not contain a probe with the name consts.SharedProbeName", service: &v1.Service{}, - lb: network.LoadBalancer{ - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - Probes: &[]network.Probe{ + lb: armnetwork.LoadBalancer{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + Probes: []*armnetwork.Probe{ { Name: ptr.To("notSharedProbe"), }, @@ -234,15 +236,15 @@ func TestShouldKeepSharedProbe(t *testing.T) { expected: false, }, { - desc: "When the lb.Probes contains a probe with the name consts.SharedProbeName, but none of the LoadBalancingRules in the probe matches the service", + desc: "When the lb.Properties.Probes contains a probe with the name consts.SharedProbeName, but none of the LoadBalancingRules in the probe matches the service", service: &v1.Service{}, - lb: network.LoadBalancer{ - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - Probes: &[]network.Probe{ + lb: armnetwork.LoadBalancer{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + Probes: []*armnetwork.Probe{ { Name: ptr.To(consts.SharedProbeName), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ - LoadBalancingRules: &[]network.SubResource{}, + Properties: &armnetwork.ProbePropertiesFormat{ + LoadBalancingRules: []*armnetwork.SubResource{}, }, }, }, @@ -251,20 +253,20 @@ func TestShouldKeepSharedProbe(t *testing.T) { expected: false, }, { - desc: "When the lb.Probes contains a probe with the name consts.SharedProbeName, and at least one of the LoadBalancingRules in the probe does not match the service", + desc: "When the lb.Properties.Probes contains a probe with the name consts.SharedProbeName, and at least one of the LoadBalancingRules in the probe does not match the service", service: &v1.Service{ ObjectMeta: metav1.ObjectMeta{ UID: types.UID("uid"), }, }, - lb: network.LoadBalancer{ - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - Probes: &[]network.Probe{ + lb: armnetwork.LoadBalancer{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + Probes: []*armnetwork.Probe{ { Name: ptr.To(consts.SharedProbeName), ID: ptr.To("id"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ - LoadBalancingRules: &[]network.SubResource{ + Properties: &armnetwork.ProbePropertiesFormat{ + LoadBalancingRules: []*armnetwork.SubResource{ { ID: ptr.To("other"), }, @@ -286,14 +288,14 @@ func TestShouldKeepSharedProbe(t *testing.T) { UID: types.UID("uid"), }, }, - lb: network.LoadBalancer{ - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - Probes: &[]network.Probe{ + lb: armnetwork.LoadBalancer{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + Probes: []*armnetwork.Probe{ { Name: ptr.To(consts.SharedProbeName), ID: ptr.To("id"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ - LoadBalancingRules: &[]network.SubResource{ + Properties: &armnetwork.ProbePropertiesFormat{ + LoadBalancingRules: []*armnetwork.SubResource{ { ID: ptr.To("other"), }, @@ -309,20 +311,20 @@ func TestShouldKeepSharedProbe(t *testing.T) { wantLB: true, }, { - desc: "When the lb.Probes contains a probe with the name consts.SharedProbeName, and all of the LoadBalancingRules in the probe match the service", + desc: "When the lb.Properties.Probes contains a probe with the name consts.SharedProbeName, and all of the LoadBalancingRules in the probe match the service", service: &v1.Service{ ObjectMeta: metav1.ObjectMeta{ UID: types.UID("uid"), }, }, - lb: network.LoadBalancer{ - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - Probes: &[]network.Probe{ + lb: armnetwork.LoadBalancer{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + Probes: []*armnetwork.Probe{ { Name: ptr.To(consts.SharedProbeName), ID: ptr.To("id"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ - LoadBalancingRules: &[]network.SubResource{ + Properties: &armnetwork.ProbePropertiesFormat{ + LoadBalancingRules: []*armnetwork.SubResource{ { ID: ptr.To("auid"), }, @@ -337,20 +339,20 @@ func TestShouldKeepSharedProbe(t *testing.T) { { desc: "Edge cases such as when the service or LoadBalancer is nil", service: nil, - lb: network.LoadBalancer{}, + lb: armnetwork.LoadBalancer{}, expected: false, }, { desc: "Case: Invalid LoadBalancingRule ID format causing getLastSegment to return an error", service: &v1.Service{}, - lb: network.LoadBalancer{ - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - Probes: &[]network.Probe{ + lb: armnetwork.LoadBalancer{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + Probes: []*armnetwork.Probe{ { Name: ptr.To(consts.SharedProbeName), ID: ptr.To("id"), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ - LoadBalancingRules: &[]network.SubResource{ + Properties: &armnetwork.ProbePropertiesFormat{ + LoadBalancingRules: []*armnetwork.SubResource{ { ID: ptr.To(""), }, @@ -368,7 +370,7 @@ func TestShouldKeepSharedProbe(t *testing.T) { for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { az := GetTestCloud(gomock.NewController(t)) - var expectedProbes []network.Probe + var expectedProbes []*armnetwork.Probe result, err := az.keepSharedProbe(tc.service, tc.lb, expectedProbes, tc.wantLB) assert.Equal(t, tc.expectedErr, err) if tc.expected { diff --git a/pkg/provider/azure_loadbalancer_repo.go b/pkg/provider/azure_loadbalancer_repo.go index 9141db1ffc..4aac783481 100644 --- a/pkg/provider/azure_loadbalancer_repo.go +++ b/pkg/provider/azure_loadbalancer_repo.go @@ -25,8 +25,9 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/klog/v2" @@ -34,44 +35,44 @@ import ( azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" + "sigs.k8s.io/cloud-provider-azure/pkg/util/errutils" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) -// DeleteLB invokes az.LoadBalancerClient.Delete with exponential backoff retry -func (az *Cloud) DeleteLB(ctx context.Context, service *v1.Service, lbName string) *retry.Error { +// DeleteLB invokes az.NetworkClientFactory.GetLoadBalancerClient().Delete with exponential backoff retry +func (az *Cloud) DeleteLB(ctx context.Context, service *v1.Service, lbName string) error { rgName := az.getLoadBalancerResourceGroup() - rerr := az.LoadBalancerClient.Delete(ctx, rgName, lbName) + rerr := az.NetworkClientFactory.GetLoadBalancerClient().Delete(ctx, rgName, lbName) if rerr == nil { // Invalidate the cache right after updating _ = az.lbCache.Delete(lbName) return nil } - klog.Errorf("LoadBalancerClient.Delete(%s) failed: %s", lbName, rerr.Error().Error()) - az.Event(service, v1.EventTypeWarning, "DeleteLoadBalancer", rerr.Error().Error()) + klog.Errorf("LoadbalancerClient.Delete(%s) failed: %s", lbName, rerr.Error()) + az.Event(service, v1.EventTypeWarning, "DeleteLoadBalancer", rerr.Error()) return rerr } -// ListLB invokes az.LoadBalancerClient.List with exponential backoff retry -func (az *Cloud) ListLB(ctx context.Context, service *v1.Service) ([]network.LoadBalancer, error) { +// ListLB invokes az.NetworkClientFactory.GetLoadBalancerClient().List with exponential backoff retry +func (az *Cloud) ListLB(ctx context.Context, service *v1.Service) ([]*armnetwork.LoadBalancer, error) { rgName := az.getLoadBalancerResourceGroup() - allLBs, rerr := az.LoadBalancerClient.List(ctx, rgName) + allLBs, rerr := az.NetworkClientFactory.GetLoadBalancerClient().List(ctx, rgName) if rerr != nil { - if rerr.IsNotFound() { + if exist, err := errutils.CheckResourceExistsFromAzcoreError(rerr); !exist && err == nil { return nil, nil } - az.Event(service, v1.EventTypeWarning, "ListLoadBalancers", rerr.Error().Error()) - klog.Errorf("LoadBalancerClient.List(%v) failure with err=%v", rgName, rerr) - return nil, rerr.Error() + az.Event(service, v1.EventTypeWarning, "ListLoadBalancers", rerr.Error()) + klog.Errorf("LoadbalancerClient.List(%v) failure with err=%v", rgName, rerr) + return nil, rerr } - klog.V(2).Infof("LoadBalancerClient.List(%v) success", rgName) + klog.V(2).Infof("LoadbalancerClient.List(%v) success", rgName) return allLBs, nil } -// ListManagedLBs invokes az.LoadBalancerClient.List and filter out +// ListManagedLBs invokes az.NetworkClientFactory.GetLoadBalancerClient().List and filter out // those that are not managed by cloud provider azure or not associated to a managed VMSet. -func (az *Cloud) ListManagedLBs(ctx context.Context, service *v1.Service, nodes []*v1.Node, clusterName string) (*[]network.LoadBalancer, error) { +func (az *Cloud) ListManagedLBs(ctx context.Context, service *v1.Service, nodes []*v1.Node, clusterName string) ([]*armnetwork.LoadBalancer, error) { allLBs, err := az.ListLB(ctx, service) if err != nil { return nil, err @@ -83,12 +84,12 @@ func (az *Cloud) ListManagedLBs(ctx context.Context, service *v1.Service, nodes } managedLBNames := utilsets.NewString(clusterName) - managedLBs := make([]network.LoadBalancer, 0) - if strings.EqualFold(az.LoadBalancerSku, consts.LoadBalancerSkuBasic) { + managedLBs := make([]*armnetwork.LoadBalancer, 0) + if strings.EqualFold(az.LoadBalancerSKU, consts.LoadBalancerSKUBasic) { // return early if wantLb=false if nodes == nil { klog.V(4).Infof("ListManagedLBs: return all LBs in the resource group %s, including unmanaged LBs", az.getLoadBalancerResourceGroup()) - return &allLBs, nil + return allLBs, nil } agentPoolVMSetNamesMap := make(map[string]bool) @@ -97,10 +98,10 @@ func (az *Cloud) ListManagedLBs(ctx context.Context, service *v1.Service, nodes return nil, fmt.Errorf("ListManagedLBs: failed to get agent pool vmSet names: %w", err) } - if agentPoolVMSetNames != nil && len(*agentPoolVMSetNames) > 0 { - for _, vmSetName := range *agentPoolVMSetNames { - klog.V(6).Infof("ListManagedLBs: found agent pool vmSet name %s", vmSetName) - agentPoolVMSetNamesMap[strings.ToLower(vmSetName)] = true + if len(agentPoolVMSetNames) > 0 { + for _, vmSetName := range agentPoolVMSetNames { + klog.V(6).Infof("ListManagedLBs: found agent pool vmSet name %s", *vmSetName) + agentPoolVMSetNamesMap[strings.ToLower(*vmSetName)] = true } } @@ -122,32 +123,35 @@ func (az *Cloud) ListManagedLBs(ctx context.Context, service *v1.Service, nodes } } - return &managedLBs, nil + return managedLBs, nil } -// CreateOrUpdateLB invokes az.LoadBalancerClient.CreateOrUpdate with exponential backoff retry -func (az *Cloud) CreateOrUpdateLB(ctx context.Context, service *v1.Service, lb network.LoadBalancer) error { +// CreateOrUpdateLB invokes az.NetworkClientFactory.GetLoadBalancerClient().CreateOrUpdate with exponential backoff retry +func (az *Cloud) CreateOrUpdateLB(ctx context.Context, service *v1.Service, lb armnetwork.LoadBalancer) error { lb = cleanupSubnetInFrontendIPConfigurations(&lb) rgName := az.getLoadBalancerResourceGroup() - rerr := az.LoadBalancerClient.CreateOrUpdate(ctx, rgName, ptr.Deref(lb.Name, ""), lb, ptr.Deref(lb.Etag, "")) - klog.V(10).Infof("LoadBalancerClient.CreateOrUpdate(%s): end", *lb.Name) - if rerr == nil { + _, err := az.NetworkClientFactory.GetLoadBalancerClient().CreateOrUpdate(ctx, rgName, ptr.Deref(lb.Name, ""), lb) + klog.V(10).Infof("LoadbalancerClient.CreateOrUpdate(%s): end", *lb.Name) + if err == nil { // Invalidate the cache right after updating _ = az.lbCache.Delete(*lb.Name) return nil } lbJSON, _ := json.Marshal(lb) - klog.Warningf("LoadBalancerClient.CreateOrUpdate(%s) failed: %v, LoadBalancer request: %s", ptr.Deref(lb.Name, ""), rerr.Error(), string(lbJSON)) - + klog.Warningf("LoadbalancerClient.CreateOrUpdate(%s) failed: %v, LoadBalancer request: %s", ptr.Deref(lb.Name, ""), err, string(lbJSON)) + var rerr *azcore.ResponseError + if !errors.As(err, &rerr) { + return err + } // Invalidate the cache because ETAG precondition mismatch. - if rerr.HTTPStatusCode == http.StatusPreconditionFailed { + if rerr.StatusCode == http.StatusPreconditionFailed { klog.V(3).Infof("LoadBalancer cache for %s is cleanup because of http.StatusPreconditionFailed", ptr.Deref(lb.Name, "")) _ = az.lbCache.Delete(*lb.Name) } - retryErrorMessage := rerr.Error().Error() + retryErrorMessage := rerr.Error() // Invalidate the cache because another new operation has canceled the current request. if strings.Contains(strings.ToLower(retryErrorMessage), consts.OperationCanceledErrorMessage) { klog.V(3).Infof("LoadBalancer cache for %s is cleanup because CreateOrUpdate is canceled by another operation", ptr.Deref(lb.Name, "")) @@ -159,103 +163,111 @@ func (az *Cloud) CreateOrUpdateLB(ctx context.Context, service *v1.Service, lb n matches := pipErrorMessageRE.FindStringSubmatch(retryErrorMessage) if len(matches) != 3 { klog.Errorf("Failed to parse the retry error message %s", retryErrorMessage) - return rerr.Error() + return rerr } pipRG, pipName := matches[1], matches[2] klog.V(3).Infof("The public IP %s referenced by load balancer %s is not in Succeeded provisioning state, will try to update it", pipName, ptr.Deref(lb.Name, "")) pip, _, err := az.getPublicIPAddress(ctx, pipRG, pipName, azcache.CacheReadTypeDefault) if err != nil { klog.Errorf("Failed to get the public IP %s in resource group %s: %v", pipName, pipRG, err) - return rerr.Error() + return rerr } // Perform a dummy update to fix the provisioning state err = az.CreateOrUpdatePIP(service, pipRG, pip) if err != nil { klog.Errorf("Failed to update the public IP %s in resource group %s: %v", pipName, pipRG, err) - return rerr.Error() + return rerr } // Invalidate the LB cache, return the error, and the controller manager // would retry the LB update in the next reconcile loop _ = az.lbCache.Delete(*lb.Name) } - return rerr.Error() + return rerr } -func (az *Cloud) CreateOrUpdateLBBackendPool(ctx context.Context, lbName string, backendPool network.BackendAddressPool) error { +func (az *Cloud) CreateOrUpdateLBBackendPool(ctx context.Context, lbName string, backendPool *armnetwork.BackendAddressPool) error { klog.V(4).Infof("CreateOrUpdateLBBackendPool: updating backend pool %s in LB %s", ptr.Deref(backendPool.Name, ""), lbName) - rerr := az.LoadBalancerClient.CreateOrUpdateBackendPools(ctx, az.getLoadBalancerResourceGroup(), lbName, ptr.Deref(backendPool.Name, ""), backendPool, ptr.Deref(backendPool.Etag, "")) - if rerr == nil { + _, err := az.NetworkClientFactory.GetBackendAddressPoolClient().CreateOrUpdate(ctx, az.getLoadBalancerResourceGroup(), lbName, ptr.Deref(backendPool.Name, ""), *backendPool) + if err == nil { // Invalidate the cache right after updating _ = az.lbCache.Delete(lbName) return nil } + var rerr *azcore.ResponseError + if !errors.As(err, &rerr) { + return err + } // Invalidate the cache because ETAG precondition mismatch. - if rerr.HTTPStatusCode == http.StatusPreconditionFailed { + if rerr.StatusCode == http.StatusPreconditionFailed { klog.V(3).Infof("LoadBalancer cache for %s is cleanup because of http.StatusPreconditionFailed", lbName) _ = az.lbCache.Delete(lbName) } - retryErrorMessage := rerr.Error().Error() + retryErrorMessage := rerr.Error() // Invalidate the cache because another new operation has canceled the current request. if strings.Contains(strings.ToLower(retryErrorMessage), consts.OperationCanceledErrorMessage) { klog.V(3).Infof("LoadBalancer cache for %s is cleanup because CreateOrUpdate is canceled by another operation", lbName) _ = az.lbCache.Delete(lbName) } - return rerr.Error() + return rerr } func (az *Cloud) DeleteLBBackendPool(ctx context.Context, lbName, backendPoolName string) error { klog.V(4).Infof("DeleteLBBackendPool: deleting backend pool %s in LB %s", backendPoolName, lbName) - rerr := az.LoadBalancerClient.DeleteLBBackendPool(ctx, az.getLoadBalancerResourceGroup(), lbName, backendPoolName) - if rerr == nil { + err := az.NetworkClientFactory.GetBackendAddressPoolClient().Delete(ctx, az.getLoadBalancerResourceGroup(), lbName, backendPoolName) + if err == nil { // Invalidate the cache right after updating _ = az.lbCache.Delete(lbName) return nil } + var rerr *azcore.ResponseError + if !errors.As(err, &rerr) { + return err + } // Invalidate the cache because ETAG precondition mismatch. - if rerr.HTTPStatusCode == http.StatusPreconditionFailed { + if rerr.StatusCode == http.StatusPreconditionFailed { klog.V(3).Infof("LoadBalancer cache for %s is cleanup because of http.StatusPreconditionFailed", lbName) _ = az.lbCache.Delete(lbName) } - retryErrorMessage := rerr.Error().Error() + retryErrorMessage := rerr.Error() // Invalidate the cache because another new operation has canceled the current request. if strings.Contains(strings.ToLower(retryErrorMessage), consts.OperationCanceledErrorMessage) { klog.V(3).Infof("LoadBalancer cache for %s is cleanup because CreateOrUpdate is canceled by another operation", lbName) _ = az.lbCache.Delete(lbName) } - return rerr.Error() + return rerr } -func cleanupSubnetInFrontendIPConfigurations(lb *network.LoadBalancer) network.LoadBalancer { - if lb.LoadBalancerPropertiesFormat == nil || lb.FrontendIPConfigurations == nil { +func cleanupSubnetInFrontendIPConfigurations(lb *armnetwork.LoadBalancer) armnetwork.LoadBalancer { + if lb.Properties == nil || lb.Properties.FrontendIPConfigurations == nil { return *lb } - frontendIPConfigurations := *lb.FrontendIPConfigurations + frontendIPConfigurations := lb.Properties.FrontendIPConfigurations for i := range frontendIPConfigurations { config := frontendIPConfigurations[i] - if config.FrontendIPConfigurationPropertiesFormat != nil && - config.Subnet != nil && - config.Subnet.ID != nil { - subnet := network.Subnet{ - ID: config.Subnet.ID, + if config.Properties != nil && + config.Properties.Subnet != nil && + config.Properties.Subnet.ID != nil { + subnet := armnetwork.Subnet{ + ID: config.Properties.Subnet.ID, } - if config.Subnet.Name != nil { - subnet.Name = config.FrontendIPConfigurationPropertiesFormat.Subnet.Name + if config.Properties.Subnet.Name != nil { + subnet.Name = config.Properties.Subnet.Name } - config.FrontendIPConfigurationPropertiesFormat.Subnet = &subnet + config.Properties.Subnet = &subnet frontendIPConfigurations[i] = config continue } } - lb.FrontendIPConfigurations = &frontendIPConfigurations + lb.Properties.FrontendIPConfigurations = frontendIPConfigurations return *lb } @@ -266,10 +278,14 @@ func (az *Cloud) MigrateToIPBasedBackendPoolAndWaitForCompletion( ctx context.Context, lbName string, backendPoolNames []string, nicsCountMap map[string]int, ) error { - if rerr := az.LoadBalancerClient.MigrateToIPBasedBackendPool(ctx, az.ResourceGroup, lbName, backendPoolNames); rerr != nil { + if _, rerr := az.NetworkClientFactory.GetLoadBalancerClient().MigrateToIPBased(ctx, az.ResourceGroup, lbName, &armnetwork.LoadBalancersClientMigrateToIPBasedOptions{ + Parameters: &armnetwork.MigrateLoadBalancerToIPBasedRequest{ + Pools: to.SliceOfPtrs(backendPoolNames...), + }, + }); rerr != nil { backendPoolNamesStr := strings.Join(backendPoolNames, ",") - klog.Errorf("MigrateToIPBasedBackendPoolAndWaitForCompletion: Failed to migrate to IP based backend pool for lb %s, backend pool %s: %s", lbName, backendPoolNamesStr, rerr.Error().Error()) - return rerr.Error() + klog.Errorf("MigrateToIPBasedBackendPoolAndWaitForCompletion: Failed to migrate to IP based backend pool for lb %s, backend pool %s: %s", lbName, backendPoolNamesStr, rerr.Error()) + return rerr } succeeded := make(map[string]bool) @@ -283,10 +299,10 @@ func (az *Cloud) MigrateToIPBasedBackendPoolAndWaitForCompletion( continue } - bp, rerr := az.LoadBalancerClient.GetLBBackendPool(ctx, az.ResourceGroup, lbName, bpName, "") + bp, rerr := az.NetworkClientFactory.GetBackendAddressPoolClient().Get(ctx, az.ResourceGroup, lbName, bpName) if rerr != nil { - klog.Errorf("MigrateToIPBasedBackendPoolAndWaitForCompletion: Failed to get backend pool %s for lb %s: %s", bpName, lbName, rerr.Error().Error()) - return false, rerr.Error() + klog.Errorf("MigrateToIPBasedBackendPoolAndWaitForCompletion: Failed to get backend pool %s for lb %s: %s", bpName, lbName, rerr.Error()) + return false, rerr } if countIPsOnBackendPool(bp) != nicsCount { @@ -312,10 +328,10 @@ func (az *Cloud) MigrateToIPBasedBackendPoolAndWaitForCompletion( func (az *Cloud) newLBCache() (azcache.Resource, error) { getter := func(ctx context.Context, key string) (interface{}, error) { - lb, err := az.LoadBalancerClient.Get(ctx, az.getLoadBalancerResourceGroup(), key, "") + lb, err := az.NetworkClientFactory.GetLoadBalancerClient().Get(ctx, az.getLoadBalancerResourceGroup(), key, nil) exists, rerr := checkResourceExistsFromError(err) if rerr != nil { - return nil, rerr.Error() + return nil, rerr } if !exists { @@ -323,7 +339,7 @@ func (az *Cloud) newLBCache() (azcache.Resource, error) { return nil, nil } - return &lb, nil + return lb, nil } if az.LoadBalancerCacheTTLInSeconds == 0 { @@ -332,7 +348,7 @@ func (az *Cloud) newLBCache() (azcache.Resource, error) { return azcache.NewTimedCache(time.Duration(az.LoadBalancerCacheTTLInSeconds)*time.Second, getter, az.Config.DisableAPICallCache) } -func (az *Cloud) getAzureLoadBalancer(ctx context.Context, name string, crt azcache.AzureCacheReadType) (lb *network.LoadBalancer, exists bool, err error) { +func (az *Cloud) getAzureLoadBalancer(ctx context.Context, name string, crt azcache.AzureCacheReadType) (lb *armnetwork.LoadBalancer, exists bool, err error) { cachedLB, err := az.lbCache.GetWithDeepCopy(ctx, name, crt) if err != nil { return lb, false, err @@ -342,7 +358,7 @@ func (az *Cloud) getAzureLoadBalancer(ctx context.Context, name string, crt azca return lb, false, nil } - return cachedLB.(*network.LoadBalancer), true, nil + return cachedLB.(*armnetwork.LoadBalancer), true, nil } // isBackendPoolOnSameLB checks whether newBackendPoolID is on the same load balancer as existingBackendPools. @@ -380,12 +396,12 @@ func (az *Cloud) serviceOwnsRule(service *v1.Service, rule string) bool { return strings.HasPrefix(strings.ToUpper(rule), strings.ToUpper(prefix)) } -func isNICPool(bp network.BackendAddressPool) bool { +func isNICPool(bp *armnetwork.BackendAddressPool) bool { logger := klog.Background().WithName("isNICPool").WithValues("backendPoolName", ptr.Deref(bp.Name, "")) - if bp.BackendAddressPoolPropertiesFormat != nil && - bp.LoadBalancerBackendAddresses != nil { - for _, addr := range *bp.LoadBalancerBackendAddresses { - if ptr.Deref(addr.IPAddress, "") == "" { + if bp.Properties != nil && + bp.Properties.LoadBalancerBackendAddresses != nil { + for _, addr := range bp.Properties.LoadBalancerBackendAddresses { + if ptr.Deref(addr.Properties.IPAddress, "") == "" { logger.V(4).Info("The load balancer backend address has empty ip address, assuming it is a NIC pool", "loadBalancerBackendAddress", ptr.Deref(addr.Name, "")) return true diff --git a/pkg/provider/azure_loadbalancer_repo_test.go b/pkg/provider/azure_loadbalancer_repo_test.go index 6b2b84431d..0f1f3a6736 100644 --- a/pkg/provider/azure_loadbalancer_repo_test.go +++ b/pkg/provider/azure_loadbalancer_repo_test.go @@ -18,12 +18,13 @@ package provider import ( "context" - "errors" "fmt" "net/http" "testing" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -31,12 +32,12 @@ import ( v1 "k8s.io/api/core/v1" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient/mockloadbalancerclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/backendaddresspoolclient/mock_backendaddresspoolclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/loadbalancerclient/mock_loadbalancerclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipaddressclient/mock_publicipaddressclient" "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) func TestDeleteLB(t *testing.T) { @@ -44,35 +45,37 @@ func TestDeleteLB(t *testing.T) { defer ctrl.Finish() az := GetTestCloud(ctrl) - mockLBClient := az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) - mockLBClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, "lb").Return(&retry.Error{HTTPStatusCode: http.StatusInternalServerError}) + mockLBClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, "lb").Return(&azcore.ResponseError{StatusCode: http.StatusInternalServerError}) err := az.DeleteLB(context.TODO(), &v1.Service{}, "lb") - assert.EqualError(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil)), fmt.Sprintf("%s", err.Error())) + assert.Contains(t, err.Error(), "UNAVAILABLE") } func TestListManagedLBs(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() tests := []struct { - existingLBs []network.LoadBalancer - expectedLBs *[]network.LoadBalancer + name string + existingLBs []*armnetwork.LoadBalancer + expectedLBs []*armnetwork.LoadBalancer callTimes int multiSLBConfigs []config.MultipleStandardLoadBalancerConfiguration - clientErr *retry.Error + clientErr error expectedErr error }{ { - clientErr: &retry.Error{HTTPStatusCode: http.StatusInternalServerError}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil)), + name: "Internal Server Error", + clientErr: &azcore.ResponseError{StatusCode: http.StatusInternalServerError}, + expectedErr: fmt.Errorf("UNAVAILABLE"), }, { - clientErr: &retry.Error{HTTPStatusCode: http.StatusNotFound}, + name: "Resource Not Found", + clientErr: &azcore.ResponseError{StatusCode: http.StatusNotFound}, expectedErr: nil, }, { - existingLBs: []network.LoadBalancer{ + name: "filtered the result", + existingLBs: []*armnetwork.LoadBalancer{ {Name: ptr.To("kubernetes")}, {Name: ptr.To("kubernetes-internal")}, {Name: ptr.To("vmas-1")}, @@ -80,7 +83,7 @@ func TestListManagedLBs(t *testing.T) { {Name: ptr.To("unmanaged")}, {Name: ptr.To("unmanaged-internal")}, }, - expectedLBs: &[]network.LoadBalancer{ + expectedLBs: []*armnetwork.LoadBalancer{ {Name: ptr.To("kubernetes")}, {Name: ptr.To("kubernetes-internal")}, {Name: ptr.To("vmas-1")}, @@ -89,7 +92,8 @@ func TestListManagedLBs(t *testing.T) { callTimes: 1, }, { - existingLBs: []network.LoadBalancer{ + name: "filtered the result with multiple standard load balancer configurations", + existingLBs: []*armnetwork.LoadBalancer{ {Name: ptr.To("kubernetes")}, {Name: ptr.To("kubernetes-internal")}, {Name: ptr.To("lb1-internal")}, @@ -99,7 +103,7 @@ func TestListManagedLBs(t *testing.T) { {Name: "kubernetes"}, {Name: "lb1"}, }, - expectedLBs: &[]network.LoadBalancer{ + expectedLBs: []*armnetwork.LoadBalancer{ {Name: ptr.To("kubernetes")}, {Name: ptr.To("kubernetes-internal")}, {Name: ptr.To("lb1-internal")}, @@ -107,83 +111,101 @@ func TestListManagedLBs(t *testing.T) { }, } for _, test := range tests { - az := GetTestCloud(ctrl) - if len(test.multiSLBConfigs) > 0 { - az.LoadBalancerSku = consts.LoadBalancerSkuStandard - az.MultipleStandardLoadBalancerConfigurations = test.multiSLBConfigs - } else { - az.LoadBalancerSku = consts.LoadBalancerSkuBasic - } + test := test + t.Run(test.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + az := GetTestCloud(ctrl) + if len(test.multiSLBConfigs) > 0 { + az.LoadBalancerSKU = consts.LoadBalancerSKUStandard + az.MultipleStandardLoadBalancerConfigurations = test.multiSLBConfigs + } else { + az.LoadBalancerSKU = consts.LoadBalancerSKUBasic + } - mockLBClient := az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) - mockLBClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(test.existingLBs, test.clientErr) - mockVMSet := NewMockVMSet(ctrl) - mockVMSet.EXPECT().GetAgentPoolVMSetNames(gomock.Any(), gomock.Any()).Return(&[]string{"vmas-0", "vmas-1"}, nil).Times(test.callTimes) - mockVMSet.EXPECT().GetPrimaryVMSetName().Return("vmas-0").AnyTimes() - az.VMSet = mockVMSet + mockLBClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(test.existingLBs, test.clientErr) + mockVMSet := NewMockVMSet(ctrl) + mockVMSet.EXPECT().GetAgentPoolVMSetNames(gomock.Any(), gomock.Any()).Return(to.SliceOfPtrs("vmas-0", "vmas-1"), nil).Times(test.callTimes) + mockVMSet.EXPECT().GetPrimaryVMSetName().Return("vmas-0").AnyTimes() + az.VMSet = mockVMSet + + lbs, err := az.ListManagedLBs(context.TODO(), &v1.Service{}, []*v1.Node{}, "kubernetes") + if test.expectedErr != nil { + assert.NotNil(t, err) + assert.Contains(t, err.Error(), test.expectedErr.Error()) + } else { + assert.Nil(t, err) + } + assert.Equal(t, test.expectedLBs, lbs) - lbs, err := az.ListManagedLBs(context.TODO(), &v1.Service{}, []*v1.Node{}, "kubernetes") - assert.Equal(t, test.expectedErr, err) - assert.Equal(t, test.expectedLBs, lbs) + ctrl.Finish() + }) } } func TestCreateOrUpdateLB(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() referencedResourceNotProvisionedRawErrorString := `Code="ReferencedResourceNotProvisioned" Message="Cannot proceed with operation because resource /subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pip used by resource /subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb is not in Succeeded state. Resource is in Failed state and the last operation that updated/is updating the resource is PutPublicIpAddressOperation."` tests := []struct { - clientErr *retry.Error + name string + clientErr error expectedErr error }{ { - clientErr: &retry.Error{HTTPStatusCode: http.StatusPreconditionFailed}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 412, RawError: %w", error(nil)), + name: "StatusPreconditionFailed", + clientErr: &azcore.ResponseError{StatusCode: http.StatusPreconditionFailed, ErrorCode: "412"}, + expectedErr: fmt.Errorf("412"), }, { - clientErr: &retry.Error{RawError: fmt.Errorf(consts.OperationCanceledErrorMessage)}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", errors.New("canceledandsupersededduetoanotheroperation")), + name: "OperationCanceled", + clientErr: &azcore.ResponseError{ErrorCode: consts.OperationCanceledErrorMessage}, + expectedErr: fmt.Errorf("canceledandsupersededduetoanotheroperation"), }, { - clientErr: &retry.Error{RawError: errors.New(referencedResourceNotProvisionedRawErrorString)}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", errors.New(referencedResourceNotProvisionedRawErrorString)), + name: "ReferencedResourceNotProvisioned", + clientErr: &azcore.ResponseError{ErrorCode: referencedResourceNotProvisionedRawErrorString}, + expectedErr: fmt.Errorf(referencedResourceNotProvisionedRawErrorString), }, } for _, test := range tests { - az := GetTestCloud(ctrl) - az.lbCache.Set("lb", "test") - - mockLBClient := az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) - mockLBClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(test.clientErr) - mockLBClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "lb", gomock.Any()).Return(network.LoadBalancer{}, nil) - - mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) - mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "pip", gomock.Any()).Return(nil).MaxTimes(1) - mockPIPClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]network.PublicIPAddress{{ - Name: ptr.To("pip"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - ProvisioningState: network.ProvisioningStateSucceeded, - }, - }}, nil).MaxTimes(2) - - err := az.CreateOrUpdateLB(context.TODO(), &v1.Service{}, network.LoadBalancer{ - Name: ptr.To("lb"), - Etag: ptr.To("etag"), + test := test + t.Run(test.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + az := GetTestCloud(ctrl) + az.lbCache.Set("lb", "test") + + mockLBClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, test.clientErr) + mockLBClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "lb", gomock.Any()).Return(&armnetwork.LoadBalancer{}, nil) + + mockPIPClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "pip", gomock.Any()).Return(nil, nil).MaxTimes(1) + mockPIPClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]*armnetwork.PublicIPAddress{{ + Name: ptr.To("pip"), + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + ProvisioningState: to.Ptr(armnetwork.ProvisioningStateSucceeded), + }, + }}, nil).MaxTimes(2) + + err := az.CreateOrUpdateLB(context.TODO(), &v1.Service{}, armnetwork.LoadBalancer{ + Name: ptr.To("lb"), + Etag: ptr.To("etag"), + }) + assert.Contains(t, err.Error(), test.expectedErr.Error()) + + // loadbalancer should be removed from cache if the etag is mismatch or the operation is canceled + shouldBeEmpty, err := az.lbCache.GetWithDeepCopy(context.TODO(), "lb", cache.CacheReadTypeDefault) + assert.NoError(t, err) + assert.Empty(t, shouldBeEmpty) + + // public ip cache should be populated since there's GetPIP + shouldNotBeEmpty, err := az.pipCache.Get(context.TODO(), az.ResourceGroup, cache.CacheReadTypeDefault) + assert.NoError(t, err) + assert.NotEmpty(t, shouldNotBeEmpty) + ctrl.Finish() }) - assert.EqualError(t, test.expectedErr, err.Error()) - - // loadbalancer should be removed from cache if the etag is mismatch or the operation is canceled - shouldBeEmpty, err := az.lbCache.GetWithDeepCopy(context.TODO(), "lb", cache.CacheReadTypeDefault) - assert.NoError(t, err) - assert.Empty(t, shouldBeEmpty) - - // public ip cache should be populated since there's GetPIP - shouldNotBeEmpty, err := az.pipCache.Get(context.TODO(), az.ResourceGroup, cache.CacheReadTypeDefault) - assert.NoError(t, err) - assert.NotEmpty(t, shouldNotBeEmpty) } } @@ -193,7 +215,7 @@ func TestCreateOrUpdateLBBackendPool(t *testing.T) { for _, tc := range []struct { description string - createOrUpdateErr *retry.Error + createOrUpdateErr error expectedErr bool }{ { @@ -201,19 +223,18 @@ func TestCreateOrUpdateLBBackendPool(t *testing.T) { }, { description: "CreateOrUpdateLBBackendPool should report an error if the api call fails", - createOrUpdateErr: &retry.Error{ - HTTPStatusCode: http.StatusPreconditionFailed, - RawError: errors.New(consts.OperationCanceledErrorMessage), + createOrUpdateErr: &azcore.ResponseError{ + StatusCode: http.StatusPreconditionFailed, + ErrorCode: consts.OperationCanceledErrorMessage, }, expectedErr: true, }, } { az := GetTestCloud(ctrl) - lbClient := mockloadbalancerclient.NewMockInterface(ctrl) - lbClient.EXPECT().CreateOrUpdateBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.createOrUpdateErr) - az.LoadBalancerClient = lbClient + lbClient := az.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) + lbClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, tc.createOrUpdateErr) - err := az.CreateOrUpdateLBBackendPool(context.TODO(), "kubernetes", network.BackendAddressPool{}) + err := az.CreateOrUpdateLBBackendPool(context.TODO(), "kubernetes", &armnetwork.BackendAddressPool{}) assert.Equal(t, tc.expectedErr, err != nil) } } @@ -224,7 +245,7 @@ func TestDeleteLBBackendPool(t *testing.T) { for _, tc := range []struct { description string - deleteErr *retry.Error + deleteErr error expectedErr bool }{ { @@ -232,17 +253,16 @@ func TestDeleteLBBackendPool(t *testing.T) { }, { description: "DeleteLBBackendPool should report an error if the api call fails", - deleteErr: &retry.Error{ - HTTPStatusCode: http.StatusPreconditionFailed, - RawError: errors.New(consts.OperationCanceledErrorMessage), + deleteErr: &azcore.ResponseError{ + StatusCode: http.StatusPreconditionFailed, + ErrorCode: consts.OperationCanceledErrorMessage, }, expectedErr: true, }, } { az := GetTestCloud(ctrl) - lbClient := mockloadbalancerclient.NewMockInterface(ctrl) - lbClient.EXPECT().DeleteLBBackendPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.deleteErr) - az.LoadBalancerClient = lbClient + backendClient := az.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) + backendClient.EXPECT().Delete(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.deleteErr) err := az.DeleteLBBackendPool(context.TODO(), "kubernetes", "kubernetes") assert.Equal(t, tc.expectedErr, err != nil) @@ -255,47 +275,47 @@ func TestMigrateToIPBasedBackendPoolAndWaitForCompletion(t *testing.T) { for _, tc := range []struct { desc string - migrationError *retry.Error - backendPool network.BackendAddressPool - backendPoolAfterRetry *network.BackendAddressPool - getBackendPoolError *retry.Error + migrationError error + backendPool *armnetwork.BackendAddressPool + backendPoolAfterRetry *armnetwork.BackendAddressPool + getBackendPoolError error expectedError error }{ { desc: "MigrateToIPBasedBackendPoolAndWaitForCompletion should return the error if the migration fails", - migrationError: retry.NewError(false, errors.New("error")), - expectedError: retry.NewError(false, errors.New("error")).Error(), + migrationError: &azcore.ResponseError{ErrorCode: "error"}, + expectedError: &azcore.ResponseError{ErrorCode: "error"}, }, { desc: "MigrateToIPBasedBackendPoolAndWaitForCompletion should return the error if failed to get the backend pool", - getBackendPoolError: retry.NewError(false, errors.New("error")), - expectedError: retry.NewError(false, errors.New("error")).Error(), + getBackendPoolError: &azcore.ResponseError{ErrorCode: "error"}, + expectedError: &azcore.ResponseError{ErrorCode: "error"}, }, { desc: "MigrateToIPBasedBackendPoolAndWaitForCompletion should retry if the number IPs on the backend pool is not expected", - backendPool: network.BackendAddressPool{ + backendPool: &armnetwork.BackendAddressPool{ Name: ptr.To(testClusterName), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, }, }, }, - backendPoolAfterRetry: &network.BackendAddressPool{ + backendPoolAfterRetry: &armnetwork.BackendAddressPool{ Name: ptr.To(testClusterName), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("2.3.4.5"), }, }, @@ -306,15 +326,16 @@ func TestMigrateToIPBasedBackendPoolAndWaitForCompletion(t *testing.T) { } { t.Run(tc.desc, func(t *testing.T) { az := GetTestCloud(ctrl) - lbClient := mockloadbalancerclient.NewMockInterface(ctrl) - lbClient.EXPECT().MigrateToIPBasedBackendPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.migrationError) + lbClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + lbClient.EXPECT().MigrateToIPBased(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(armnetwork.LoadBalancersClientMigrateToIPBasedResponse{}, tc.migrationError) + backendPoolClient := az.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) + if tc.migrationError == nil { - lbClient.EXPECT().GetLBBackendPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.backendPool, tc.getBackendPoolError) + backendPoolClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.backendPool, tc.getBackendPoolError) } if tc.backendPoolAfterRetry != nil { - lbClient.EXPECT().GetLBBackendPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(*tc.backendPoolAfterRetry, nil) + backendPoolClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.backendPoolAfterRetry, nil) } - az.LoadBalancerClient = lbClient lbName := testClusterName backendPoolNames := []string{testClusterName} @@ -434,43 +455,43 @@ func TestServiceOwnsRuleSharedProbe(t *testing.T) { func TestIsNICPool(t *testing.T) { tests := []struct { desc string - bp network.BackendAddressPool + bp *armnetwork.BackendAddressPool expected bool }{ { desc: "nil BackendAddressPoolPropertiesFormat", - bp: network.BackendAddressPool{ + bp: &armnetwork.BackendAddressPool{ Name: ptr.To("pool1"), }, expected: false, }, { desc: "nil LoadBalancerBackendAddresses", - bp: network.BackendAddressPool{ - Name: ptr.To("pool1"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{}, + bp: &armnetwork.BackendAddressPool{ + Name: ptr.To("pool1"), + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{}, }, expected: false, }, { desc: "empty LoadBalancerBackendAddresses", - bp: network.BackendAddressPool{ + bp: &armnetwork.BackendAddressPool{ Name: ptr.To("pool1"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{}, + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{}, }, }, expected: false, }, { desc: "LoadBalancerBackendAddress with empty IPAddress", - bp: network.BackendAddressPool{ + bp: &armnetwork.BackendAddressPool{ Name: ptr.To("pool1"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { Name: ptr.To("addr1"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To(""), }, }, @@ -481,13 +502,13 @@ func TestIsNICPool(t *testing.T) { }, { desc: "LoadBalancerBackendAddress with non-empty IPAddress", - bp: network.BackendAddressPool{ + bp: &armnetwork.BackendAddressPool{ Name: ptr.To("pool1"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { Name: ptr.To("addr1"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.1"), }, }, @@ -498,19 +519,19 @@ func TestIsNICPool(t *testing.T) { }, { desc: "LoadBalancerBackendAddress with both empty and non-empty IPAddress", - bp: network.BackendAddressPool{ + bp: &armnetwork.BackendAddressPool{ Name: ptr.To("pool1"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { Name: ptr.To("addr1"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To(""), }, }, { Name: ptr.To("addr2"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.2"), }, }, diff --git a/pkg/provider/azure_loadbalancer_test.go b/pkg/provider/azure_loadbalancer_test.go index 6b0fb9e1dd..4cb722cc11 100644 --- a/pkg/provider/azure_loadbalancer_test.go +++ b/pkg/provider/azure_loadbalancer_test.go @@ -28,10 +28,10 @@ import ( "testing" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" "golang.org/x/text/cases" @@ -46,15 +46,15 @@ import ( k8stesting "k8s.io/client-go/testing" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient/mockloadbalancerclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/subnetclient/mocksubnetclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/backendaddresspoolclient/mock_backendaddresspoolclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/loadbalancerclient/mock_loadbalancerclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipaddressclient/mock_publicipaddressclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/mock_virtualmachinescalesetclient" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" "sigs.k8s.io/cloud-provider-azure/pkg/provider/privatelinkservice" + "sigs.k8s.io/cloud-provider-azure/pkg/provider/subnet" "sigs.k8s.io/cloud-provider-azure/pkg/provider/zone" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) @@ -81,17 +81,17 @@ func TestExistsPip(t *testing.T) { testcases := []struct { desc string service v1.Service - expectedClientList func(client *mockpublicipclient.MockInterface) + expectedClientList func(client *mock_publicipaddressclient.MockInterface) expectedExist bool }{ { "IPv4 exists", getTestService("service", v1.ProtocolTCP, nil, false, 80), - func(client *mockpublicipclient.MockInterface) { - pips := []network.PublicIPAddress{ + func(client *mock_publicipaddressclient.MockInterface) { + pips := []*armnetwork.PublicIPAddress{ { Name: ptr.To("testCluster-aservice"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -103,19 +103,19 @@ func TestExistsPip(t *testing.T) { { "IPv4 not exists", getTestService("service", v1.ProtocolTCP, nil, false, 80), - func(client *mockpublicipclient.MockInterface) { - client.EXPECT().List(gomock.Any(), "rg").Return([]network.PublicIPAddress{}, nil).MaxTimes(2) + func(client *mock_publicipaddressclient.MockInterface) { + client.EXPECT().List(gomock.Any(), "rg").Return([]*armnetwork.PublicIPAddress{}, nil).MaxTimes(2) }, false, }, { "IPv6 exists", getTestService("service", v1.ProtocolTCP, nil, true, 80), - func(client *mockpublicipclient.MockInterface) { - pips := []network.PublicIPAddress{ + func(client *mock_publicipaddressclient.MockInterface) { + pips := []*armnetwork.PublicIPAddress{ { Name: ptr.To("testCluster-aservice"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("fe::1"), }, }, @@ -127,11 +127,11 @@ func TestExistsPip(t *testing.T) { { "IPv6 not exists - should not have suffix", getTestService("service", v1.ProtocolTCP, nil, true, 80), - func(client *mockpublicipclient.MockInterface) { - pips := []network.PublicIPAddress{ + func(client *mock_publicipaddressclient.MockInterface) { + pips := []*armnetwork.PublicIPAddress{ { Name: ptr.To("testCluster-aservice-IPv6"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("fe::1"), }, }, @@ -143,17 +143,17 @@ func TestExistsPip(t *testing.T) { { "DualStack exists", getTestServiceDualStack("service", v1.ProtocolTCP, nil, 80), - func(client *mockpublicipclient.MockInterface) { - pips := []network.PublicIPAddress{ + func(client *mock_publicipaddressclient.MockInterface) { + pips := []*armnetwork.PublicIPAddress{ { Name: ptr.To("testCluster-aservice"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("testCluster-aservice-IPv6"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("fe::1"), }, }, @@ -165,11 +165,11 @@ func TestExistsPip(t *testing.T) { { "DualStack, IPv4 not exists", getTestServiceDualStack("service", v1.ProtocolTCP, nil, 80), - func(client *mockpublicipclient.MockInterface) { - pips := []network.PublicIPAddress{ + func(client *mock_publicipaddressclient.MockInterface) { + pips := []*armnetwork.PublicIPAddress{ { Name: ptr.To("testCluster-aservice-IPv6"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("fe::1"), }, }, @@ -183,7 +183,7 @@ func TestExistsPip(t *testing.T) { t.Run(tc.desc, func(t *testing.T) { az := GetTestCloud(ctrl) service := tc.service - mockPIPsClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) tc.expectedClientList(mockPIPsClient) exist := az.existsPip(context.TODO(), "testCluster", &service) assert.Equal(t, tc.expectedExist, exist) @@ -193,30 +193,30 @@ func TestExistsPip(t *testing.T) { // TODO: Dualstack func TestGetLoadBalancer(t *testing.T) { - lb1 := network.LoadBalancer{ - Name: ptr.To("testCluster"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, + lb1 := &armnetwork.LoadBalancer{ + Name: ptr.To("testCluster"), + Properties: &armnetwork.LoadBalancerPropertiesFormat{}, } - lb2 := network.LoadBalancer{ + lb2 := &armnetwork.LoadBalancer{ Name: ptr.To("testCluster"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + FrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice")}, }, }, }, }, } - lb3 := network.LoadBalancer{ + lb3 := &armnetwork.LoadBalancer{ Name: ptr.To("testCluster-internal"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + FrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ PrivateIPAddress: ptr.To("10.0.0.6"), }, }, @@ -226,7 +226,7 @@ func TestGetLoadBalancer(t *testing.T) { tests := []struct { desc string service v1.Service - existingLBs []network.LoadBalancer + existingLBs []*armnetwork.LoadBalancer pipExists bool expectedGotLB bool expectedStatus *v1.LoadBalancerStatus @@ -234,7 +234,7 @@ func TestGetLoadBalancer(t *testing.T) { { desc: "GetLoadBalancer should return true when only public IP exists", service: getTestService("service", v1.ProtocolTCP, nil, false, 80), - existingLBs: []network.LoadBalancer{lb1}, + existingLBs: []*armnetwork.LoadBalancer{lb1}, pipExists: true, expectedGotLB: true, expectedStatus: nil, @@ -242,7 +242,7 @@ func TestGetLoadBalancer(t *testing.T) { { desc: "GetLoadBalancer should return false when neither public IP nor LB exists", service: getTestService("service", v1.ProtocolTCP, nil, false, 80), - existingLBs: []network.LoadBalancer{lb1}, + existingLBs: []*armnetwork.LoadBalancer{lb1}, pipExists: false, expectedGotLB: false, expectedStatus: nil, @@ -250,7 +250,7 @@ func TestGetLoadBalancer(t *testing.T) { { desc: "GetLoadBalancer should return true when external service finds external LB", service: getTestService("service", v1.ProtocolTCP, nil, false, 80), - existingLBs: []network.LoadBalancer{lb2}, + existingLBs: []*armnetwork.LoadBalancer{lb2}, pipExists: true, expectedGotLB: true, expectedStatus: &v1.LoadBalancerStatus{ @@ -262,7 +262,7 @@ func TestGetLoadBalancer(t *testing.T) { { desc: "GetLoadBalancer should return true when internal service finds internal LB", service: getInternalTestService("service", 80), - existingLBs: []network.LoadBalancer{lb3}, + existingLBs: []*armnetwork.LoadBalancer{lb3}, expectedGotLB: true, expectedStatus: &v1.LoadBalancerStatus{ Ingress: []v1.LoadBalancerIngress{ @@ -273,7 +273,7 @@ func TestGetLoadBalancer(t *testing.T) { { desc: "GetLoadBalancer should return true when external service finds previous internal LB", service: getTestService("service", v1.ProtocolTCP, nil, false, 80), - existingLBs: []network.LoadBalancer{lb3}, + existingLBs: []*armnetwork.LoadBalancer{lb3}, expectedGotLB: true, expectedStatus: &v1.LoadBalancerStatus{ Ingress: []v1.LoadBalancerIngress{ @@ -284,7 +284,7 @@ func TestGetLoadBalancer(t *testing.T) { { desc: "GetLoadBalancer should return true when external service finds external LB", service: getInternalTestService("service", 80), - existingLBs: []network.LoadBalancer{lb2}, + existingLBs: []*armnetwork.LoadBalancer{lb2}, pipExists: true, expectedGotLB: true, expectedStatus: &v1.LoadBalancerStatus{ @@ -301,20 +301,20 @@ func TestGetLoadBalancer(t *testing.T) { defer ctrl.Finish() az := GetTestCloud(ctrl) - mockPIPsClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) if c.pipExists { - mockPIPsClient.EXPECT().List(gomock.Any(), "rg").Return([]network.PublicIPAddress{ + mockPIPsClient.EXPECT().List(gomock.Any(), "rg").Return([]*armnetwork.PublicIPAddress{ { Name: ptr.To("testCluster-aservice"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, }, nil) } else { - mockPIPsClient.EXPECT().List(gomock.Any(), "rg").Return([]network.PublicIPAddress{}, nil).MaxTimes(2) + mockPIPsClient.EXPECT().List(gomock.Any(), "rg").Return([]*armnetwork.PublicIPAddress{}, nil).MaxTimes(2) } - mockLBsClient := az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + mockLBsClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) mockLBsClient.EXPECT().List(gomock.Any(), az.Config.ResourceGroup).Return(c.existingLBs, nil) service := c.service @@ -329,8 +329,8 @@ func TestGetLoadBalancer(t *testing.T) { func TestFindRule(t *testing.T) { tests := []struct { msg string - existingRule []network.LoadBalancingRule - curRule network.LoadBalancingRule + existingRule []*armnetwork.LoadBalancingRule + curRule *armnetwork.LoadBalancingRule expected bool }{ { @@ -339,17 +339,17 @@ func TestFindRule(t *testing.T) { }, { msg: "rule names don't match should return false", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("httpProbe1"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ FrontendPort: ptr.To(int32(1)), }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("httpProbe2"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ FrontendPort: ptr.To(int32(1)), }, }, @@ -357,37 +357,37 @@ func TestFindRule(t *testing.T) { }, { msg: "rule names match while protocols don't should return false", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("httpRule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Protocol: network.TransportProtocolTCP, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Protocol: to.Ptr(armnetwork.TransportProtocolTCP), }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("httpRule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Protocol: network.TransportProtocolUDP, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Protocol: to.Ptr(armnetwork.TransportProtocolUDP), }, }, expected: false, }, { msg: "rule names match while EnableTCPResets don't should return false", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("httpRule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Protocol: network.TransportProtocolTCP, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Protocol: to.Ptr(armnetwork.TransportProtocolTCP), EnableTCPReset: ptr.To(true), }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("httpRule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Protocol: network.TransportProtocolTCP, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Protocol: to.Ptr(armnetwork.TransportProtocolTCP), EnableTCPReset: ptr.To(false), }, }, @@ -395,17 +395,17 @@ func TestFindRule(t *testing.T) { }, { msg: "rule names match while frontend ports don't should return false", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("httpProbe"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ FrontendPort: ptr.To(int32(1)), }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("httpProbe"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ FrontendPort: ptr.To(int32(2)), }, }, @@ -413,17 +413,17 @@ func TestFindRule(t *testing.T) { }, { msg: "rule names match while backend ports don't should return false", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("httpProbe"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ BackendPort: ptr.To(int32(1)), }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("httpProbe"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ BackendPort: ptr.To(int32(2)), }, }, @@ -431,17 +431,17 @@ func TestFindRule(t *testing.T) { }, { msg: "rule names match while idletimeout don't should return false", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("httpRule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ IdleTimeoutInMinutes: ptr.To(int32(1)), }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("httpRule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ IdleTimeoutInMinutes: ptr.To(int32(2)), }, }, @@ -449,15 +449,15 @@ func TestFindRule(t *testing.T) { }, { msg: "rule names match while idletimeout nil should return true", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { - Name: ptr.To("httpRule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{}, + Name: ptr.To("httpRule"), + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{}, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("httpRule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ IdleTimeoutInMinutes: ptr.To(int32(2)), }, }, @@ -465,148 +465,148 @@ func TestFindRule(t *testing.T) { }, { msg: "rule names match while LoadDistribution don't should return false", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("httpRule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - LoadDistribution: network.LoadDistributionSourceIP, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + LoadDistribution: to.Ptr(armnetwork.LoadDistributionSourceIP), }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("httpRule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - LoadDistribution: network.LoadDistributionDefault, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + LoadDistribution: to.Ptr(armnetwork.LoadDistributionDefault), }, }, expected: false, }, { msg: "rule and probe names match should return true", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("probe1"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Probe: &network.SubResource{ID: ptr.To("probe")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Probe: &armnetwork.SubResource{ID: ptr.To("probe")}, }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("probe1"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Probe: &network.SubResource{ID: ptr.To("probe")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Probe: &armnetwork.SubResource{ID: ptr.To("probe")}, }, }, expected: true, }, { msg: "rule names match while probe don't should return false", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("probe1"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ Probe: nil, }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("probe1"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Probe: &network.SubResource{ID: ptr.To("probe")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Probe: &armnetwork.SubResource{ID: ptr.To("probe")}, }, }, expected: false, }, { msg: "both rule names and LoadBalancingRulePropertiesFormats match should return true", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("matchName"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ BackendPort: ptr.To(int32(2)), FrontendPort: ptr.To(int32(2)), - LoadDistribution: network.LoadDistributionSourceIP, + LoadDistribution: to.Ptr(armnetwork.LoadDistributionSourceIP), }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("matchName"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ BackendPort: ptr.To(int32(2)), FrontendPort: ptr.To(int32(2)), - LoadDistribution: network.LoadDistributionSourceIP, + LoadDistribution: to.Ptr(armnetwork.LoadDistributionSourceIP), }, }, expected: true, }, { msg: "rule and FrontendIPConfiguration names match should return true", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("matchName"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("FrontendIPConfiguration")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("FrontendIPConfiguration")}, }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("matchName"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("frontendipconfiguration")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("frontendipconfiguration")}, }, }, expected: true, }, { msg: "rule names match while FrontendIPConfiguration don't should return false", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("matchName"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("FrontendIPConfiguration")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("FrontendIPConfiguration")}, }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("matchName"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("frontendipconifguration")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("frontendipconifguration")}, }, }, expected: false, }, { msg: "rule and BackendAddressPool names match should return true", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("matchName"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - BackendAddressPool: &network.SubResource{ID: ptr.To("BackendAddressPool")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + BackendAddressPool: &armnetwork.SubResource{ID: ptr.To("BackendAddressPool")}, }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("matchName"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - BackendAddressPool: &network.SubResource{ID: ptr.To("backendaddresspool")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + BackendAddressPool: &armnetwork.SubResource{ID: ptr.To("backendaddresspool")}, }, }, expected: true, }, { msg: "rule and Probe names match should return true", - existingRule: []network.LoadBalancingRule{ + existingRule: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("matchName"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Probe: &network.SubResource{ID: ptr.To("Probe")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Probe: &armnetwork.SubResource{ID: ptr.To("Probe")}, }, }, }, - curRule: network.LoadBalancingRule{ + curRule: &armnetwork.LoadBalancingRule{ Name: ptr.To("matchName"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Probe: &network.SubResource{ID: ptr.To("probe")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Probe: &armnetwork.SubResource{ID: ptr.To("probe")}, }, }, expected: true, @@ -734,66 +734,63 @@ func TestEnsureLoadBalancerDeleted(t *testing.T) { }, } - ctrl := gomock.NewController(t) - defer ctrl.Finish() - az := GetTestCloud(ctrl) - mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { - return false, false, lb, nil - }).AnyTimes() - mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - mockLBBackendPool.EXPECT().GetBackendPrivateIPs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + for i, c := range tests { + i := i + c := c + t.Run(c.desc, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + az := GetTestCloud(ctrl) + mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { + return false, false, lb, nil + }).AnyTimes() + mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + mockLBBackendPool.EXPECT().GetBackendPrivateIPs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, vmCount, availabilitySetCount) - setMockEnv(az, ctrl, expectedInterfaces, expectedVirtualMachines, 5) + clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, vmCount, availabilitySetCount) + setMockEnv(az, expectedInterfaces, expectedVirtualMachines, 5) - for i, c := range tests { - service := c.service - if c.service.Annotations[consts.ServiceAnnotationLoadBalancerInternal] == "true" { - validateTestSubnet(t, az, &service) - } + service := c.service + if c.service.Annotations[consts.ServiceAnnotationLoadBalancerInternal] == "true" { + validateTestSubnet(t, az, &service) + } - expectedLBs := make([]network.LoadBalancer, 0) - setMockLBs(az, ctrl, &expectedLBs, "service", 1, i+1, c.isInternalSvc) + expectedLBs := make([]*armnetwork.LoadBalancer, 0) + setMockLBs(az, &expectedLBs, "service", 1, i+1, c.isInternalSvc) - mockPLSRepo := privatelinkservice.NewMockRepository(ctrl) - mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil).AnyTimes() - az.plsRepo = mockPLSRepo + mockPLSRepo := privatelinkservice.NewMockRepository(ctrl) + mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil).AnyTimes() + az.plsRepo = mockPLSRepo - // create the service first. - lbStatus, err := az.EnsureLoadBalancer(context.TODO(), testClusterName, &service, clusterResources.nodes) - if c.expectCreateError { - assert.NotNil(t, err, "TestCase[%d]: %s", i, c.desc) - } else { - assert.Nil(t, err, "TestCase[%d]: %s", i, c.desc) - assert.NotNil(t, lbStatus, "TestCase[%d]: %s", i, c.desc) - result, rerr := az.LoadBalancerClient.List(context.TODO(), az.Config.ResourceGroup) - assert.Nil(t, rerr, "TestCase[%d]: %s", i, c.desc) - assert.Equal(t, 1, len(result), "TestCase[%d]: %s", i, c.desc) - assert.Equal(t, 1, len(*result[0].LoadBalancingRules), "TestCase[%d]: %s", i, c.desc) - } + // create the service first. + lbStatus, err := az.EnsureLoadBalancer(context.TODO(), testClusterName, &service, clusterResources.nodes) + if c.expectCreateError { + assert.NotNil(t, err, "TestCase[%d]: %s", i, c.desc) + } else { + assert.Nil(t, err, "TestCase[%d]: %s", i, c.desc) + assert.NotNil(t, lbStatus, "TestCase[%d]: %s", i, c.desc) + result, rerr := az.NetworkClientFactory.GetLoadBalancerClient().List(context.TODO(), az.Config.ResourceGroup) + assert.Nil(t, rerr, "TestCase[%d]: %s", i, c.desc) + assert.Equal(t, 1, len(result), "TestCase[%d]: %s", i, c.desc) + assert.Equal(t, 1, len(result[0].Properties.LoadBalancingRules), "TestCase[%d]: %s", i, c.desc) + } - // finally, delete it. - if c.wrongRGAtDelete { - az.LoadBalancerResourceGroup = "nil" - } - if c.flipService { - flippedService := flipServiceInternalAnnotation(&service) - c.service = *flippedService - c.isInternalSvc = !c.isInternalSvc - } - expectedLBs = make([]network.LoadBalancer, 0) - setMockLBs(az, ctrl, &expectedLBs, "service", 1, i+1, c.isInternalSvc) - - err = az.EnsureLoadBalancerDeleted(context.TODO(), testClusterName, &service) - expectedLBs = make([]network.LoadBalancer, 0) - mockLBsClient := mockloadbalancerclient.NewMockInterface(ctrl) - mockLBsClient.EXPECT().List(gomock.Any(), az.Config.ResourceGroup).Return(expectedLBs, nil).MaxTimes(2) - az.LoadBalancerClient = mockLBsClient - assert.Nil(t, err, "TestCase[%d]: %s", i, c.desc) - result, rerr := az.LoadBalancerClient.List(context.TODO(), az.Config.ResourceGroup) - assert.Nil(t, rerr, "TestCase[%d]: %s", i, c.desc) - assert.Equal(t, 0, len(result), "TestCase[%d]: %s", i, c.desc) + // finally, delete it. + if c.wrongRGAtDelete { + az.LoadBalancerResourceGroup = "nil" + } + if c.flipService { + flippedService := flipServiceInternalAnnotation(&service) + c.service = *flippedService + c.isInternalSvc = !c.isInternalSvc + } + expectedLBs = make([]*armnetwork.LoadBalancer, 0) + setMockLBs(az, &expectedLBs, "service", 1, i+1, c.isInternalSvc) + + err = az.EnsureLoadBalancerDeleted(context.TODO(), testClusterName, &service) + assert.Nil(t, err, "TestCase[%d]: %s", i, c.desc) + }) } } @@ -843,9 +840,9 @@ func TestEnsureLoadBalancerLock(t *testing.T) { az.azureResourceLocker = NewAzureResourceLocker( az, "holder", "aks-managed-resource-locker", "kube-system", 900, ) - mockLBClient := az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + mockLBClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) mockLBClient.EXPECT().List(gomock.Any(), gomock.Any()). - Return(nil, retry.NewError(false, errors.New("list lb failed"))) + Return(nil, &azcore.ResponseError{ErrorCode: "list lb failed"}) _, err = az.EnsureLoadBalancer(context.Background(), testClusterName, &svc, nil) assert.Error(t, err) @@ -899,9 +896,9 @@ func TestEnsureLoadBalancerDeletedLock(t *testing.T) { az.azureResourceLocker = NewAzureResourceLocker( az, "holder", "aks-managed-resource-locker", "kube-system", 900, ) - mockLBClient := az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + mockLBClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) mockLBClient.EXPECT().List(gomock.Any(), gomock.Any()). - Return(nil, retry.NewError(false, errors.New("list lb failed"))) + Return(nil, &azcore.ResponseError{ErrorCode: "list lb failed"}) err = az.EnsureLoadBalancerDeleted(context.Background(), testClusterName, &svc) assert.Error(t, err) @@ -912,7 +909,7 @@ func TestEnsureLoadBalancerDeletedLock(t *testing.T) { func TestServiceOwnsPublicIP(t *testing.T) { tests := []struct { desc string - pip *network.PublicIPAddress + pip *armnetwork.PublicIPAddress clusterName string serviceName string serviceLBIP string @@ -928,12 +925,12 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "false should be returned when service name tag doesn't match", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("default/nginx"), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -942,11 +939,11 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "true should be returned when service name tag matches and cluster name tag is not set", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("default/nginx"), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -956,12 +953,12 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "false should be returned when cluster name doesn't match", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("default/nginx"), consts.ClusterNameKey: ptr.To("kubernetes"), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -971,13 +968,13 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "false should be returned when cluster name matches while service name doesn't match", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("default/web"), consts.ClusterNameKey: ptr.To("kubernetes"), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -987,12 +984,12 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "true should be returned when both service name tag and cluster name match", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("default/nginx"), consts.ClusterNameKey: ptr.To("kubernetes"), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -1002,13 +999,13 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "false should be returned when the tag is empty and load balancer IP does not match", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), Tags: map[string]*string{ consts.ServiceTagKey: ptr.To(""), consts.ClusterNameKey: ptr.To("kubernetes"), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -1019,12 +1016,12 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "true should be returned if there is a match among a multi-service tag", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("default/nginx1,default/nginx2"), consts.ClusterNameKey: ptr.To("kubernetes"), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -1034,13 +1031,13 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "false should be returned if there is not a match among a multi-service tag", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("default/nginx1,default/nginx2"), consts.ClusterNameKey: ptr.To("kubernetes"), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -1050,12 +1047,12 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "true should be returned if the load balancer IP is matched even if the svc name is not included in the tag", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Tags: map[string]*string{ consts.ServiceTagKey: ptr.To(""), consts.ClusterNameKey: ptr.To("kubernetes"), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -1067,12 +1064,12 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "true should be returned if the load balancer IP is not matched but the svc name is included in the tag", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("default/nginx1,default/nginx2"), consts.ClusterNameKey: ptr.To("kubernetes"), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -1083,8 +1080,8 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "should be user-assigned pip if it has no tags", - pip: &network.PublicIPAddress{ - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + pip: &armnetwork.PublicIPAddress{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -1094,9 +1091,9 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "should be true if the pip name matches", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -1106,10 +1103,10 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "should be true if the pip with tag matches the pip name", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), Tags: map[string]*string{}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -1119,12 +1116,12 @@ func TestServiceOwnsPublicIP(t *testing.T) { }, { desc: "should be true if the pip with service tag matches the pip name", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("default/web"), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -1188,13 +1185,13 @@ func TestGetPublicIPAddressResourceGroup(t *testing.T) { } func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { - existingPipWithTag := network.PublicIPAddress{ + existingPipWithTag := armnetwork.PublicIPAddress{ ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), Name: ptr.To("testPIP"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, - PublicIPAllocationMethod: network.Static, - IPTags: &[]network.IPTag{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), + IPTags: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -1203,19 +1200,19 @@ func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { }, } existingPipWithTagIPv6Suffix := existingPipWithTag - existingPipWithTagIPv6Suffix.Name = ptr.To("testPIP-IPv6") + existingPipWithTagIPv6Suffix.Name = to.Ptr("testPIP-IPv6") - existingPipWithNoPublicIPAddressFormatProperties := network.PublicIPAddress{ - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), - Name: ptr.To("testPIP"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test2")}, - PublicIPAddressPropertiesFormat: nil, + existingPipWithNoPublicIPAddressFormatProperties := armnetwork.PublicIPAddress{ + ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), + Name: ptr.To("testPIP"), + Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test2")}, + Properties: nil, } tests := []struct { desc string desiredPipName string - existingPip network.PublicIPAddress + existingPip armnetwork.PublicIPAddress ipTagRequest serviceIPTagRequest lbShouldExist bool lbIsInternal bool @@ -1231,7 +1228,7 @@ func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { desiredPipName: *existingPipWithTag.Name, ipTagRequest: serviceIPTagRequest{ IPTagsRequestedByAnnotation: true, - IPTags: existingPipWithTag.PublicIPAddressPropertiesFormat.IPTags, + IPTags: existingPipWithTag.Properties.IPTags, }, expectedShouldRelease: false, }, @@ -1255,7 +1252,7 @@ func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { desiredPipName: *existingPipWithTag.Name, ipTagRequest: serviceIPTagRequest{ IPTagsRequestedByAnnotation: true, - IPTags: existingPipWithTag.PublicIPAddressPropertiesFormat.IPTags, + IPTags: existingPipWithTag.Properties.IPTags, }, expectedShouldRelease: true, }, @@ -1267,7 +1264,7 @@ func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { desiredPipName: *existingPipWithTag.Name, ipTagRequest: serviceIPTagRequest{ IPTagsRequestedByAnnotation: true, - IPTags: existingPipWithTag.PublicIPAddressPropertiesFormat.IPTags, + IPTags: existingPipWithTag.Properties.IPTags, }, expectedShouldRelease: true, }, @@ -1279,7 +1276,7 @@ func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { desiredPipName: *existingPipWithTag.Name, ipTagRequest: serviceIPTagRequest{ IPTagsRequestedByAnnotation: true, - IPTags: existingPipWithTag.PublicIPAddressPropertiesFormat.IPTags, + IPTags: existingPipWithTag.Properties.IPTags, }, expectedShouldRelease: true, }, @@ -1291,7 +1288,7 @@ func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { desiredPipName: "otherName", ipTagRequest: serviceIPTagRequest{ IPTagsRequestedByAnnotation: true, - IPTags: existingPipWithTag.PublicIPAddressPropertiesFormat.IPTags, + IPTags: existingPipWithTag.Properties.IPTags, }, expectedShouldRelease: true, }, @@ -1303,7 +1300,7 @@ func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { desiredPipName: *existingPipWithTag.Name, ipTagRequest: serviceIPTagRequest{ IPTagsRequestedByAnnotation: true, - IPTags: &[]network.IPTag{ + IPTags: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag2"), Tag: ptr.To("tag2value"), @@ -1322,7 +1319,7 @@ func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { desiredPipName: *existingPipWithTag.Name, ipTagRequest: serviceIPTagRequest{ IPTagsRequestedByAnnotation: true, - IPTags: &[]network.IPTag{ + IPTags: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -1340,7 +1337,7 @@ func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { serviceReferences: []string{}, ipTagRequest: serviceIPTagRequest{ IPTagsRequestedByAnnotation: true, - IPTags: existingPipWithTag.PublicIPAddressPropertiesFormat.IPTags, + IPTags: existingPipWithTag.Properties.IPTags, }, expectedShouldRelease: true, }, @@ -1353,7 +1350,7 @@ func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { serviceReferences: []string{"svc1"}, ipTagRequest: serviceIPTagRequest{ IPTagsRequestedByAnnotation: true, - IPTags: existingPipWithTag.PublicIPAddressPropertiesFormat.IPTags, + IPTags: existingPipWithTag.Properties.IPTags, }, }, { @@ -1365,7 +1362,7 @@ func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { serviceReferences: []string{}, ipTagRequest: serviceIPTagRequest{ IPTagsRequestedByAnnotation: true, - IPTags: existingPipWithTag.PublicIPAddressPropertiesFormat.IPTags, + IPTags: existingPipWithTag.Properties.IPTags, }, isUserAssignedPIP: true, }, @@ -1458,7 +1455,7 @@ func TestConvertIPTagMapToSlice(t *testing.T) { tests := []struct { desc string input map[string]string - expected *[]network.IPTag + expected []*armnetwork.IPTag }{ { desc: "nil slice should be returned when the map is nil", @@ -1468,14 +1465,14 @@ func TestConvertIPTagMapToSlice(t *testing.T) { { desc: "empty slice should be returned when the map is empty", input: map[string]string{}, - expected: &[]network.IPTag{}, + expected: []*armnetwork.IPTag{}, }, { desc: "one tag should be returned when the map has one tag", input: map[string]string{ "tag1": "tag1value", }, - expected: &[]network.IPTag{ + expected: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -1488,7 +1485,7 @@ func TestConvertIPTagMapToSlice(t *testing.T) { "tag1": "tag1value", "tag2": "tag2value", }, - expected: &[]network.IPTag{ + expected: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -1507,14 +1504,14 @@ func TestConvertIPTagMapToSlice(t *testing.T) { // Sort output to provide stability of return from map for test comparison // The order doesn't matter at runtime. if actual != nil { - sort.Slice(*actual, func(i, j int) bool { - ipTagSlice := *actual + sort.Slice(actual, func(i, j int) bool { + ipTagSlice := actual return ptr.Deref(ipTagSlice[i].IPTagType, "") < ptr.Deref(ipTagSlice[j].IPTagType, "") }) } if c.expected != nil { - sort.Slice(*c.expected, func(i, j int) bool { - ipTagSlice := *c.expected + sort.Slice(c.expected, func(i, j int) bool { + ipTagSlice := c.expected return ptr.Deref(ipTagSlice[i].IPTagType, "") < ptr.Deref(ipTagSlice[j].IPTagType, "") }) } @@ -1560,7 +1557,7 @@ func TestGetserviceIPTagRequestForPublicIP(t *testing.T) { }, expected: serviceIPTagRequest{ IPTagsRequestedByAnnotation: true, - IPTags: &[]network.IPTag{}, + IPTags: []*armnetwork.IPTag{}, }, }, { @@ -1574,7 +1571,7 @@ func TestGetserviceIPTagRequestForPublicIP(t *testing.T) { }, expected: serviceIPTagRequest{ IPTagsRequestedByAnnotation: true, - IPTags: &[]network.IPTag{ + IPTags: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -1593,14 +1590,14 @@ func TestGetserviceIPTagRequestForPublicIP(t *testing.T) { // Sort output to provide stability of return from map for test comparison // The order doesn't matter at runtime. if actual.IPTags != nil { - sort.Slice(*actual.IPTags, func(i, j int) bool { - ipTagSlice := *actual.IPTags + sort.Slice(actual.IPTags, func(i, j int) bool { + ipTagSlice := actual.IPTags return ptr.Deref(ipTagSlice[i].IPTagType, "") < ptr.Deref(ipTagSlice[j].IPTagType, "") }) } if c.expected.IPTags != nil { - sort.Slice(*c.expected.IPTags, func(i, j int) bool { - ipTagSlice := *c.expected.IPTags + sort.Slice(c.expected.IPTags, func(i, j int) bool { + ipTagSlice := c.expected.IPTags return ptr.Deref(ipTagSlice[i].IPTagType, "") < ptr.Deref(ipTagSlice[j].IPTagType, "") }) } @@ -1612,8 +1609,8 @@ func TestGetserviceIPTagRequestForPublicIP(t *testing.T) { func TestAreIpTagsEquivalent(t *testing.T) { tests := []struct { desc string - input1 *[]network.IPTag - input2 *[]network.IPTag + input1 []*armnetwork.IPTag + input2 []*armnetwork.IPTag expected bool }{ { @@ -1625,18 +1622,18 @@ func TestAreIpTagsEquivalent(t *testing.T) { { desc: "nils should be considered to empty arrays (case 1)", input1: nil, - input2: &[]network.IPTag{}, + input2: []*armnetwork.IPTag{}, expected: true, }, { desc: "nils should be considered to empty arrays (case 1)", - input1: &[]network.IPTag{}, + input1: []*armnetwork.IPTag{}, input2: nil, expected: true, }, { desc: "nil should not be considered equal to anything (case 1)", - input1: &[]network.IPTag{ + input1: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -1651,7 +1648,7 @@ func TestAreIpTagsEquivalent(t *testing.T) { }, { desc: "nil should not be considered equal to anything (case 2)", - input2: &[]network.IPTag{ + input2: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -1666,7 +1663,7 @@ func TestAreIpTagsEquivalent(t *testing.T) { }, { desc: "exactly equal should be treated as equal", - input1: &[]network.IPTag{ + input1: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -1676,7 +1673,7 @@ func TestAreIpTagsEquivalent(t *testing.T) { Tag: ptr.To("tag2value"), }, }, - input2: &[]network.IPTag{ + input2: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -1690,7 +1687,7 @@ func TestAreIpTagsEquivalent(t *testing.T) { }, { desc: "equal but out of order should be treated as equal", - input1: &[]network.IPTag{ + input1: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -1700,7 +1697,7 @@ func TestAreIpTagsEquivalent(t *testing.T) { Tag: ptr.To("tag2value"), }, }, - input2: &[]network.IPTag{ + input2: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag2"), Tag: ptr.To("tag2value"), @@ -1725,27 +1722,27 @@ func TestGetServiceLoadBalancerMultiSLB(t *testing.T) { for _, tc := range []struct { description string - existingLBs []network.LoadBalancer - refreshedLBs []network.LoadBalancer - existingPIPs []network.PublicIPAddress + existingLBs []*armnetwork.LoadBalancer + refreshedLBs []*armnetwork.LoadBalancer + existingPIPs []*armnetwork.PublicIPAddress service v1.Service local bool multiSLBConfigs []config.MultipleStandardLoadBalancerConfiguration - expectedLB *network.LoadBalancer - expectedLBs *[]network.LoadBalancer + expectedLB *armnetwork.LoadBalancer + expectedLBs []*armnetwork.LoadBalancer expectedError error }{ { description: "should return the existing lb if the service is moved to the lb", - existingLBs: []network.LoadBalancer{ + existingLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("lb1-internal"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + FrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("atest1"), ID: ptr.To("atest1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ PrivateIPAddress: ptr.To("1.2.3.4"), }, }, @@ -1768,32 +1765,32 @@ func TestGetServiceLoadBalancerMultiSLB(t *testing.T) { }, }, }, - expectedLB: &network.LoadBalancer{ + expectedLB: &armnetwork.LoadBalancer{ Name: ptr.To("lb2-internal"), }, - expectedLBs: &[]network.LoadBalancer{ + expectedLBs: []*armnetwork.LoadBalancer{ {Name: ptr.To("lb2-internal")}, }, }, { description: "remove backend pool when a local service changes its load balancer", - existingLBs: []network.LoadBalancer{ + existingLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("lb1"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + FrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("atest1"), ID: ptr.To("atest1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("pip")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("pip")}, }, }, { Name: ptr.To("atest2"), }, }, - BackendAddressPools: &[]network.BackendAddressPool{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("kubernetes"), }, @@ -1804,23 +1801,23 @@ func TestGetServiceLoadBalancerMultiSLB(t *testing.T) { }, }, }, - refreshedLBs: []network.LoadBalancer{ + refreshedLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("lb1"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + FrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("atest1"), ID: ptr.To("atest1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("pip")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("pip")}, }, }, { Name: ptr.To("atest2"), }, }, - BackendAddressPools: &[]network.BackendAddressPool{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("kubernetes"), }, @@ -1828,10 +1825,10 @@ func TestGetServiceLoadBalancerMultiSLB(t *testing.T) { }, }, }, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -1849,31 +1846,31 @@ func TestGetServiceLoadBalancerMultiSLB(t *testing.T) { }, }, }, - expectedLB: &network.LoadBalancer{ + expectedLB: &armnetwork.LoadBalancer{ Name: ptr.To("lb2"), Location: ptr.To("westus"), - Sku: &network.LoadBalancerSku{ - Name: network.LoadBalancerSkuNameStandard, + SKU: &armnetwork.LoadBalancerSKU{ + Name: to.Ptr(armnetwork.LoadBalancerSKUNameStandard), }, - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, + Properties: &armnetwork.LoadBalancerPropertiesFormat{}, }, - expectedLBs: &[]network.LoadBalancer{ + expectedLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("lb1"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + FrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("atest1"), ID: ptr.To("atest1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("pip")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("pip")}, }, }, { Name: ptr.To("atest2"), }, }, - BackendAddressPools: &[]network.BackendAddressPool{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("kubernetes"), }, @@ -1886,28 +1883,27 @@ func TestGetServiceLoadBalancerMultiSLB(t *testing.T) { tc := tc t.Run(tc.description, func(t *testing.T) { cloud := GetTestCloud(ctrl) - cloud.LoadBalancerSku = "Standard" + cloud.LoadBalancerSKU = "Standard" cloud.MultipleStandardLoadBalancerConfigurations = tc.multiSLBConfigs - lbClient := mockloadbalancerclient.NewMockInterface(ctrl) + lbClient := cloud.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) lbClient.EXPECT().Delete(gomock.Any(), gomock.Any(), "lb1-internal").MaxTimes(1) - lbClient.EXPECT().DeleteLBBackendPool(gomock.Any(), gomock.Any(), "lb1", "default-test1").Return(nil).MaxTimes(1) + bpClient := cloud.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) + bpClient.EXPECT().Delete(gomock.Any(), gomock.Any(), "lb1", "default-test1").Return(nil).MaxTimes(1) lbClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.refreshedLBs, nil).MaxTimes(1) - lbClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).MaxTimes(1) - cloud.LoadBalancerClient = lbClient + lbClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).MaxTimes(1) mockPLSRepo := cloud.plsRepo.(*privatelinkservice.MockRepository) mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil) - mockPIPClient := mockpublicipclient.NewMockInterface(ctrl) - mockPIPClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]network.PublicIPAddress{}, nil).MaxTimes(2) - cloud.PublicIPAddressesClient = mockPIPClient + mockPIPClient := cloud.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + mockPIPClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armnetwork.PublicIPAddress{}, nil).MaxTimes(2) if tc.local { tc.service.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyLocal } lb, lbs, _, _, _, err := cloud.getServiceLoadBalancer(context.TODO(), &tc.service, testClusterName, - []*v1.Node{}, true, &tc.existingLBs) + []*v1.Node{}, true, tc.existingLBs) assert.Equal(t, tc.expectedError, err) assert.Equal(t, tc.expectedLB, lb) assert.Equal(t, tc.expectedLBs, lbs) @@ -1918,11 +1914,11 @@ func TestGetServiceLoadBalancerMultiSLB(t *testing.T) { func TestGetServiceLoadBalancerCommon(t *testing.T) { testCases := []struct { desc string - sku string - existingLBs []network.LoadBalancer + SKU string + existingLBs []*armnetwork.LoadBalancer service v1.Service annotations map[string]string - expectedLB *network.LoadBalancer + expectedLB *armnetwork.LoadBalancer expectedStatus *v1.LoadBalancerStatus wantLB bool expectedExists bool @@ -1930,15 +1926,17 @@ func TestGetServiceLoadBalancerCommon(t *testing.T) { }{ { desc: "getServiceLoadBalancer shall return corresponding lb, status, exists if there are existed lbs", - existingLBs: []network.LoadBalancer{ + existingLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("testCluster"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + FrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ + ID: ptr.To("testCluster-aservice1"), + }, }, }, }, @@ -1947,14 +1945,14 @@ func TestGetServiceLoadBalancerCommon(t *testing.T) { }, service: getTestService("service1", v1.ProtocolTCP, nil, false, 80), wantLB: false, - expectedLB: &network.LoadBalancer{ + expectedLB: &armnetwork.LoadBalancer{ Name: ptr.To("testCluster"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + FrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, }, }, }, @@ -1965,21 +1963,21 @@ func TestGetServiceLoadBalancerCommon(t *testing.T) { expectedError: false, }, { - desc: "getServiceLoadBalancer shall select the lb with minimum lb rules if wantLb is true, the sku is " + + desc: "getServiceLoadBalancer shall select the lb with minimum lb rules if wantLb is true, the SKU is " + "not standard and there are existing lbs already", - existingLBs: []network.LoadBalancer{ + existingLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("testCluster"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ {Name: ptr.To("rule1")}, }, }, }, { Name: ptr.To("as-1"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ {Name: ptr.To("rule1")}, {Name: ptr.To("rule2")}, }, @@ -1987,8 +1985,8 @@ func TestGetServiceLoadBalancerCommon(t *testing.T) { }, { Name: ptr.To("as-2"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ {Name: ptr.To("rule1")}, {Name: ptr.To("rule2")}, {Name: ptr.To("rule3")}, @@ -1999,10 +1997,10 @@ func TestGetServiceLoadBalancerCommon(t *testing.T) { service: getTestService("service1", v1.ProtocolTCP, nil, false, 80), annotations: map[string]string{consts.ServiceAnnotationLoadBalancerMode: "__auto__"}, wantLB: true, - expectedLB: &network.LoadBalancer{ + expectedLB: &armnetwork.LoadBalancer{ Name: ptr.To("testCluster"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ {Name: ptr.To("rule1")}, }, }, @@ -2013,43 +2011,46 @@ func TestGetServiceLoadBalancerCommon(t *testing.T) { { desc: "getServiceLoadBalancer shall create a new lb otherwise", service: getTestService("service1", v1.ProtocolTCP, nil, false, 80), - expectedLB: &network.LoadBalancer{ - Name: ptr.To("testCluster"), - Location: ptr.To("westus"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, + expectedLB: &armnetwork.LoadBalancer{ + Name: ptr.To("testCluster"), + Location: ptr.To("westus"), + Properties: &armnetwork.LoadBalancerPropertiesFormat{}, }, expectedExists: false, expectedError: false, }, } - ctrl := gomock.NewController(t) - defer ctrl.Finish() for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() az := GetTestCloud(ctrl) clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 3, 3) - setMockEnv(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnv(az, expectedInterfaces, expectedVirtualMachines, 1) - mockLBsClient := mockloadbalancerclient.NewMockInterface(ctrl) - mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).Times(len(test.existingLBs)) + mockLBsClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", gomock.Any(), gomock.Any()).Return(nil, nil).Times(len(test.existingLBs)) mockLBsClient.EXPECT().List(gomock.Any(), "rg").Return(test.existingLBs, nil) mockLBsClient.EXPECT().Delete(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - az.LoadBalancerClient = mockLBsClient for _, existingLB := range test.existingLBs { - err := az.LoadBalancerClient.CreateOrUpdate(context.TODO(), "rg", *existingLB.Name, existingLB, "") - assert.NoError(t, err.Error()) + _, err := az.NetworkClientFactory.GetLoadBalancerClient().CreateOrUpdate(context.TODO(), "rg", *existingLB.Name, *existingLB) + assert.NoError(t, err) } if test.annotations != nil { test.service.Annotations = test.annotations } - az.LoadBalancerSku = test.sku + az.LoadBalancerSKU = test.SKU service := test.service lb, _, status, _, exists, err := az.getServiceLoadBalancer(context.TODO(), &service, testClusterName, - clusterResources.nodes, test.wantLB, &[]network.LoadBalancer{}) + clusterResources.nodes, test.wantLB, []*armnetwork.LoadBalancer{}) assert.Equal(t, test.expectedLB, lb) - assert.Equal(t, test.expectedStatus, status) + if test.expectedStatus != nil { + assert.Equal(t, *test.expectedStatus, *status) + } else { + assert.Nil(t, status) + } assert.Equal(t, test.expectedExists, exists) assert.Equal(t, test.expectedError, err != nil) }) @@ -2063,75 +2064,70 @@ func TestGetServiceLoadBalancerWithExtendedLocation(t *testing.T) { az := GetTestCloudWithExtendedLocation(ctrl) clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 3, 3) - setMockEnv(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnv(az, expectedInterfaces, expectedVirtualMachines, 1) // Test with wantLB=false - expectedLB := &network.LoadBalancer{ + expectedLB := &armnetwork.LoadBalancer{ Name: ptr.To("testCluster"), Location: ptr.To("westus"), - ExtendedLocation: &network.ExtendedLocation{ + ExtendedLocation: &armnetwork.ExtendedLocation{ Name: ptr.To("microsoftlosangeles1"), - Type: network.EdgeZone, + Type: to.Ptr(armnetwork.ExtendedLocationTypesEdgeZone), }, - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, + Properties: &armnetwork.LoadBalancerPropertiesFormat{}, } - mockLBsClient := mockloadbalancerclient.NewMockInterface(ctrl) + mockLBsClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) mockLBsClient.EXPECT().List(gomock.Any(), "rg").Return(nil, nil) - az.LoadBalancerClient = mockLBsClient lb, _, status, _, exists, err := az.getServiceLoadBalancer(context.TODO(), &service, testClusterName, - clusterResources.nodes, false, &[]network.LoadBalancer{}) + clusterResources.nodes, false, []*armnetwork.LoadBalancer{}) assert.Equal(t, expectedLB, lb, "GetServiceLoadBalancer shall return a default LB with expected location.") assert.Nil(t, status, "GetServiceLoadBalancer: Status should be nil for default LB.") assert.Equal(t, false, exists, "GetServiceLoadBalancer: Default LB should not exist.") assert.NoError(t, err, "GetServiceLoadBalancer: No error should be thrown when returning default LB.") // Test with wantLB=true - expectedLB = &network.LoadBalancer{ + expectedLB = &armnetwork.LoadBalancer{ Name: ptr.To("testCluster"), Location: ptr.To("westus"), - ExtendedLocation: &network.ExtendedLocation{ + ExtendedLocation: &armnetwork.ExtendedLocation{ Name: ptr.To("microsoftlosangeles1"), - Type: network.EdgeZone, + Type: to.Ptr(armnetwork.ExtendedLocationTypesEdgeZone), }, - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, - Sku: &network.LoadBalancerSku{ - Name: network.LoadBalancerSkuName("Basic"), - Tier: network.LoadBalancerSkuTier(""), + Properties: &armnetwork.LoadBalancerPropertiesFormat{}, + SKU: &armnetwork.LoadBalancerSKU{ + Name: to.Ptr(armnetwork.LoadBalancerSKUNameBasic), }, } - mockLBsClient = mockloadbalancerclient.NewMockInterface(ctrl) + mockLBsClient = az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) mockLBsClient.EXPECT().List(gomock.Any(), "rg").Return(nil, nil) - az.LoadBalancerClient = mockLBsClient lb, _, status, _, exists, err = az.getServiceLoadBalancer(context.TODO(), &service, testClusterName, - clusterResources.nodes, true, &[]network.LoadBalancer{}) - assert.Equal(t, expectedLB, lb, "GetServiceLoadBalancer shall return a new LB with expected location.") + clusterResources.nodes, true, []*armnetwork.LoadBalancer{}) + assert.Equal(t, *expectedLB, *lb, "GetServiceLoadBalancer shall return a new LB with expected location.") assert.Nil(t, status, "GetServiceLoadBalancer: Status should be nil for new LB.") assert.Equal(t, false, exists, "GetServiceLoadBalancer: LB should not exist before hand.") assert.NoError(t, err, "GetServiceLoadBalancer: No error should be thrown when returning new LB.") } func TestIsFrontendIPChanged(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { desc string - config network.FrontendIPConfiguration + config *armnetwork.FrontendIPConfiguration service v1.Service lbFrontendIPConfigName string annotations string loadBalancerIP string - existingSubnet network.Subnet - existingPIPs []network.PublicIPAddress + existingSubnet *armnetwork.Subnet + existingPIPs []*armnetwork.PublicIPAddress expectedFlag bool expectedError bool }{ { desc: "isFrontendIPChanged shall return true if config.Name has a prefix of lb's name and " + "config.Name != lbFrontendIPConfigName", - config: network.FrontendIPConfiguration{Name: ptr.To("atest1-name")}, + config: &armnetwork.FrontendIPConfiguration{Name: ptr.To("atest1-name")}, service: getInternalTestService("test1", 80), lbFrontendIPConfigName: "configName", expectedFlag: true, @@ -2140,7 +2136,7 @@ func TestIsFrontendIPChanged(t *testing.T) { { desc: "isFrontendIPChanged shall return false if config.Name doesn't have a prefix of lb's name " + "and config.Name != lbFrontendIPConfigName", - config: network.FrontendIPConfiguration{Name: ptr.To("btest1-name")}, + config: &armnetwork.FrontendIPConfiguration{Name: ptr.To("btest1-name")}, service: getInternalTestService("test1", 80), lbFrontendIPConfigName: "configName", expectedFlag: false, @@ -2149,10 +2145,10 @@ func TestIsFrontendIPChanged(t *testing.T) { { desc: "isFrontendIPChanged shall return false if the service is internal, no loadBalancerIP is given, " + "subnetName == nil and config.PrivateIPAllocationMethod == network.Static", - config: network.FrontendIPConfiguration{ + config: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("btest1-name"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAllocationMethod: network.Static, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), }, }, lbFrontendIPConfigName: "btest1-name", @@ -2163,10 +2159,10 @@ func TestIsFrontendIPChanged(t *testing.T) { { desc: "isFrontendIPChanged shall return false if the service is internal, no loadBalancerIP is given, " + "subnetName == nil and config.PrivateIPAllocationMethod != network.Static", - config: network.FrontendIPConfiguration{ + config: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("btest1-name"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAllocationMethod: network.Dynamic, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), }, }, lbFrontendIPConfigName: "btest1-name", @@ -2177,26 +2173,26 @@ func TestIsFrontendIPChanged(t *testing.T) { { desc: "isFrontendIPChanged shall return true if the service is internal and " + "config.Subnet.ID != subnet.ID", - config: network.FrontendIPConfiguration{ + config: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("btest1-name"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - Subnet: &network.Subnet{ID: ptr.To("testSubnet")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + Subnet: &armnetwork.Subnet{ID: ptr.To("testSubnet")}, }, }, lbFrontendIPConfigName: "btest1-name", service: getInternalTestService("test1", 80), annotations: "testSubnet", - existingSubnet: network.Subnet{ID: ptr.To("testSubnet1")}, + existingSubnet: &armnetwork.Subnet{ID: ptr.To("testSubnet1")}, expectedFlag: true, expectedError: false, }, { desc: "isFrontendIPChanged shall return false if the service is internal, subnet == nil, " + - "loadBalancerIP == config.PrivateIPAddress and config.PrivateIPAllocationMethod != 'static'", - config: network.FrontendIPConfiguration{ + "loadBalancerIP == config.Properties.PrivateIPAddress and config.PrivateIPAllocationMethod != 'static'", + config: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("btest1-name"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAllocationMethod: network.Dynamic, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), PrivateIPAddress: ptr.To("1.1.1.1"), }, }, @@ -2208,11 +2204,11 @@ func TestIsFrontendIPChanged(t *testing.T) { }, { desc: "isFrontendIPChanged shall return false if the service is internal, subnet == nil, " + - "loadBalancerIP == config.PrivateIPAddress and config.PrivateIPAllocationMethod == 'static'", - config: network.FrontendIPConfiguration{ + "loadBalancerIP == config.Properties.PrivateIPAddress and config.PrivateIPAllocationMethod == 'static'", + config: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("btest1-name"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAllocationMethod: network.Static, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), PrivateIPAddress: ptr.To("1.1.1.1"), }, }, @@ -2224,11 +2220,11 @@ func TestIsFrontendIPChanged(t *testing.T) { }, { desc: "isFrontendIPChanged shall return true if the service is internal, subnet == nil and " + - "loadBalancerIP != config.PrivateIPAddress", - config: network.FrontendIPConfiguration{ + "loadBalancerIP != config.Properties.PrivateIPAddress", + config: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("btest1-name"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAllocationMethod: network.Static, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), PrivateIPAddress: ptr.To("1.1.1.2"), }, }, @@ -2240,18 +2236,18 @@ func TestIsFrontendIPChanged(t *testing.T) { }, { desc: "isFrontendIPChanged shall return false if config.PublicIPAddress == nil", - config: network.FrontendIPConfiguration{ - Name: ptr.To("btest1-name"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{}, + config: &armnetwork.FrontendIPConfiguration{ + Name: ptr.To("btest1-name"), + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{}, }, lbFrontendIPConfigName: "btest1-name", service: getTestService("test1", v1.ProtocolTCP, nil, false, 80), loadBalancerIP: "1.1.1.1", - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pipName"), ID: ptr.To("pip"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.1.1.1"), }, }, @@ -2261,20 +2257,20 @@ func TestIsFrontendIPChanged(t *testing.T) { }, { desc: "isFrontendIPChanged shall return false if pip.ID == config.PublicIPAddress.ID", - config: network.FrontendIPConfiguration{ + config: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("btest1-name"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("/subscriptions/subscription" + + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("/subscriptions/subscription" + "/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pipName")}, }, }, lbFrontendIPConfigName: "btest1-name", service: getTestService("test1", v1.ProtocolTCP, nil, false, 80), loadBalancerIP: "1.1.1.1", - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pipName"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.1.1.1"), }, ID: ptr.To("/subscriptions/subscription" + @@ -2286,10 +2282,10 @@ func TestIsFrontendIPChanged(t *testing.T) { }, { desc: "isFrontendIPChanged shall return true if pip.ID != config.PublicIPAddress.ID", - config: network.FrontendIPConfiguration{ + config: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("btest1-name"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("/subscriptions/subscription" + "/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pipName1"), }, @@ -2298,12 +2294,12 @@ func TestIsFrontendIPChanged(t *testing.T) { lbFrontendIPConfigName: "btest1-name", service: getTestService("test1", v1.ProtocolTCP, nil, false, 80), loadBalancerIP: "1.1.1.1", - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pipName"), ID: ptr.To("/subscriptions/subscription" + "/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pipName2"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.1.1.1"), }, }, @@ -2314,20 +2310,19 @@ func TestIsFrontendIPChanged(t *testing.T) { } for _, test := range testCases { + test := test t.Run(test.desc, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() az := GetTestCloud(ctrl) - mockSubnetsClient := az.SubnetsClient.(*mocksubnetclient.MockInterface) - mockSubnetsClient.EXPECT().Get(gomock.Any(), "rg", "vnet", "testSubnet", "").Return(test.existingSubnet, nil).AnyTimes() - mockSubnetsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", "vnet", "testSubnet", test.existingSubnet).Return(nil) - err := az.SubnetsClient.CreateOrUpdate(context.TODO(), "rg", "vnet", "testSubnet", test.existingSubnet) - if err != nil { - t.Fatal(err) - } + mockSubnetsClient := az.subnetRepo.(*subnet.MockRepository) + mockSubnetsClient.EXPECT().Get(gomock.Any(), "rg", "vnet", "testSubnet").Return(test.existingSubnet, nil).AnyTimes() + mockSubnetsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", "vnet", "testSubnet", test.existingSubnet).Return(nil).AnyTimes() - mockPIPsClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) - mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() for _, existingPIP := range test.existingPIPs { - err := az.PublicIPAddressesClient.CreateOrUpdate(context.TODO(), "rg", *existingPIP.Name, existingPIP) + _, err := az.NetworkClientFactory.GetPublicIPAddressClient().CreateOrUpdate(context.TODO(), "rg", *existingPIP.Name, *existingPIP) if err != nil { t.Fatal(err) } @@ -2336,7 +2331,7 @@ func TestIsFrontendIPChanged(t *testing.T) { service := test.service setServiceLoadBalancerIP(&service, test.loadBalancerIP) test.service.Annotations[consts.ServiceAnnotationLoadBalancerInternalSubnet] = test.annotations - var subnet network.Subnet + var subnet armnetwork.Subnet flag, rerr := az.isFrontendIPChanged(context.TODO(), "testCluster", test.config, &service, test.lbFrontendIPConfigName, &subnet) if rerr != nil { @@ -2355,7 +2350,7 @@ func TestDeterminePublicIPName(t *testing.T) { testCases := []struct { desc string loadBalancerIP string - existingPIPs []network.PublicIPAddress + existingPIPs []*armnetwork.PublicIPAddress expectedPIPName string expectedError bool isIPv6 bool @@ -2376,10 +2371,10 @@ func TestDeterminePublicIPName(t *testing.T) { desc: "determinePublicIpName shall return loadBalancerIP in service.Spec if it's in the " + "resource group", loadBalancerIP: "1.2.3.4", - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pipName"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, @@ -2395,13 +2390,13 @@ func TestDeterminePublicIPName(t *testing.T) { service := getTestService("test1", v1.ProtocolTCP, nil, false, 80) setServiceLoadBalancerIP(&service, test.loadBalancerIP) - mockPIPsClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) mockPIPsClient.EXPECT().List(gomock.Any(), "rg").Return(test.existingPIPs, nil).MaxTimes(2) - mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() for _, existingPIP := range test.existingPIPs { mockPIPsClient.EXPECT().Get(gomock.Any(), "rg", *existingPIP.Name, gomock.Any()).Return(existingPIP, nil).AnyTimes() - err := az.PublicIPAddressesClient.CreateOrUpdate(context.TODO(), "rg", *existingPIP.Name, existingPIP) - assert.NoError(t, err.Error()) + _, err := az.NetworkClientFactory.GetPublicIPAddressClient().CreateOrUpdate(context.TODO(), "rg", *existingPIP.Name, *existingPIP) + assert.NoError(t, err) } pipName, _, err := az.determinePublicIPName(context.TODO(), "testCluster", &service, test.isIPv6) assert.Equal(t, test.expectedPIPName, pipName) @@ -2417,32 +2412,32 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { testCases := []struct { desc string service v1.Service - loadBalancerSku string + loadBalancerSKU string probeProtocol string probePath string - expectedProbes map[bool][]network.Probe - expectedRules map[bool][]network.LoadBalancingRule + expectedProbes map[bool][]*armnetwork.Probe + expectedRules map[bool][]*armnetwork.LoadBalancingRule expectedErr bool }{ { desc: "getExpectedLBRules shall return corresponding probe and lbRule(blb)", service: getTestServiceDualStack("test1", v1.ProtocolTCP, map[string]string{}, 80), - loadBalancerSku: "basic", + loadBalancerSKU: "basic", expectedProbes: getDefaultTestProbes("Tcp", ""), expectedRules: getDefaultTestRules(false), }, { - desc: "getExpectedLBRules shall return tcp probe on non supported protocols when basic lb sku is used", + desc: "getExpectedLBRules shall return tcp probe on non supported protocols when basic lb SKU is used", service: getTestServiceDualStack("test1", v1.ProtocolTCP, map[string]string{}, 80), - loadBalancerSku: "basic", + loadBalancerSKU: "basic", probeProtocol: "Mongodb", expectedRules: getDefaultTestRules(false), expectedProbes: getDefaultTestProbes("Tcp", ""), }, { - desc: "getExpectedLBRules shall return tcp probe on https protocols when basic lb sku is used", + desc: "getExpectedLBRules shall return tcp probe on https protocols when basic lb SKU is used", service: getTestServiceDualStack("test1", v1.ProtocolTCP, map[string]string{}, 80), - loadBalancerSku: "basic", + loadBalancerSKU: "basic", probeProtocol: "Https", expectedRules: getDefaultTestRules(false), expectedProbes: getDefaultTestProbes("Tcp", ""), @@ -2450,20 +2445,20 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { { desc: "getExpectedLBRules shall return error (slb with external mode and SCTP)", service: getTestServiceDualStack("test1", v1.ProtocolSCTP, map[string]string{}, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", expectedErr: true, }, { desc: "getExpectedLBRules shall return corresponding probe and lbRule(slb with tcp reset)", service: getTestServiceDualStack("test1", v1.ProtocolTCP, nil, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", expectedProbes: getDefaultTestProbes("Tcp", ""), expectedRules: getDefaultTestRules(true), }, { desc: "getExpectedLBRules shall respect the probe protocol and path configuration in the config file", service: getTestServiceDualStack("test1", v1.ProtocolTCP, nil, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Http", probePath: "/healthy", expectedProbes: getDefaultTestProbes("Http", "/healthy"), @@ -2472,7 +2467,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { { desc: "getExpectedLBRules shall respect the probe protocol and path configuration in the config file", service: getTestServiceDualStack("test1", v1.ProtocolTCP, nil, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Https", probePath: "/healthy1", expectedProbes: getDefaultTestProbes("Https", "/healthy1"), @@ -2483,8 +2478,8 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { service: getTestService("test1", v1.ProtocolTCP, map[string]string{ consts.ServiceAnnotationLoadBalancerInternal: "true", }, true, 80), - loadBalancerSku: "standard", - expectedProbes: map[bool][]network.Probe{ + loadBalancerSKU: "standard", + expectedProbes: map[bool][]*armnetwork.Probe{ // Use false as IPv6 param but it is a IPv6 probe. true: {getTestProbe("Tcp", "", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), false)}, }, @@ -2496,9 +2491,9 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.ServiceAnnotationLoadBalancerEnableHighAvailabilityPorts: "true", consts.ServiceAnnotationLoadBalancerInternal: "true", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", expectedProbes: getDefaultTestProbes("Tcp", ""), - expectedRules: map[bool][]network.LoadBalancingRule{ + expectedRules: map[bool][]*armnetwork.LoadBalancingRule{ consts.IPVersionIPv4: getHATestRules(true, true, v1.ProtocolTCP, consts.IPVersionIPv4, true), consts.IPVersionIPv6: getHATestRules(true, true, v1.ProtocolTCP, consts.IPVersionIPv6, true), }, @@ -2509,8 +2504,8 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.ServiceAnnotationLoadBalancerEnableHighAvailabilityPorts: "true", consts.ServiceAnnotationLoadBalancerInternal: "true", }, 80), - loadBalancerSku: "standard", - expectedRules: map[bool][]network.LoadBalancingRule{ + loadBalancerSKU: "standard", + expectedRules: map[bool][]*armnetwork.LoadBalancingRule{ consts.IPVersionIPv4: getHATestRules(true, false, v1.ProtocolSCTP, consts.IPVersionIPv4, true), consts.IPVersionIPv6: getHATestRules(true, false, v1.ProtocolSCTP, consts.IPVersionIPv6, true), }, @@ -2521,9 +2516,9 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.ServiceAnnotationLoadBalancerEnableHighAvailabilityPorts: "true", consts.ServiceAnnotationLoadBalancerInternal: "true", }, 80, 8080), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", expectedProbes: getDefaultTestProbes("Tcp", ""), - expectedRules: map[bool][]network.LoadBalancingRule{ + expectedRules: map[bool][]*armnetwork.LoadBalancingRule{ consts.IPVersionIPv4: getHATestRules(true, true, v1.ProtocolTCP, consts.IPVersionIPv4, true), consts.IPVersionIPv6: getHATestRules(true, true, v1.ProtocolTCP, consts.IPVersionIPv6, true), }, @@ -2531,7 +2526,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { { desc: "getExpectedLBRules should leave probe path empty when using TCP probe", service: getTestServiceDualStack("test1", v1.ProtocolTCP, nil, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Tcp", expectedProbes: getDefaultTestProbes("Tcp", ""), expectedRules: getDefaultTestRules(true), @@ -2541,7 +2536,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { service: getTestServiceDualStack("test1", v1.ProtocolTCP, map[string]string{ consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsRequestPath): "/healthy1", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "TCP1", expectedProbes: getDefaultTestProbes("Tcp", ""), expectedRules: getDefaultTestRules(true), @@ -2551,7 +2546,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { service: getTestServiceDualStack("test1", v1.ProtocolTCP, map[string]string{ consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsRequestPath): "/healthy1", }, 80), - loadBalancerSku: "basic", + loadBalancerSKU: "basic", probeProtocol: "TCP1", expectedProbes: getDefaultTestProbes("Tcp", ""), expectedRules: getDefaultTestRules(false), @@ -2562,7 +2557,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsRequestPath): "/healthy1", consts.ServiceAnnotationLoadBalancerHealthProbeProtocol: "https", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", expectedProbes: getDefaultTestProbes("Https", "/healthy1"), expectedRules: getDefaultTestRules(true), }, @@ -2572,7 +2567,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsRequestPath): "/healthy1", consts.ServiceAnnotationLoadBalancerHealthProbeProtocol: "http", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", expectedProbes: getDefaultTestProbes("Http", "/healthy1"), expectedRules: getDefaultTestRules(true), }, @@ -2582,7 +2577,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsRequestPath): "/healthy1", consts.ServiceAnnotationLoadBalancerHealthProbeProtocol: "tcp", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", expectedProbes: getDefaultTestProbes("Tcp", ""), expectedRules: getDefaultTestRules(true), }, @@ -2591,7 +2586,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { service: getTestServiceDualStack("test1", v1.ProtocolTCP, map[string]string{ consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsRequestPath): "/healthy1", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Https", expectedProbes: getDefaultTestProbes("Https", "/healthy1"), expectedRules: getDefaultTestRules(true), @@ -2602,7 +2597,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.ServiceAnnotationLoadBalancerHealthProbeRequestPath: "/healthy1", consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsRequestPath): "/healthy2", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Https", expectedProbes: getDefaultTestProbes("Https", "/healthy2"), expectedRules: getDefaultTestRules(true), @@ -2614,7 +2609,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsNumOfProbe): "20", consts.ServiceAnnotationLoadBalancerHealthProbeProtocol: "https", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Tcp", expectedErr: true, }, @@ -2625,7 +2620,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsNumOfProbe): "20", consts.ServiceAnnotationLoadBalancerHealthProbeProtocol: "tcp", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Tcp", expectedErr: true, }, @@ -2635,7 +2630,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsProbeInterval): "20", consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsNumOfProbe): "5", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Https", probePath: "/healthy1", expectedProbes: getTestProbes("Https", "/healthy1", ptr.To(int32(20)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(5))), @@ -2647,7 +2642,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsProbeInterval): "20", consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsNumOfProbe): "5", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Http", expectedProbes: getTestProbes("Http", "/", ptr.To(int32(20)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(5))), expectedRules: getDefaultTestRules(true), @@ -2658,7 +2653,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsProbeInterval): "20", consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsNumOfProbe): "5", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Tcp", expectedProbes: getTestProbes("Tcp", "", ptr.To(int32(20)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(5))), expectedRules: getDefaultTestRules(true), @@ -2669,7 +2664,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsProbeInterval): "20", consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsNumOfProbe): "5a", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Tcp", expectedErr: true, }, @@ -2679,7 +2674,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsProbeInterval): "1", consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsNumOfProbe): "5", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Tcp", expectedErr: true, }, @@ -2689,7 +2684,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsProbeInterval): "10", consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsNumOfProbe): "1", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Tcp", expectedErr: true, }, @@ -2699,15 +2694,15 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsProbeInterval): "10", consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsNumOfProbe): "20", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Tcp", expectedErr: true, }, { desc: "getExpectedLBRules should return correct rule when floating ip annotations are added", service: getTestServiceDualStack("test1", v1.ProtocolTCP, map[string]string{consts.ServiceAnnotationDisableLoadBalancerFloatingIP: "true"}, 80), - loadBalancerSku: "basic", - expectedRules: map[bool][]network.LoadBalancingRule{ + loadBalancerSKU: "basic", + expectedRules: map[bool][]*armnetwork.LoadBalancingRule{ consts.IPVersionIPv4: {getFloatingIPTestRule(false, false, 80, consts.IPVersionIPv4)}, consts.IPVersionIPv6: {getFloatingIPTestRule(false, false, 80, consts.IPVersionIPv6)}, }, @@ -2726,7 +2721,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { service: getTestServiceDualStack("test1", v1.ProtocolTCP, map[string]string{ "service.beta.kubernetes.io/azure-load-balancer-disable-tcp-reset": "true", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", expectedRules: getTCPResetTestRules(false), expectedProbes: getDefaultTestProbes("Tcp", ""), }, @@ -2745,7 +2740,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { "service.beta.kubernetes.io/port_80_health-probe_protocol": "HtTpS", "service.beta.kubernetes.io/azure-load-balancer-health-probe-protocol": "TcP", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Https", expectedRules: getDefaultTestRules(true), expectedProbes: getDefaultTestProbes("Https", "/"), @@ -2764,11 +2759,11 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { service: getTestServiceDualStack("test1", v1.ProtocolTCP, map[string]string{ "service.beta.kubernetes.io/port_8000_health-probe_port": "port-tcp-80", }, 80, 8000), - expectedRules: map[bool][]network.LoadBalancingRule{ + expectedRules: map[bool][]*armnetwork.LoadBalancingRule{ consts.IPVersionIPv4: {getTestRule(false, 80, consts.IPVersionIPv4), getTestRule(false, 8000, consts.IPVersionIPv4)}, consts.IPVersionIPv6: {getTestRule(false, 80, consts.IPVersionIPv6), getTestRule(false, 8000, consts.IPVersionIPv6)}, }, - expectedProbes: map[bool][]network.Probe{ + expectedProbes: map[bool][]*armnetwork.Probe{ consts.IPVersionIPv4: { getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(8000)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), @@ -2784,7 +2779,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { service: getTestServiceDualStack("test1", v1.ProtocolTCP, map[string]string{ "service.beta.kubernetes.io/port_8000_health-probe_port": "80", }, 80, 8000), - expectedRules: map[bool][]network.LoadBalancingRule{ + expectedRules: map[bool][]*armnetwork.LoadBalancingRule{ consts.IPVersionIPv4: { getTestRule(false, 80, consts.IPVersionIPv4), getTestRule(false, 8000, consts.IPVersionIPv4), @@ -2794,7 +2789,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { getTestRule(false, 8000, consts.IPVersionIPv6), }, }, - expectedProbes: map[bool][]network.Probe{ + expectedProbes: map[bool][]*armnetwork.Probe{ consts.IPVersionIPv4: { getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(8000)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), @@ -2810,25 +2805,25 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { service: getTestServiceDualStack("test1", v1.ProtocolTCP, map[string]string{ "service.beta.kubernetes.io/port_8000_no_probe_rule": "true", }, 80, 8000), - expectedRules: map[bool][]network.LoadBalancingRule{ + expectedRules: map[bool][]*armnetwork.LoadBalancingRule{ consts.IPVersionIPv4: { getTestRule(false, 80, consts.IPVersionIPv4), - func() network.LoadBalancingRule { + func() *armnetwork.LoadBalancingRule { rule := getTestRule(false, 8000, consts.IPVersionIPv4) - rule.Probe = nil + rule.Properties.Probe = nil return rule }(), }, consts.IPVersionIPv6: { getTestRule(false, 80, consts.IPVersionIPv6), - func() network.LoadBalancingRule { + func() *armnetwork.LoadBalancingRule { rule := getTestRule(false, 8000, consts.IPVersionIPv6) - rule.Probe = nil + rule.Properties.Probe = nil return rule }(), }, }, - expectedProbes: map[bool][]network.Probe{ + expectedProbes: map[bool][]*armnetwork.Probe{ consts.IPVersionIPv4: { getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), }, @@ -2842,7 +2837,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { service: getTestServiceDualStack("test1", v1.ProtocolTCP, map[string]string{ "service.beta.kubernetes.io/port_8000_no_lb_rule": "true", }, 80, 8000), - expectedRules: map[bool][]network.LoadBalancingRule{ + expectedRules: map[bool][]*armnetwork.LoadBalancingRule{ consts.IPVersionIPv4: { getTestRule(false, 80, consts.IPVersionIPv4), }, @@ -2850,7 +2845,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { getTestRule(false, 80, consts.IPVersionIPv6), }, }, - expectedProbes: map[bool][]network.Probe{ + expectedProbes: map[bool][]*armnetwork.Probe{ consts.IPVersionIPv4: { getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), }, @@ -2864,7 +2859,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { service: getTestServiceDualStack("test1", v1.ProtocolTCP, map[string]string{ "service.beta.kubernetes.io/port_8000_health-probe_port": "5080", }, 80, 8000), - expectedRules: map[bool][]network.LoadBalancingRule{ + expectedRules: map[bool][]*armnetwork.LoadBalancingRule{ consts.IPVersionIPv4: { getTestRule(false, 80, consts.IPVersionIPv4), getTestRule(false, 8000, consts.IPVersionIPv4), @@ -2874,7 +2869,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { getTestRule(false, 8000, consts.IPVersionIPv6), }, }, - expectedProbes: map[bool][]network.Probe{ + expectedProbes: map[bool][]*armnetwork.Probe{ consts.IPVersionIPv4: { getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(8000)), ptr.To(int32(5080)), ptr.To(int32(2)), consts.IPVersionIPv4), @@ -2889,17 +2884,17 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { rulesDualStack := getDefaultTestRules(true) for _, rules := range rulesDualStack { for _, rule := range rules { - rule.IdleTimeoutInMinutes = ptr.To(int32(5)) + rule.Properties.IdleTimeoutInMinutes = to.Ptr(int32(5)) } } testCases = append(testCases, struct { desc string service v1.Service - loadBalancerSku string + loadBalancerSKU string probeProtocol string probePath string - expectedProbes map[bool][]network.Probe - expectedRules map[bool][]network.LoadBalancingRule + expectedProbes map[bool][]*armnetwork.Probe + expectedRules map[bool][]*armnetwork.LoadBalancingRule expectedErr bool }{ desc: "getExpectedLBRules should expected rules when timeout are added", @@ -2908,12 +2903,12 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { consts.BuildHealthProbeAnnotationKeyForPort(80, consts.HealthProbeParamsNumOfProbe): "10", consts.ServiceAnnotationLoadBalancerIdleTimeout: "5", }, 80), - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Tcp", expectedProbes: getTestProbes("Tcp", "", ptr.To(int32(10)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(10))), expectedRules: rulesDualStack, }) - rules1DualStack := map[bool][]network.LoadBalancingRule{ + rules1DualStack := map[bool][]*armnetwork.LoadBalancingRule{ consts.IPVersionIPv4: { getTestRule(true, 80, consts.IPVersionIPv4), getTestRule(true, 443, consts.IPVersionIPv4), @@ -2926,10 +2921,10 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { }, } for _, rule := range rules1DualStack[consts.IPVersionIPv4] { - rule.Probe.ID = ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lbname/probes/atest1-TCP-34567") + rule.Properties.Probe.ID = to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lbname/probes/atest1-TCP-34567") } for _, rule := range rules1DualStack[consts.IPVersionIPv6] { - rule.Probe.ID = ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lbname/probes/atest1-TCP-34567-IPv6") + rule.Properties.Probe.ID = to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lbname/probes/atest1-TCP-34567-IPv6") } // When the service spec externalTrafficPolicy is Local all of these annotations should be ignored @@ -2947,21 +2942,21 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { testCases = append(testCases, struct { desc string service v1.Service - loadBalancerSku string + loadBalancerSKU string probeProtocol string probePath string - expectedProbes map[bool][]network.Probe - expectedRules map[bool][]network.LoadBalancingRule + expectedProbes map[bool][]*armnetwork.Probe + expectedRules map[bool][]*armnetwork.LoadBalancingRule expectedErr bool }{ desc: "getExpectedLBRules should expected rules when externalTrafficPolicy is local", service: svc, - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "Http", expectedProbes: probes, expectedRules: rules1DualStack, }) - rules1DualStack = map[bool][]network.LoadBalancingRule{ + rules1DualStack = map[bool][]*armnetwork.LoadBalancingRule{ consts.IPVersionIPv4: { getTestRule(true, 80, consts.IPVersionIPv4), }, @@ -2986,16 +2981,16 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { testCases = append(testCases, struct { desc string service v1.Service - loadBalancerSku string + loadBalancerSKU string probeProtocol string probePath string - expectedProbes map[bool][]network.Probe - expectedRules map[bool][]network.LoadBalancingRule + expectedProbes map[bool][]*armnetwork.Probe + expectedRules map[bool][]*armnetwork.LoadBalancingRule expectedErr bool }{ desc: "getExpectedLBRules should return expected rules when externalTrafficPolicy is local and service.beta.kubernetes.io/azure-pls-proxy-protocol is enabled", service: svc, - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "https", expectedProbes: probes, expectedRules: rules1DualStack, @@ -3018,16 +3013,16 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { testCases = append(testCases, struct { desc string service v1.Service - loadBalancerSku string + loadBalancerSKU string probeProtocol string probePath string - expectedProbes map[bool][]network.Probe - expectedRules map[bool][]network.LoadBalancingRule + expectedProbes map[bool][]*armnetwork.Probe + expectedRules map[bool][]*armnetwork.LoadBalancingRule expectedErr bool }{ desc: "getExpectedLBRules should return expected rules when externalTrafficPolicy is local and service.beta.kubernetes.io/azure-pls-proxy-protocol is enabled", service: svc, - loadBalancerSku: "standard", + loadBalancerSKU: "standard", probeProtocol: "https", expectedProbes: probes, expectedRules: rules1DualStack, @@ -3035,7 +3030,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { az := GetTestCloud(ctrl) - az.Config.LoadBalancerSku = test.loadBalancerSku + az.Config.LoadBalancerSKU = test.loadBalancerSKU service := test.service firstPort := service.Spec.Ports[0] probeProtocol := test.probeProtocol @@ -3096,80 +3091,80 @@ func TestGetExpectedLBRulesSharedProbe(t *testing.T) { probe, lbrule, err := az.getExpectedLBRules(&svc, "frontendIPConfigID", "backendPoolID", "lbname", consts.IPVersionIPv4) assert.NoError(t, err) assert.Equal(t, 1, len(probe)) - assert.Equal(t, *az.buildClusterServiceSharedProbe(), probe[0]) + assert.Equal(t, *az.buildClusterServiceSharedProbe(), *probe[0]) assert.Equal(t, 2, len(lbrule)) - assert.Equal(t, "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lbname/probes/cluster-service-shared-health-probe", *lbrule[0].Probe.ID) - assert.Equal(t, "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lbname/probes/cluster-service-shared-health-probe", *lbrule[1].Probe.ID) + assert.Equal(t, "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lbname/probes/cluster-service-shared-health-probe", *lbrule[0].Properties.Probe.ID) + assert.Equal(t, "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lbname/probes/cluster-service-shared-health-probe", *lbrule[1].Properties.Probe.ID) }) } } // getDefaultTestRules returns dualstack rules. -func getDefaultTestRules(enableTCPReset bool) map[bool][]network.LoadBalancingRule { - return map[bool][]network.LoadBalancingRule{ +func getDefaultTestRules(enableTCPReset bool) map[bool][]*armnetwork.LoadBalancingRule { + return map[bool][]*armnetwork.LoadBalancingRule{ consts.IPVersionIPv4: {getTestRule(enableTCPReset, 80, consts.IPVersionIPv4)}, consts.IPVersionIPv6: {getTestRule(enableTCPReset, 80, consts.IPVersionIPv6)}, } } // getDefaultInternalIPv6Rules returns a rule for IPv6 single stack. -func getDefaultInternalIPv6Rules(enableTCPReset bool) map[bool][]network.LoadBalancingRule { +func getDefaultInternalIPv6Rules(enableTCPReset bool) map[bool][]*armnetwork.LoadBalancingRule { rule := getTestRule(enableTCPReset, 80, false) - rule.EnableFloatingIP = ptr.To(false) - rule.BackendPort = ptr.To(getBackendPort(*rule.FrontendPort)) - rule.BackendAddressPool.ID = ptr.To("backendPoolID-IPv6") - return map[bool][]network.LoadBalancingRule{ + rule.Properties.EnableFloatingIP = to.Ptr(false) + rule.Properties.BackendPort = to.Ptr(getBackendPort(*rule.Properties.FrontendPort)) + rule.Properties.BackendAddressPool.ID = to.Ptr("backendPoolID-IPv6") + return map[bool][]*armnetwork.LoadBalancingRule{ true: {rule}, } } // getTCPResetTestRules returns rules with TCPReset always set. -func getTCPResetTestRules(enableTCPReset bool) map[bool][]network.LoadBalancingRule { +func getTCPResetTestRules(enableTCPReset bool) map[bool][]*armnetwork.LoadBalancingRule { IPv4Rule := getTestRule(enableTCPReset, 80, consts.IPVersionIPv4) IPv6Rule := getTestRule(enableTCPReset, 80, consts.IPVersionIPv6) - IPv4Rule.EnableTCPReset = ptr.To(enableTCPReset) - IPv6Rule.EnableTCPReset = ptr.To(enableTCPReset) - return map[bool][]network.LoadBalancingRule{ + IPv4Rule.Properties.EnableTCPReset = to.Ptr(enableTCPReset) + IPv6Rule.Properties.EnableTCPReset = to.Ptr(enableTCPReset) + return map[bool][]*armnetwork.LoadBalancingRule{ consts.IPVersionIPv4: {IPv4Rule}, consts.IPVersionIPv6: {IPv6Rule}, } } // getTestRule returns a rule for dualStack. -func getTestRule(enableTCPReset bool, port int32, isIPv6 bool) network.LoadBalancingRule { +func getTestRule(enableTCPReset bool, port int32, isIPv6 bool) *armnetwork.LoadBalancingRule { suffix := "" if isIPv6 { suffix = "-" + consts.IPVersionIPv6String } - expectedRules := network.LoadBalancingRule{ + expectedRules := &armnetwork.LoadBalancingRule{ Name: ptr.To(fmt.Sprintf("atest1-TCP-%d", port) + suffix), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Protocol: network.TransportProtocol("Tcp"), - FrontendIPConfiguration: &network.SubResource{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Protocol: ptr.To(armnetwork.TransportProtocolTCP), + FrontendIPConfiguration: &armnetwork.SubResource{ ID: ptr.To("frontendIPConfigID" + suffix), }, - BackendAddressPool: &network.SubResource{ + BackendAddressPool: &armnetwork.SubResource{ ID: ptr.To("backendPoolID" + suffix), }, - LoadDistribution: "Default", + LoadDistribution: to.Ptr(armnetwork.LoadDistributionDefault), FrontendPort: ptr.To(port), BackendPort: ptr.To(port), EnableFloatingIP: ptr.To(true), DisableOutboundSnat: ptr.To(false), IdleTimeoutInMinutes: ptr.To(int32(4)), - Probe: &network.SubResource{ + Probe: &armnetwork.SubResource{ ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/" + fmt.Sprintf("Microsoft.Network/loadBalancers/lbname/probes/atest1-TCP-%d%s", port, suffix)), }, }, } if enableTCPReset { - expectedRules.EnableTCPReset = ptr.To(true) + expectedRules.Properties.EnableTCPReset = to.Ptr(true) } return expectedRules } -func getHATestRules(_, hasProbe bool, protocol v1.Protocol, isIPv6, isInternal bool) []network.LoadBalancingRule { +func getHATestRules(_, hasProbe bool, protocol v1.Protocol, isIPv6, isInternal bool) []*armnetwork.LoadBalancingRule { suffix := "" enableFloatingIP := true if isIPv6 { @@ -3179,18 +3174,18 @@ func getHATestRules(_, hasProbe bool, protocol v1.Protocol, isIPv6, isInternal b } } - expectedRules := []network.LoadBalancingRule{ + expectedRules := []*armnetwork.LoadBalancingRule{ { Name: ptr.To(fmt.Sprintf("atest1-%s-80%s", string(protocol), suffix)), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Protocol: network.TransportProtocol("All"), - FrontendIPConfiguration: &network.SubResource{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Protocol: to.Ptr(armnetwork.TransportProtocolAll), + FrontendIPConfiguration: &armnetwork.SubResource{ ID: ptr.To("frontendIPConfigID" + suffix), }, - BackendAddressPool: &network.SubResource{ + BackendAddressPool: &armnetwork.SubResource{ ID: ptr.To("backendPoolID" + suffix), }, - LoadDistribution: "Default", + LoadDistribution: to.Ptr(armnetwork.LoadDistributionDefault), FrontendPort: ptr.To(int32(0)), BackendPort: ptr.To(int32(0)), EnableFloatingIP: ptr.To(enableFloatingIP), @@ -3201,7 +3196,7 @@ func getHATestRules(_, hasProbe bool, protocol v1.Protocol, isIPv6, isInternal b }, } if hasProbe { - expectedRules[0].Probe = &network.SubResource{ + expectedRules[0].Properties.Probe = &armnetwork.SubResource{ ID: ptr.To(fmt.Sprintf("/subscriptions/subscription/resourceGroups/rg/providers/"+ "Microsoft.Network/loadBalancers/lbname/probes/atest1-%s-80%s", string(protocol), suffix)), } @@ -3209,94 +3204,94 @@ func getHATestRules(_, hasProbe bool, protocol v1.Protocol, isIPv6, isInternal b return expectedRules } -func getFloatingIPTestRule(enableTCPReset, enableFloatingIP bool, port int32, isIPv6 bool) network.LoadBalancingRule { +func getFloatingIPTestRule(enableTCPReset, enableFloatingIP bool, port int32, isIPv6 bool) *armnetwork.LoadBalancingRule { suffix := "" if isIPv6 { suffix = "-" + consts.IPVersionIPv6String } - expectedRules := network.LoadBalancingRule{ + expectedRules := &armnetwork.LoadBalancingRule{ Name: ptr.To(fmt.Sprintf("atest1-TCP-%d%s", port, suffix)), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Protocol: network.TransportProtocol("Tcp"), - FrontendIPConfiguration: &network.SubResource{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Protocol: ptr.To(armnetwork.TransportProtocolTCP), + FrontendIPConfiguration: &armnetwork.SubResource{ ID: ptr.To("frontendIPConfigID" + suffix), }, - BackendAddressPool: &network.SubResource{ + BackendAddressPool: &armnetwork.SubResource{ ID: ptr.To("backendPoolID" + suffix), }, - LoadDistribution: "Default", + LoadDistribution: to.Ptr(armnetwork.LoadDistributionDefault), FrontendPort: ptr.To(port), BackendPort: ptr.To(getBackendPort(port)), EnableFloatingIP: ptr.To(enableFloatingIP), DisableOutboundSnat: ptr.To(false), IdleTimeoutInMinutes: ptr.To(int32(4)), - Probe: &network.SubResource{ + Probe: &armnetwork.SubResource{ ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/" + fmt.Sprintf("Microsoft.Network/loadBalancers/lbname/probes/atest1-TCP-%d%s", port, suffix)), }, }, } if enableTCPReset { - expectedRules.EnableTCPReset = ptr.To(true) + expectedRules.Properties.EnableTCPReset = to.Ptr(true) } return expectedRules } -func getTestLoadBalancer(name, rgName, clusterName, identifier *string, service v1.Service, lbSku string) network.LoadBalancer { +func getTestLoadBalancer(name, rgName, clusterName, identifier *string, service v1.Service, lbSKU string) *armnetwork.LoadBalancer { caser := cases.Title(language.English) - lb := network.LoadBalancer{ + lb := &armnetwork.LoadBalancer{ Name: name, - Sku: &network.LoadBalancerSku{ - Name: network.LoadBalancerSkuName(lbSku), + SKU: &armnetwork.LoadBalancerSKU{ + Name: to.Ptr(armnetwork.LoadBalancerSKUName(lbSKU)), }, - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + FrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{ { Name: identifier, ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + "Microsoft.Network/loadBalancers/" + *name + "/frontendIPConfigurations/" + *identifier), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, }, }, }, - BackendAddressPools: &[]network.BackendAddressPool{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ {Name: clusterName}, }, - Probes: &[]network.Probe{ + Probes: []*armnetwork.Probe{ { Name: ptr.To(*identifier + "-" + string(service.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service.Spec.Ports[0].Port))), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10080)), - Protocol: network.ProbeProtocolTCP, + Protocol: to.Ptr(armnetwork.ProbeProtocolTCP), IntervalInSeconds: ptr.To(int32(5)), ProbeThreshold: ptr.To(int32(2)), }, }, }, - LoadBalancingRules: &[]network.LoadBalancingRule{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ { Name: ptr.To(*identifier + "-" + string(service.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service.Spec.Ports[0].Port))), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Protocol: network.TransportProtocol(caser.String((strings.ToLower(string(service.Spec.Ports[0].Protocol))))), - FrontendIPConfiguration: &network.SubResource{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Protocol: to.Ptr(armnetwork.TransportProtocol(caser.String((strings.ToLower(string(service.Spec.Ports[0].Protocol)))))), + FrontendIPConfiguration: &armnetwork.SubResource{ ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + "Microsoft.Network/loadBalancers/" + *name + "/frontendIPConfigurations/aservice1"), }, - BackendAddressPool: &network.SubResource{ + BackendAddressPool: &armnetwork.SubResource{ ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + "Microsoft.Network/loadBalancers/" + *name + "/backendAddressPools/" + *clusterName), }, - LoadDistribution: network.LoadDistribution("Default"), + LoadDistribution: to.Ptr(armnetwork.LoadDistributionDefault), FrontendPort: ptr.To(service.Spec.Ports[0].Port), BackendPort: ptr.To(service.Spec.Ports[0].Port), EnableFloatingIP: ptr.To(true), - EnableTCPReset: ptr.To(strings.EqualFold(lbSku, "standard")), + EnableTCPReset: ptr.To(strings.EqualFold(lbSKU, "standard")), DisableOutboundSnat: ptr.To(false), IdleTimeoutInMinutes: ptr.To(int32(4)), - Probe: &network.SubResource{ + Probe: &armnetwork.SubResource{ ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/Microsoft.Network/loadBalancers/testCluster/probes/aservice1-TCP-80"), }, }, @@ -3307,53 +3302,53 @@ func getTestLoadBalancer(name, rgName, clusterName, identifier *string, service return lb } -func getTestLoadBalancerDualStack(name, rgName, clusterName, identifier *string, service v1.Service, lbSku string) network.LoadBalancer { +func getTestLoadBalancerDualStack(name, rgName, clusterName, identifier *string, service v1.Service, lbSKU string) *armnetwork.LoadBalancer { caser := cases.Title(language.English) - lb := getTestLoadBalancer(name, rgName, clusterName, identifier, service, lbSku) - *lb.LoadBalancerPropertiesFormat.FrontendIPConfigurations = append(*lb.LoadBalancerPropertiesFormat.FrontendIPConfigurations, network.FrontendIPConfiguration{ + lb := getTestLoadBalancer(name, rgName, clusterName, identifier, service, lbSKU) + lb.Properties.FrontendIPConfigurations = append(lb.Properties.FrontendIPConfigurations, &armnetwork.FrontendIPConfiguration{ Name: ptr.To(*identifier + ipv6Suffix), ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + "Microsoft.Network/loadBalancers/" + *name + "/frontendIPConfigurations/" + *identifier + ipv6Suffix), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("testCluster-aservice1-IPv6"), }, }, }) - *lb.LoadBalancerPropertiesFormat.BackendAddressPools = append(*lb.LoadBalancerPropertiesFormat.BackendAddressPools, network.BackendAddressPool{ + lb.Properties.BackendAddressPools = append(lb.Properties.BackendAddressPools, &armnetwork.BackendAddressPool{ Name: ptr.To(*clusterName + ipv6Suffix), }) - *lb.LoadBalancerPropertiesFormat.Probes = append(*lb.LoadBalancerPropertiesFormat.Probes, network.Probe{ + lb.Properties.Probes = append(lb.Properties.Probes, &armnetwork.Probe{ Name: ptr.To(*identifier + "-" + string(service.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service.Spec.Ports[0].Port)) + ipv6Suffix), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10080)), - Protocol: network.ProbeProtocolTCP, + Protocol: to.Ptr(armnetwork.ProbeProtocolTCP), IntervalInSeconds: ptr.To(int32(5)), ProbeThreshold: ptr.To(int32(2)), }, }) - *lb.LoadBalancerPropertiesFormat.LoadBalancingRules = append(*lb.LoadBalancerPropertiesFormat.LoadBalancingRules, network.LoadBalancingRule{ + lb.Properties.LoadBalancingRules = append(lb.Properties.LoadBalancingRules, &armnetwork.LoadBalancingRule{ Name: ptr.To(*identifier + "-" + string(service.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service.Spec.Ports[0].Port)) + ipv6Suffix), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Protocol: network.TransportProtocol(caser.String((strings.ToLower(string(service.Spec.Ports[0].Protocol))))), - FrontendIPConfiguration: &network.SubResource{ + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + Protocol: to.Ptr(armnetwork.TransportProtocol(caser.String((strings.ToLower(string(service.Spec.Ports[0].Protocol)))))), + FrontendIPConfiguration: &armnetwork.SubResource{ ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + "Microsoft.Network/loadBalancers/" + *name + "/frontendIPConfigurations/aservice1-IPv6"), }, - BackendAddressPool: &network.SubResource{ + BackendAddressPool: &armnetwork.SubResource{ ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + "Microsoft.Network/loadBalancers/" + *name + "/backendAddressPools/" + *clusterName + ipv6Suffix), }, - LoadDistribution: network.LoadDistribution("Default"), + LoadDistribution: to.Ptr(armnetwork.LoadDistributionDefault), FrontendPort: ptr.To(service.Spec.Ports[0].Port), BackendPort: ptr.To(service.Spec.Ports[0].Port), EnableFloatingIP: ptr.To(true), - EnableTCPReset: ptr.To(strings.EqualFold(lbSku, "standard")), + EnableTCPReset: ptr.To(strings.EqualFold(lbSKU, "standard")), DisableOutboundSnat: ptr.To(false), IdleTimeoutInMinutes: ptr.To(int32(4)), - Probe: &network.SubResource{ + Probe: &armnetwork.SubResource{ ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/Microsoft.Network/loadBalancers/testCluster/probes/aservice1-TCP-80-IPv6"), }, }, @@ -3362,356 +3357,354 @@ func getTestLoadBalancerDualStack(name, rgName, clusterName, identifier *string, } func TestReconcileLoadBalancerCommon(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() service1 := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80) basicLb1 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service1, "Basic") service2 := getTestServiceDualStack("test1", v1.ProtocolTCP, nil, 80) basicLb2 := getTestLoadBalancerDualStack(ptr.To("lb1"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("bservice1"), service2, "Basic") - basicLb2.Name = ptr.To("testCluster") - basicLb2.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + basicLb2.Name = to.Ptr("testCluster") + basicLb2.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("bservice1"), ID: ptr.To("bservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, }, }, { Name: ptr.To("bservice1-IPv6"), ID: ptr.To("bservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, }, }, } service3 := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80) - modifiedLbs := make([]network.LoadBalancer, 2) + modifiedLbs := make([]*armnetwork.LoadBalancer, 2) for i := range modifiedLbs { modifiedLbs[i] = getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service3, "Basic") - modifiedLbs[i].FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + modifiedLbs[i].Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, }, }, { Name: ptr.To("bservice1"), ID: ptr.To("bservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, }, }, { Name: ptr.To("aservice1-IPv6"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, }, }, { Name: ptr.To("bservice1-IPv6"), ID: ptr.To("bservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, }, }, } - modifiedLbs[i].Probes = &[]network.Probe{ + modifiedLbs[i].Properties.Probes = []*armnetwork.Probe{ { Name: ptr.To(svcPrefix + string(service3.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service3.Spec.Ports[0].Port))), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10080)), }, }, { Name: ptr.To(svcPrefix + string(service3.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service3.Spec.Ports[0].Port))), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10081)), }, }, { Name: ptr.To(svcPrefix + string(service3.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service3.Spec.Ports[0].Port)) + ipv6Suffix), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10080)), }, }, { Name: ptr.To(svcPrefix + string(service3.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service3.Spec.Ports[0].Port)) + ipv6Suffix), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10081)), }, }, } } expectedLb1 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service3, "Basic") - expectedLb1.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + expectedLb1.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, }, }, { Name: ptr.To("bservice1"), ID: ptr.To("bservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, }, }, { Name: ptr.To("aservice1-IPv6"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, }, }, { Name: ptr.To("bservice1-IPv6"), ID: ptr.To("bservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, }, }, } service4 := getTestServiceDualStack("service1", v1.ProtocolTCP, map[string]string{}, 80) existingSLB := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service4, "Standard") - existingSLB.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + existingSLB.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, }, }, { Name: ptr.To("bservice1"), ID: ptr.To("bservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, }, }, { Name: ptr.To("aservice1-IPv6"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, }, }, { Name: ptr.To("bservice1-IPv6"), ID: ptr.To("bservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, }, }, } - existingSLB.Probes = &[]network.Probe{ + existingSLB.Properties.Probes = []*armnetwork.Probe{ { Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port))), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10080)), }, }, { Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port))), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10081)), }, }, { Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port)) + ipv6Suffix), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10080)), }, }, { Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port)) + ipv6Suffix), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10081)), }, }, } expectedSLb := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service4, "Standard") - (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].DisableOutboundSnat = ptr.To(true) - (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].EnableTCPReset = ptr.To(true) - (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].IdleTimeoutInMinutes = ptr.To(int32(4)) - (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].DisableOutboundSnat = ptr.To(true) - (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].EnableTCPReset = ptr.To(true) - (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].IdleTimeoutInMinutes = ptr.To(int32(4)) - expectedSLb.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + (expectedSLb.Properties.LoadBalancingRules)[0].Properties.DisableOutboundSnat = to.Ptr(true) + (expectedSLb.Properties.LoadBalancingRules)[0].Properties.EnableTCPReset = to.Ptr(true) + (expectedSLb.Properties.LoadBalancingRules)[0].Properties.IdleTimeoutInMinutes = to.Ptr(int32(4)) + (expectedSLb.Properties.LoadBalancingRules)[1].Properties.DisableOutboundSnat = to.Ptr(true) + (expectedSLb.Properties.LoadBalancingRules)[1].Properties.EnableTCPReset = to.Ptr(true) + (expectedSLb.Properties.LoadBalancingRules)[1].Properties.IdleTimeoutInMinutes = to.Ptr(int32(4)) + expectedSLb.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, }, }, { Name: ptr.To("bservice1"), ID: ptr.To("bservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, }, }, { Name: ptr.To("aservice1-IPv6"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, }, }, { Name: ptr.To("bservice1-IPv6"), ID: ptr.To("bservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, }, }, } service5 := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80) slb5 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service5, "Standard") - slb5.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + slb5.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, }, }, { Name: ptr.To("bservice1"), ID: ptr.To("bservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, }, }, { Name: ptr.To("aservice1-IPv6"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, }, }, { Name: ptr.To("bservice1-IPv6"), ID: ptr.To("bservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, }, }, } - slb5.Probes = &[]network.Probe{ + slb5.Properties.Probes = []*armnetwork.Probe{ { Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port))), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10080)), }, }, { Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port))), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10081)), }, }, { Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port)) + ipv6Suffix), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10080)), }, }, { Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port)) + ipv6Suffix), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10081)), }, }, } // change to false to test that reconciliation will fix it (despite the fact that disable-tcp-reset was removed in 1.20) - (*slb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].EnableTCPReset = ptr.To(false) - (*slb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].EnableTCPReset = ptr.To(false) + (slb5.Properties.LoadBalancingRules)[0].Properties.EnableTCPReset = to.Ptr(false) + (slb5.Properties.LoadBalancingRules)[1].Properties.EnableTCPReset = to.Ptr(false) expectedSLb5 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service5, "Standard") - (*expectedSLb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].DisableOutboundSnat = ptr.To(true) - (*expectedSLb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].IdleTimeoutInMinutes = ptr.To(int32(4)) - (*expectedSLb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].DisableOutboundSnat = ptr.To(true) - (*expectedSLb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].IdleTimeoutInMinutes = ptr.To(int32(4)) - expectedSLb5.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + (expectedSLb5.Properties.LoadBalancingRules)[0].Properties.DisableOutboundSnat = ptr.To(true) + (expectedSLb5.Properties.LoadBalancingRules)[0].Properties.IdleTimeoutInMinutes = ptr.To(int32(4)) + (expectedSLb5.Properties.LoadBalancingRules)[1].Properties.DisableOutboundSnat = ptr.To(true) + (expectedSLb5.Properties.LoadBalancingRules)[1].Properties.IdleTimeoutInMinutes = ptr.To(int32(4)) + expectedSLb5.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, }, }, { Name: ptr.To("bservice1"), ID: ptr.To("bservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, }, }, { Name: ptr.To("aservice1-IPv6"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, }, }, { Name: ptr.To("bservice1-IPv6"), ID: ptr.To("bservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, }, }, } service6 := getTestServiceDualStack("service1", v1.ProtocolUDP, nil, 80) lb6 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service6, "basic") - lb6.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{} - lb6.Probes = &[]network.Probe{} + lb6.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{} + lb6.Properties.Probes = []*armnetwork.Probe{} expectedLB6 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service6, "basic") - expectedLB6.Probes = &[]network.Probe{} - (*expectedLB6.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].Probe = nil - (*expectedLB6.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].EnableTCPReset = nil - (*expectedLB6.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].Probe = nil - (*expectedLB6.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].EnableTCPReset = nil - expectedLB6.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + expectedLB6.Properties.Probes = []*armnetwork.Probe{} + (expectedLB6.Properties.LoadBalancingRules)[0].Properties.Probe = nil + (expectedLB6.Properties.LoadBalancingRules)[0].Properties.EnableTCPReset = nil + (expectedLB6.Properties.LoadBalancingRules)[1].Properties.Probe = nil + (expectedLB6.Properties.LoadBalancingRules)[1].Properties.EnableTCPReset = nil + expectedLB6.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, }, }, { Name: ptr.To("aservice1-IPv6"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, }, }, } @@ -3720,43 +3713,43 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { service7.Spec.HealthCheckNodePort = 10081 service7.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyTypeLocal lb7 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service7, "basic") - lb7.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{} - lb7.Probes = &[]network.Probe{} + lb7.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{} + lb7.Properties.Probes = []*armnetwork.Probe{} expectedLB7 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service7, "basic") - (*expectedLB7.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].Probe = &network.SubResource{ + (expectedLB7.Properties.LoadBalancingRules)[0].Properties.Probe = &armnetwork.SubResource{ ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/probes/aservice1-TCP-10081"), } - (*expectedLB7.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].Probe = &network.SubResource{ + (expectedLB7.Properties.LoadBalancingRules)[1].Properties.Probe = &armnetwork.SubResource{ ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/probes/aservice1-TCP-10081-IPv6"), } - (*expectedLB7.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].EnableTCPReset = nil - (*lb7.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].DisableOutboundSnat = ptr.To(true) - (*expectedLB7.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].EnableTCPReset = nil - (*lb7.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].DisableOutboundSnat = ptr.To(true) - expectedLB7.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + (expectedLB7.Properties.LoadBalancingRules)[0].Properties.EnableTCPReset = nil + (lb7.Properties.LoadBalancingRules)[0].Properties.DisableOutboundSnat = ptr.To(true) + (expectedLB7.Properties.LoadBalancingRules)[1].Properties.EnableTCPReset = nil + (lb7.Properties.LoadBalancingRules)[1].Properties.DisableOutboundSnat = ptr.To(true) + expectedLB7.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, }, }, { Name: ptr.To("aservice1-IPv6"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, }, }, } - expectedLB7.Probes = &[]network.Probe{ + expectedLB7.Properties.Probes = []*armnetwork.Probe{ { Name: ptr.To(svcPrefix + string(v1.ProtocolTCP) + "-" + strconv.Itoa(int(service7.Spec.HealthCheckNodePort))), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10081)), RequestPath: ptr.To("/healthz"), - Protocol: network.ProbeProtocolHTTP, + Protocol: to.Ptr(armnetwork.ProbeProtocolHTTP), IntervalInSeconds: ptr.To(int32(5)), ProbeThreshold: ptr.To(int32(2)), }, @@ -3764,10 +3757,10 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { { Name: ptr.To(svcPrefix + string(v1.ProtocolTCP) + "-" + strconv.Itoa(int(service7.Spec.HealthCheckNodePort)) + ipv6Suffix), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10081)), RequestPath: ptr.To("/healthz"), - Protocol: network.ProbeProtocolHTTP, + Protocol: to.Ptr(armnetwork.ProbeProtocolHTTP), IntervalInSeconds: ptr.To(int32(5)), ProbeThreshold: ptr.To(int32(2)), }, @@ -3776,34 +3769,34 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { service8 := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80) lb8 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("anotherRG"), ptr.To("testCluster"), ptr.To("aservice1"), service8, "Standard") - lb8.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{} - lb8.Probes = &[]network.Probe{} + lb8.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{} + lb8.Properties.Probes = []*armnetwork.Probe{} expectedLB8 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("anotherRG"), ptr.To("testCluster"), ptr.To("aservice1"), service8, "Standard") - (*expectedLB8.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].DisableOutboundSnat = ptr.To(false) - (*expectedLB8.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].DisableOutboundSnat = ptr.To(false) - expectedLB8.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + (expectedLB8.Properties.LoadBalancingRules)[0].Properties.DisableOutboundSnat = ptr.To(false) + (expectedLB8.Properties.LoadBalancingRules)[1].Properties.DisableOutboundSnat = ptr.To(false) + expectedLB8.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, }, }, { Name: ptr.To("aservice1-IPv6"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, }, }, } - expectedLB8.Probes = &[]network.Probe{ + expectedLB8.Properties.Probes = []*armnetwork.Probe{ { Name: ptr.To(svcPrefix + string(service8.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service7.Spec.Ports[0].Port))), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10080)), - Protocol: network.ProbeProtocolTCP, + Protocol: to.Ptr(armnetwork.ProbeProtocolTCP), IntervalInSeconds: ptr.To(int32(5)), ProbeThreshold: ptr.To(int32(2)), }, @@ -3811,9 +3804,9 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { { Name: ptr.To(svcPrefix + string(service8.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service7.Spec.Ports[0].Port)) + ipv6Suffix), - ProbePropertiesFormat: &network.ProbePropertiesFormat{ + Properties: &armnetwork.ProbePropertiesFormat{ Port: ptr.To(int32(10080)), - Protocol: network.ProbeProtocolTCP, + Protocol: to.Ptr(armnetwork.ProbeProtocolTCP), IntervalInSeconds: ptr.To(int32(5)), ProbeThreshold: ptr.To(int32(2)), }, @@ -3823,22 +3816,22 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { testCases := []struct { desc string service v1.Service - loadBalancerSku string + loadBalancerSKU string preConfigLBType string loadBalancerResourceGroup string disableOutboundSnat *bool wantLb bool shouldRefreshLBAfterReconcileBackendPools bool - existingLB network.LoadBalancer - expectedLB network.LoadBalancer + existingLB *armnetwork.LoadBalancer + expectedLB *armnetwork.LoadBalancer expectLBUpdate bool - expectedGetLBError *retry.Error + expectedGetLBError error expectedError error }{ { desc: "reconcileLoadBalancer shall return the lb deeply equal to the existingLB if there's no " + "modification needed when wantLb == true", - loadBalancerSku: "basic", + loadBalancerSKU: "basic", service: service1, existingLB: basicLb1, wantLb: true, @@ -3848,7 +3841,7 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { { desc: "reconcileLoadBalancer shall return the lb deeply equal to the existingLB if there's no " + "modification needed when wantLb == false", - loadBalancerSku: "basic", + loadBalancerSKU: "basic", service: service2, existingLB: basicLb2, wantLb: false, @@ -3857,7 +3850,7 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { }, { desc: "reconcileLoadBalancer shall remove and reconstruct the corresponding field of lb", - loadBalancerSku: "basic", + loadBalancerSKU: "basic", service: service3, existingLB: modifiedLbs[0], wantLb: true, @@ -3867,7 +3860,7 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { }, { desc: "reconcileLoadBalancer shall not raise an error", - loadBalancerSku: "basic", + loadBalancerSKU: "basic", service: service3, existingLB: modifiedLbs[1], preConfigLBType: "external", @@ -3878,7 +3871,7 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { }, { desc: "reconcileLoadBalancer shall remove and reconstruct the corresponding field of lb and set enableTcpReset to true in lbRule", - loadBalancerSku: "standard", + loadBalancerSKU: "standard", service: service4, disableOutboundSnat: ptr.To(true), existingLB: existingSLB, @@ -3889,7 +3882,7 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { }, { desc: "reconcileLoadBalancer shall remove and reconstruct the corresponding field of lb and set enableTcpReset (false => true) in lbRule", - loadBalancerSku: "standard", + loadBalancerSKU: "standard", service: service5, disableOutboundSnat: ptr.To(true), existingLB: slb5, @@ -3900,7 +3893,7 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { }, { desc: "reconcileLoadBalancer shall reconcile UDP services", - loadBalancerSku: "basic", + loadBalancerSKU: "basic", service: service6, existingLB: lb6, wantLb: true, @@ -3910,7 +3903,7 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { }, { desc: "reconcileLoadBalancer shall reconcile probes for local traffic policy UDP services", - loadBalancerSku: "basic", + loadBalancerSKU: "basic", service: service7, existingLB: lb7, wantLb: true, @@ -3920,7 +3913,7 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { }, { desc: "reconcileLoadBalancer in other resource group", - loadBalancerSku: "standard", + loadBalancerSKU: "standard", loadBalancerResourceGroup: "anotherRG", service: service8, existingLB: lb8, @@ -3931,7 +3924,7 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { }, { desc: "reconcileLoadBalancer should refresh the LB after reconciling backend pools if needed", - loadBalancerSku: "basic", + loadBalancerSKU: "basic", service: service1, existingLB: basicLb1, wantLb: true, @@ -3945,73 +3938,74 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { existingLB: basicLb1, wantLb: true, shouldRefreshLBAfterReconcileBackendPools: true, - expectedGetLBError: retry.NewError(false, errors.New("error")), - expectedError: fmt.Errorf("reconcileLoadBalancer for service (default/service1): failed to get load balancer testCluster: %w", retry.NewError(false, errors.New("error")).Error()), + expectedGetLBError: &azcore.ResponseError{ErrorCode: "error"}, + expectedError: fmt.Errorf("reconcileLoadBalancer for service (default/service1): failed to get load balancer testCluster: %w", errors.New("error")), }, } for _, test := range testCases { test := test t.Run(test.desc, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() az := GetTestCloud(ctrl) - az.Config.LoadBalancerSku = test.loadBalancerSku - az.DisableOutboundSNAT = test.disableOutboundSnat + az.Config.LoadBalancerSKU = test.loadBalancerSKU + az.Config.DisableOutboundSNAT = test.disableOutboundSnat if test.preConfigLBType != "" { az.Config.PreConfiguredBackendPoolLoadBalancerTypes = test.preConfigLBType } az.LoadBalancerResourceGroup = test.loadBalancerResourceGroup clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 3, 3) - setMockEnvDualStack(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnvDualStack(az, expectedInterfaces, expectedVirtualMachines, 1) service := test.service setServiceLoadBalancerIP(&service, "1.2.3.4") setServiceLoadBalancerIP(&service, "fd00::eef0") - err := az.PublicIPAddressesClient.CreateOrUpdate(context.TODO(), "rg", "pipName", network.PublicIPAddress{ + _, err := az.NetworkClientFactory.GetPublicIPAddressClient().CreateOrUpdate(context.TODO(), "rg", "pipName", armnetwork.PublicIPAddress{ Name: ptr.To("pipName"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), - PublicIPAddressVersion: network.IPv4, + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }) - assert.NoError(t, err.Error()) - err = az.PublicIPAddressesClient.CreateOrUpdate(context.TODO(), "rg", "pipName-IPv6", network.PublicIPAddress{ + assert.NoError(t, err) + _, err = az.NetworkClientFactory.GetPublicIPAddressClient().CreateOrUpdate(context.TODO(), "rg", "pipName-IPv6", armnetwork.PublicIPAddress{ Name: ptr.To("pipName-IPv6"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("fd00::eef0"), - PublicIPAddressVersion: network.IPv6, + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), }, }) - assert.NoError(t, err.Error()) + assert.NoError(t, err) - mockLBsClient := mockloadbalancerclient.NewMockInterface(ctrl) - mockLBsClient.EXPECT().List(gomock.Any(), az.getLoadBalancerResourceGroup()).Return([]network.LoadBalancer{test.existingLB}, nil) + mockLBsClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBsClient.EXPECT().List(gomock.Any(), az.getLoadBalancerResourceGroup()).Return([]*armnetwork.LoadBalancer{test.existingLB}, nil) mockLBsClient.EXPECT().Get(gomock.Any(), az.getLoadBalancerResourceGroup(), *test.existingLB.Name, gomock.Any()).Return(test.existingLB, test.expectedGetLBError).AnyTimes() expectLBUpdateCount := 1 if test.expectLBUpdate { expectLBUpdateCount++ } - mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), az.getLoadBalancerResourceGroup(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).Times(expectLBUpdateCount) - az.LoadBalancerClient = mockLBsClient + mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), az.getLoadBalancerResourceGroup(), gomock.Any(), gomock.Any()).Return(nil, nil).Times(expectLBUpdateCount) - err = az.LoadBalancerClient.CreateOrUpdate(context.TODO(), az.getLoadBalancerResourceGroup(), "lb1", test.existingLB, "") - assert.NoError(t, err.Error()) + _, err = az.NetworkClientFactory.GetLoadBalancerClient().CreateOrUpdate(context.TODO(), az.getLoadBalancerResourceGroup(), "lb1", *test.existingLB) + assert.NoError(t, err) mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) if test.shouldRefreshLBAfterReconcileBackendPools { - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(false, false, &test.expectedLB, test.expectedError) + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(false, false, test.expectedLB, test.expectedError) } - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { return false, false, lb, nil }).AnyTimes() mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() lb, rerr := az.reconcileLoadBalancer(context.TODO(), "testCluster", &service, clusterResources.nodes, test.wantLb) - assert.Equal(t, test.expectedError, rerr) - - if test.expectedError == nil { - assert.Equal(t, test.expectedLB, *lb) + if test.expectedError != nil { + assert.EqualError(t, rerr, test.expectedError.Error()) + } else { + assert.Equal(t, *test.expectedLB, *lb) } }) } @@ -4027,50 +4021,50 @@ func TestGetServiceLoadBalancerStatus(t *testing.T) { internalService := getInternalTestService("service1", 80) v4Enabled, v6Enabled := getIPFamiliesEnabled(&service) - setMockPublicIPs(az, ctrl, 1, v4Enabled, v6Enabled) + setMockPublicIPs(az, 1, v4Enabled, v6Enabled) lb1 := getTestLoadBalancer(ptr.To("lb1"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), internalService, "Basic") - lb1.FrontendIPConfigurations = nil + lb1.Properties.FrontendIPConfigurations = nil lb2 := getTestLoadBalancer(ptr.To("lb2"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), internalService, "Basic") - lb2.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + lb2.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, PrivateIPAddress: ptr.To("private"), }, }, } lb3 := getTestLoadBalancer(ptr.To("lb3"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("test1"), internalService, "Basic") - lb3.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + lb3.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("bservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, PrivateIPAddress: ptr.To("private"), }, }, } lb4 := getTestLoadBalancer(ptr.To("lb4"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service, "Basic") - lb4.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + lb4.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: nil}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: nil}, PrivateIPAddress: ptr.To("private"), }, }, } lb5 := getTestLoadBalancer(ptr.To("lb5"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service, "Basic") - lb5.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + lb5.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: nil, PrivateIPAddress: ptr.To("private"), }, @@ -4078,11 +4072,11 @@ func TestGetServiceLoadBalancerStatus(t *testing.T) { } lb6 := getTestLoadBalancer(ptr.To("lb6"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service, "Basic") - lb6.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ + lb6.Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("aservice1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("illegal/id/")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("illegal/id/")}, PrivateIPAddress: ptr.To("private"), }, }, @@ -4091,7 +4085,7 @@ func TestGetServiceLoadBalancerStatus(t *testing.T) { testCases := []struct { desc string service *v1.Service - lb *network.LoadBalancer + lb *armnetwork.LoadBalancer expectedStatus *v1.LoadBalancerStatus expectedError bool }{ @@ -4103,44 +4097,44 @@ func TestGetServiceLoadBalancerStatus(t *testing.T) { { desc: "getServiceLoadBalancerStatus shall return nil if given lb has no front ip config", service: &service, - lb: &lb1, + lb: lb1, }, { desc: "getServiceLoadBalancerStatus shall return private ip if service is internal", service: &internalService, - lb: &lb2, + lb: lb2, expectedStatus: &v1.LoadBalancerStatus{Ingress: []v1.LoadBalancerIngress{{IP: "private"}}}, }, { - desc: "getServiceLoadBalancerStatus shall return nil if lb.FrontendIPConfigurations.name != " + + desc: "getServiceLoadBalancerStatus shall return nil if lb.Properties.FrontendIPConfigurations.name != " + "az.getDefaultFrontendIPConfigName(service)", service: &internalService, - lb: &lb3, + lb: lb3, }, { desc: "getServiceLoadBalancerStatus shall report error if the id of lb's " + "public ip address cannot be read", service: &service, - lb: &lb4, + lb: lb4, expectedError: true, }, { desc: "getServiceLoadBalancerStatus shall report error if lb's public ip address cannot be read", service: &service, - lb: &lb5, + lb: lb5, expectedError: true, }, { desc: "getServiceLoadBalancerStatus shall report error if id of lb's public ip address is illegal", service: &service, - lb: &lb6, + lb: lb6, expectedError: true, }, { desc: "getServiceLoadBalancerStatus shall return the corresponding " + "lb status if everything is good", service: &service, - lb: &lb2, + lb: lb2, expectedStatus: &v1.LoadBalancerStatus{Ingress: []v1.LoadBalancerIngress{{IP: "1.2.3.4"}}}, }, } @@ -4160,109 +4154,108 @@ func TestSafeDeletePublicIP(t *testing.T) { testCases := []struct { desc string - pip *network.PublicIPAddress - lb *network.LoadBalancer - listError *retry.Error + pip *armnetwork.PublicIPAddress + lb *armnetwork.LoadBalancer + listError error expectedError error }{ { desc: "safeDeletePublicIP shall delete corresponding ip configurations and lb rules", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPConfiguration: &network.IPConfiguration{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + IPConfiguration: &armnetwork.IPConfiguration{ ID: ptr.To("id1"), }, }, }, - lb: &network.LoadBalancer{ + lb: &armnetwork.LoadBalancer{ Name: ptr.To("lb1"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + FrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{ { ID: ptr.To("id1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - LoadBalancingRules: &[]network.SubResource{{ID: ptr.To("rules1")}}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + LoadBalancingRules: []*armnetwork.SubResource{{ID: ptr.To("rules1")}}, }, }, }, - LoadBalancingRules: &[]network.LoadBalancingRule{{ID: ptr.To("rules1")}}, + LoadBalancingRules: []*armnetwork.LoadBalancingRule{{ID: ptr.To("rules1")}}, }, }, }, { desc: "safeDeletePublicIP should return error if failed to list pip", - pip: &network.PublicIPAddress{ + pip: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPConfiguration: &network.IPConfiguration{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + IPConfiguration: &armnetwork.IPConfiguration{ ID: ptr.To("id1"), }, }, }, - listError: retry.NewError(false, errors.New("error")), - expectedError: retry.NewError(false, errors.New("error")).Error(), + listError: &azcore.ResponseError{ErrorCode: "error"}, + expectedError: &azcore.ResponseError{ErrorCode: "error"}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { az := GetTestCloud(ctrl) - mockPIPsClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) if test.pip != nil && - test.pip.PublicIPAddressPropertiesFormat != nil && - test.pip.IPConfiguration != nil { - mockPIPsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]network.PublicIPAddress{*test.pip}, test.listError) + test.pip.Properties != nil && + test.pip.Properties.IPConfiguration != nil { + mockPIPsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armnetwork.PublicIPAddress{test.pip}, test.listError) } - mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", "pip1", gomock.Any()).Return(nil).AnyTimes() + mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", "pip1", gomock.Any()).Return(nil, nil).AnyTimes() mockPIPsClient.EXPECT().Delete(gomock.Any(), "rg", "pip1").Return(nil).AnyTimes() - err := az.PublicIPAddressesClient.CreateOrUpdate(context.TODO(), "rg", "pip1", network.PublicIPAddress{ + _, err := az.NetworkClientFactory.GetPublicIPAddressClient().CreateOrUpdate(context.TODO(), "rg", "pip1", armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPConfiguration: &network.IPConfiguration{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + IPConfiguration: &armnetwork.IPConfiguration{ ID: ptr.To("id1"), }, }, }) - assert.NoError(t, err.Error()) + assert.NoError(t, err) service := getTestService("test1", v1.ProtocolTCP, nil, false, 80) if test.listError == nil { - mockLBsClient := mockloadbalancerclient.NewMockInterface(ctrl) - mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) - az.LoadBalancerClient = mockLBsClient + mockLBsClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil) } rerr := az.safeDeletePublicIP(context.TODO(), &service, "rg", test.pip, test.lb) if test.expectedError == nil { - assert.Equal(t, 0, len(*test.lb.FrontendIPConfigurations)) - assert.Equal(t, 0, len(*test.lb.LoadBalancingRules)) + assert.Equal(t, 0, len(test.lb.Properties.FrontendIPConfigurations)) + assert.Equal(t, 0, len(test.lb.Properties.LoadBalancingRules)) assert.NoError(t, rerr) } else { - assert.Equal(t, rerr.Error(), test.listError.Error().Error()) + assert.Equal(t, rerr.Error(), test.listError.Error()) } }) } } func TestReconcilePublicIPsCommon(t *testing.T) { - deleteUnwantedPIPsAndCreateANewOneclientGet := func(client *mockpublicipclient.MockInterface) { - client.EXPECT().Get(gomock.Any(), "rg", "testCluster-atest1", gomock.Any()).Return(network.PublicIPAddress{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1")}, nil).Times(1) - client.EXPECT().Get(gomock.Any(), "rg", "testCluster-atest1-IPv6", gomock.Any()).Return(network.PublicIPAddress{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1-IPv6")}, nil).Times(1) + deleteUnwantedPIPsAndCreateANewOneclientGet := func(client *mock_publicipaddressclient.MockInterface) { + client.EXPECT().Get(gomock.Any(), "rg", "testCluster-atest1", gomock.Any()).Return(&armnetwork.PublicIPAddress{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1")}, nil).Times(1) + client.EXPECT().Get(gomock.Any(), "rg", "testCluster-atest1-IPv6", gomock.Any()).Return(&armnetwork.PublicIPAddress{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1-IPv6")}, nil).Times(1) } - getPIPAddMissingOne := func(client *mockpublicipclient.MockInterface) { - client.EXPECT().Get(gomock.Any(), "rg", "testCluster-atest1-IPv6", gomock.Any()).Return(network.PublicIPAddress{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1-IPv6")}, nil).Times(1) + getPIPAddMissingOne := func(client *mock_publicipaddressclient.MockInterface) { + client.EXPECT().Get(gomock.Any(), "rg", "testCluster-atest1-IPv6", gomock.Any()).Return(&armnetwork.PublicIPAddress{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1-IPv6")}, nil).Times(1) } testCases := []struct { desc string annotations map[string]string - existingPIPs []network.PublicIPAddress + existingPIPs []*armnetwork.PublicIPAddress wantLb bool expectedIDs []string - expectedPIPs []*network.PublicIPAddress // len(expectedPIPs) <= 2 + expectedPIPs []*armnetwork.PublicIPAddress // len(expectedPIPs) <= 2 expectedError bool expectedCreateOrUpdateCount int expectedDeleteCount int - expectedClientGet *func(client *mockpublicipclient.MockInterface) + expectedClientGet *func(client *mock_publicipaddressclient.MockInterface) }{ { desc: "shall return nil if there's no pip in service", @@ -4273,7 +4266,7 @@ func TestReconcilePublicIPsCommon(t *testing.T) { { desc: "shall return nil if no pip is owned by service", wantLb: false, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip1"), }, @@ -4284,18 +4277,18 @@ func TestReconcilePublicIPsCommon(t *testing.T) { { desc: "shall delete unwanted pips and create new ones", wantLb: true, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip1"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("pip1-IPv6"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("fd00::eef0"), }, }, @@ -4314,7 +4307,7 @@ func TestReconcilePublicIPsCommon(t *testing.T) { desc: "shall report error if the given PIP name doesn't exist in the resource group", wantLb: true, annotations: map[string]string{consts.ServiceAnnotationPIPNameDualStack[false]: "testPIP"}, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip1"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, @@ -4335,48 +4328,48 @@ func TestReconcilePublicIPsCommon(t *testing.T) { consts.ServiceAnnotationPIPNameDualStack[false]: "testPIP", consts.ServiceAnnotationPIPNameDualStack[true]: "testPIP-IPv6", }, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip1"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("pip2"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("testPIP"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("testPIP-IPv6"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Dynamic, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), IPAddress: ptr.To("fd00::eef0"), }, }, }, - expectedPIPs: []*network.PublicIPAddress{ + expectedPIPs: []*armnetwork.PublicIPAddress{ { ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), Name: ptr.To("testPIP"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, @@ -4384,9 +4377,9 @@ func TestReconcilePublicIPsCommon(t *testing.T) { ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), Name: ptr.To("testPIP-IPv6"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Dynamic, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), IPAddress: ptr.To("fd00::eef0"), }, }, @@ -4401,64 +4394,64 @@ func TestReconcilePublicIPsCommon(t *testing.T) { consts.ServiceAnnotationPIPNameDualStack[false]: "testPIP", consts.ServiceAnnotationPIPNameDualStack[true]: "testPIP-IPv6", }, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip1"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("pip2"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1,default/test2")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("pip1-IPv6"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), IPAddress: ptr.To("fd00::eef0"), }, }, { Name: ptr.To("pip2-IPv6"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1,default/test2")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), IPAddress: ptr.To("fd00::eef0"), }, }, { Name: ptr.To("testPIP"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("testPIP-IPv6"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Dynamic, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), IPAddress: ptr.To("fd00::eef0"), }, }, }, - expectedPIPs: []*network.PublicIPAddress{ + expectedPIPs: []*armnetwork.PublicIPAddress{ { ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), Name: ptr.To("testPIP"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, @@ -4466,9 +4459,9 @@ func TestReconcilePublicIPsCommon(t *testing.T) { ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), Name: ptr.To("testPIP-IPv6"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Dynamic, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), IPAddress: ptr.To("fd00::eef0"), }, }, @@ -4484,53 +4477,53 @@ func TestReconcilePublicIPsCommon(t *testing.T) { consts.ServiceAnnotationPIPNameDualStack[true]: "testPIP-IPv6", consts.ServiceAnnotationIPTagsForPublicIP: "tag1=tag1value", }, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip1"), Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("default/test1"), consts.LegacyServiceTagKey: ptr.To("foo"), // It should be ignored when ServiceTagKey is present. }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("pip2"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("testPIP"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("testPIP-IPv6"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Dynamic, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), IPAddress: ptr.To("fd00::eef0"), }, }, }, - expectedPIPs: []*network.PublicIPAddress{ + expectedPIPs: []*armnetwork.PublicIPAddress{ { ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), Name: ptr.To("testPIP"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, - PublicIPAllocationMethod: network.Static, - IPTags: &[]network.IPTag{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), + IPTags: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -4542,10 +4535,10 @@ func TestReconcilePublicIPsCommon(t *testing.T) { ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), Name: ptr.To("testPIP-IPv6"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Dynamic, - IPTags: &[]network.IPTag{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + IPTags: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -4565,14 +4558,14 @@ func TestReconcilePublicIPsCommon(t *testing.T) { consts.ServiceAnnotationPIPNameDualStack[true]: "testPIP-IPv6", consts.ServiceAnnotationIPTagsForPublicIP: "tag1=tag1value", }, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("testPIP"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, - PublicIPAllocationMethod: network.Static, - IPTags: &[]network.IPTag{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), + IPTags: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -4584,10 +4577,10 @@ func TestReconcilePublicIPsCommon(t *testing.T) { { Name: ptr.To("testPIP-IPv6"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Dynamic, - IPTags: &[]network.IPTag{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + IPTags: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -4597,15 +4590,15 @@ func TestReconcilePublicIPsCommon(t *testing.T) { }, }, }, - expectedPIPs: []*network.PublicIPAddress{ + expectedPIPs: []*armnetwork.PublicIPAddress{ { ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), Name: ptr.To("testPIP"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, - PublicIPAllocationMethod: network.Static, - IPTags: &[]network.IPTag{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), + IPTags: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -4618,10 +4611,10 @@ func TestReconcilePublicIPsCommon(t *testing.T) { ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), Name: ptr.To("testPIP-IPv6"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Dynamic, - IPTags: &[]network.IPTag{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + IPTags: []*armnetwork.IPTag{ { IPTagType: ptr.To("tag1"), Tag: ptr.To("tag1value"), @@ -4641,62 +4634,62 @@ func TestReconcilePublicIPsCommon(t *testing.T) { consts.ServiceAnnotationPIPNameDualStack[false]: "testPIP", consts.ServiceAnnotationPIPNameDualStack[true]: "testPIP-IPv6", }, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("pip2"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("testPIP"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("pip2-IPv6"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Dynamic, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), IPAddress: ptr.To("fd00::eef0"), }, }, { Name: ptr.To("testPIP-IPv6"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Dynamic, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), IPAddress: ptr.To("fd00::eef0"), }, }, }, - expectedPIPs: []*network.PublicIPAddress{ + expectedPIPs: []*armnetwork.PublicIPAddress{ { ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), Name: ptr.To("testPIP"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), Name: ptr.To("testPIP-IPv6"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Dynamic, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), IPAddress: ptr.To("fd00::eef0"), }, }, @@ -4707,22 +4700,22 @@ func TestReconcilePublicIPsCommon(t *testing.T) { { desc: "shall delete the unwanted PIP name from service tag and shall not delete it if there is other reference", wantLb: false, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip1"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1,default/test2")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), - PublicIPAddressVersion: network.IPv4, + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, { Name: ptr.To("pip1-IPv6"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1,default/test2")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("fd00::eef0"), - PublicIPAllocationMethod: network.Dynamic, - PublicIPAddressVersion: network.IPv6, + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), }, }, }, @@ -4731,13 +4724,13 @@ func TestReconcilePublicIPsCommon(t *testing.T) { { desc: "shall create the missing one", wantLb: true, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("testCluster-atest1"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1"), Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, @@ -4760,19 +4753,19 @@ func TestReconcilePublicIPsCommon(t *testing.T) { defer ctrl.Finish() deletedPips := make(map[string]bool) - savedPips := make(map[string]network.PublicIPAddress) + savedPips := make(map[string]*armnetwork.PublicIPAddress) createOrUpdateCount := 0 var m sync.Mutex az := GetTestCloud(ctrl) - mockPIPsClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) creator := mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", gomock.Any(), gomock.Any()).AnyTimes() - creator.DoAndReturn(func(_ context.Context, _ string, publicIPAddressName string, parameters network.PublicIPAddress) *retry.Error { + creator.DoAndReturn(func(_ context.Context, _ string, publicIPAddressName string, parameters armnetwork.PublicIPAddress) (result *armnetwork.PublicIPAddress, rerr error) { m.Lock() deletedPips[publicIPAddressName] = false - savedPips[publicIPAddressName] = parameters + savedPips[publicIPAddressName] = ¶meters createOrUpdateCount++ m.Unlock() - return nil + return nil, nil }) if test.expectedClientGet != nil { @@ -4783,7 +4776,7 @@ func TestReconcilePublicIPsCommon(t *testing.T) { for _, pip := range test.existingPIPs { savedPips[*pip.Name] = pip getter := mockPIPsClient.EXPECT().Get(gomock.Any(), "rg", *pip.Name, gomock.Any()).AnyTimes() - getter.DoAndReturn(func(_ context.Context, _ string, publicIPAddressName string, _ string) (result network.PublicIPAddress, rerr *retry.Error) { + getter.DoAndReturn(func(_ context.Context, _ string, publicIPAddressName string, _ *string) (result *armnetwork.PublicIPAddress, rerr error) { m.Lock() deletedValue, deletedContains := deletedPips[publicIPAddressName] savedPipValue, savedPipContains := savedPips[publicIPAddressName] @@ -4793,24 +4786,24 @@ func TestReconcilePublicIPsCommon(t *testing.T) { return savedPipValue, nil } - return network.PublicIPAddress{}, &retry.Error{HTTPStatusCode: http.StatusNotFound} + return nil, &azcore.ResponseError{StatusCode: http.StatusNotFound} }) deleter := mockPIPsClient.EXPECT().Delete(gomock.Any(), "rg", *pip.Name).Return(nil).AnyTimes() - deleter.Do(func(_ context.Context, _ string, publicIPAddressName string) *retry.Error { + deleter.Do(func(_ context.Context, _ string, publicIPAddressName string) error { m.Lock() deletedPips[publicIPAddressName] = true m.Unlock() return nil }) - err := az.PublicIPAddressesClient.CreateOrUpdate(context.TODO(), "rg", ptr.Deref(pip.Name, ""), pip) - assert.NoError(t, err.Error()) + _, err := az.NetworkClientFactory.GetPublicIPAddressClient().CreateOrUpdate(context.TODO(), "rg", ptr.Deref(pip.Name, ""), *pip) + assert.NoError(t, err) // Clear create or update count to prepare for main execution createOrUpdateCount = 0 } lister := mockPIPsClient.EXPECT().List(gomock.Any(), "rg").AnyTimes() - lister.DoAndReturn(func(_ context.Context, _ string) (result []network.PublicIPAddress, rerr *retry.Error) { + lister.DoAndReturn(func(_ context.Context, _ string) (result []*armnetwork.PublicIPAddress, rerr error) { m.Lock() for pipName, pip := range savedPips { deleted, deletedContains := deletedPips[pipName] @@ -4830,19 +4823,19 @@ func TestReconcilePublicIPsCommon(t *testing.T) { if len(test.expectedIDs) != 0 { ids := []string{} for _, pip := range pips { - ids = append(ids, ptr.Deref(pip.ID, "")) + ids = append(ids, *pip.ID) } assert.Truef(t, compareStrings(test.expectedIDs, ids), "expectedIDs %q, IDs %q", test.expectedIDs, ids) } // Check PIPs if len(test.expectedPIPs) != 0 { - pipsNames := []string{} + pipsNames := []*string{} for _, pip := range pips { - pipsNames = append(pipsNames, ptr.Deref(pip.Name, "")) + pipsNames = append(pipsNames, pip.Name) } assert.Equal(t, len(test.expectedPIPs), len(pips), pipsNames) - pipsOrdered := []*network.PublicIPAddress{} + pipsOrdered := []*armnetwork.PublicIPAddress{} if len(test.expectedPIPs) == 1 { pipsOrdered = append(pipsOrdered, pips[0]) } else { @@ -4859,16 +4852,16 @@ func TestReconcilePublicIPsCommon(t *testing.T) { assert.NotNil(t, pip.Name) assert.Equal(t, *test.expectedPIPs[i].Name, *pip.Name, "pip name %q", *pip.Name) - if test.expectedPIPs[i].PublicIPAddressPropertiesFormat != nil { - sortIPTags(test.expectedPIPs[i].PublicIPAddressPropertiesFormat.IPTags) + if test.expectedPIPs[i].Properties != nil { + sortIPTags(&test.expectedPIPs[i].Properties.IPTags) } - if pip.PublicIPAddressPropertiesFormat != nil { - sortIPTags(pip.PublicIPAddressPropertiesFormat.IPTags) + if pip.Properties != nil { + sortIPTags(&pip.Properties.IPTags) } - assert.Equal(t, test.expectedPIPs[i].PublicIPAddressPropertiesFormat, - pip.PublicIPAddressPropertiesFormat, "pip name %q", *pip.Name) + assert.Equal(t, test.expectedPIPs[i].Properties, + pip.Properties, "pip name %q", *pip.Name) } } assert.Equal(t, test.expectedCreateOrUpdateCount, createOrUpdateCount) @@ -4901,8 +4894,8 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { inputDNSLabel string expectedID string additionalAnnotations map[string]string - existingPIPs []network.PublicIPAddress - expectedPIP *network.PublicIPAddress + existingPIPs []*armnetwork.PublicIPAddress + expectedPIP *armnetwork.PublicIPAddress foundDNSLabelAnnotation bool isIPv6 bool useSLB bool @@ -4912,13 +4905,13 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { { desc: "shall return existed IPv4 PIP if there is any", pipName: "pip1", - existingPIPs: []network.PublicIPAddress{{Name: ptr.To("pip1")}}, - expectedPIP: &network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{{Name: ptr.To("pip1")}}, + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), ID: ptr.To(expectedPIPID), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, - PublicIPAllocationMethod: network.Static, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), }, Tags: map[string]*string{}, }, @@ -4927,14 +4920,14 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { { desc: "shall return existed IPv6 PIP if there is any", pipName: "pip1-IPv6", - existingPIPs: []network.PublicIPAddress{{Name: ptr.To("pip1-IPv6")}}, - expectedPIP: &network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{{Name: ptr.To("pip1-IPv6")}}, + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1-IPv6"), ID: ptr.To(rgprefix + "/providers/Microsoft.Network/publicIPAddresses/pip1-IPv6"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Dynamic, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), }, Tags: map[string]*string{}, }, @@ -4953,18 +4946,18 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { pipName: "pip1", inputDNSLabel: "newdns", foundDNSLabelAnnotation: true, - existingPIPs: []network.PublicIPAddress{{ - Name: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{}, + existingPIPs: []*armnetwork.PublicIPAddress{{ + Name: ptr.To("pip1"), + Properties: &armnetwork.PublicIPAddressPropertiesFormat{}, }}, - expectedPIP: &network.PublicIPAddress{ + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), ID: ptr.To(expectedPIPID), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - DNSSettings: &network.PublicIPAddressDNSSettings{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + DNSSettings: &armnetwork.PublicIPAddressDNSSettings{ DomainNameLabel: ptr.To("newdns"), }, - PublicIPAddressVersion: network.IPv4, + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, Tags: map[string]*string{consts.ServiceUsingDNSKey: ptr.To("default/test1")}, }, @@ -4974,20 +4967,20 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { desc: "shall delete DNS from PIP if DNS label is set empty", pipName: "pip1", foundDNSLabelAnnotation: true, - existingPIPs: []network.PublicIPAddress{{ + existingPIPs: []*armnetwork.PublicIPAddress{{ Name: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - DNSSettings: &network.PublicIPAddressDNSSettings{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + DNSSettings: &armnetwork.PublicIPAddressDNSSettings{ DomainNameLabel: ptr.To("previousdns"), }, }, }}, - expectedPIP: &network.PublicIPAddress{ + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), ID: ptr.To(expectedPIPID), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ DNSSettings: nil, - PublicIPAddressVersion: network.IPv4, + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, Tags: map[string]*string{}, }, @@ -4997,22 +4990,22 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { desc: "shall not delete DNS from PIP if DNS label annotation is not set", pipName: "pip1", foundDNSLabelAnnotation: false, - existingPIPs: []network.PublicIPAddress{{ + existingPIPs: []*armnetwork.PublicIPAddress{{ Name: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - DNSSettings: &network.PublicIPAddressDNSSettings{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + DNSSettings: &armnetwork.PublicIPAddressDNSSettings{ DomainNameLabel: ptr.To("previousdns"), }, }, }}, - expectedPIP: &network.PublicIPAddress{ + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), ID: ptr.To(expectedPIPID), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - DNSSettings: &network.PublicIPAddressDNSSettings{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + DNSSettings: &armnetwork.PublicIPAddressDNSSettings{ DomainNameLabel: ptr.To("previousdns"), }, - PublicIPAddressVersion: network.IPv4, + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, @@ -5022,19 +5015,19 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { inputDNSLabel: "newdns", foundDNSLabelAnnotation: true, isIPv6: true, - existingPIPs: []network.PublicIPAddress{{ - Name: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{}, + existingPIPs: []*armnetwork.PublicIPAddress{{ + Name: ptr.To("pip1"), + Properties: &armnetwork.PublicIPAddressPropertiesFormat{}, }}, - expectedPIP: &network.PublicIPAddress{ + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), ID: ptr.To(expectedPIPID), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - DNSSettings: &network.PublicIPAddressDNSSettings{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + DNSSettings: &armnetwork.PublicIPAddressDNSSettings{ DomainNameLabel: ptr.To("newdns"), }, - PublicIPAllocationMethod: network.Dynamic, - PublicIPAddressVersion: network.IPv6, + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), }, Tags: map[string]*string{consts.ServiceUsingDNSKey: ptr.To("default/test1")}, }, @@ -5046,23 +5039,23 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { inputDNSLabel: "newdns", foundDNSLabelAnnotation: true, isIPv6: true, - existingPIPs: []network.PublicIPAddress{{ + existingPIPs: []*armnetwork.PublicIPAddress{{ Name: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - DNSSettings: &network.PublicIPAddressDNSSettings{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + DNSSettings: &armnetwork.PublicIPAddressDNSSettings{ DomainNameLabel: ptr.To("previousdns"), }, }, }}, - expectedPIP: &network.PublicIPAddress{ + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), ID: ptr.To(expectedPIPID), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - DNSSettings: &network.PublicIPAddressDNSSettings{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + DNSSettings: &armnetwork.PublicIPAddressDNSSettings{ DomainNameLabel: ptr.To("newdns"), }, - PublicIPAllocationMethod: network.Dynamic, - PublicIPAddressVersion: network.IPv6, + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), }, Tags: map[string]*string{ "k8s-azure-dns-label-service": ptr.To("default/test1"), @@ -5076,25 +5069,25 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { inputDNSLabel: "newdns", foundDNSLabelAnnotation: true, isIPv6: false, - existingPIPs: []network.PublicIPAddress{{ + existingPIPs: []*armnetwork.PublicIPAddress{{ Name: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - DNSSettings: &network.PublicIPAddressDNSSettings{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + DNSSettings: &armnetwork.PublicIPAddressDNSSettings{ DomainNameLabel: ptr.To("previousdns"), }, - PublicIPAllocationMethod: network.Dynamic, - PublicIPAddressVersion: network.IPv4, + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }}, - expectedPIP: &network.PublicIPAddress{ + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), ID: ptr.To(expectedPIPID), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - DNSSettings: &network.PublicIPAddressDNSSettings{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + DNSSettings: &armnetwork.PublicIPAddressDNSSettings{ DomainNameLabel: ptr.To("newdns"), }, - PublicIPAllocationMethod: network.Dynamic, - PublicIPAddressVersion: network.IPv4, + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, Tags: map[string]*string{ "k8s-azure-dns-label-service": ptr.To("default/test1"), @@ -5107,11 +5100,11 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { pipName: "pip1", inputDNSLabel: "test", foundDNSLabelAnnotation: true, - existingPIPs: []network.PublicIPAddress{{ + existingPIPs: []*armnetwork.PublicIPAddress{{ Name: ptr.To("pip1"), Tags: map[string]*string{consts.ServiceUsingDNSKey: ptr.To("test1")}, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - DNSSettings: &network.PublicIPAddressDNSSettings{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + DNSSettings: &armnetwork.PublicIPAddressDNSSettings{ DomainNameLabel: ptr.To("previousdns"), }, }, @@ -5122,7 +5115,7 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { desc: "shall return the pip without calling PUT API if the tags are good", pipName: "pip1", inputDNSLabel: "test", - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip1"), ID: ptr.To(expectedPIPID), @@ -5130,43 +5123,43 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { consts.ServiceUsingDNSKey: ptr.To("default/test1"), consts.ServiceTagKey: ptr.To("default/test1"), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - DNSSettings: &network.PublicIPAddressDNSSettings{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + DNSSettings: &armnetwork.PublicIPAddressDNSSettings{ DomainNameLabel: ptr.To("test"), }, - PublicIPAllocationMethod: network.Static, - PublicIPAddressVersion: network.IPv4, + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, - expectedPIP: &network.PublicIPAddress{ + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), ID: ptr.To(expectedPIPID), Tags: map[string]*string{ consts.ServiceUsingDNSKey: ptr.To("default/test1"), consts.ServiceTagKey: ptr.To("default/test1"), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - DNSSettings: &network.PublicIPAddressDNSSettings{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + DNSSettings: &armnetwork.PublicIPAddressDNSSettings{ DomainNameLabel: ptr.To("test"), }, - PublicIPAllocationMethod: network.Static, - PublicIPAddressVersion: network.IPv4, + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, { desc: "shall tag the service name to the pip correctly", pipName: "pip1", - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ {Name: ptr.To("pip1")}, }, - expectedPIP: &network.PublicIPAddress{ + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), ID: ptr.To(expectedPIPID), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, - PublicIPAllocationMethod: network.Static, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), }, Tags: map[string]*string{}, }, @@ -5177,21 +5170,21 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { pipName: "pip1", isIPv6: true, useSLB: true, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Static, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), }, }, }, - expectedPIP: &network.PublicIPAddress{ + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), ID: ptr.To(expectedPIPID), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Static, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), }, Tags: map[string]*string{}, }, @@ -5200,14 +5193,14 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { { desc: "shall update pip tags if there is any change", pipName: "pip1", - existingPIPs: []network.PublicIPAddress{{Name: ptr.To("pip1"), Tags: map[string]*string{"a": ptr.To("b")}}}, - expectedPIP: &network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{{Name: ptr.To("pip1"), Tags: map[string]*string{"a": ptr.To("b")}}}, + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), Tags: map[string]*string{"a": ptr.To("c")}, ID: ptr.To(expectedPIPID), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, - PublicIPAllocationMethod: network.Static, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), }, }, additionalAnnotations: map[string]string{ @@ -5218,22 +5211,22 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { { desc: "should not tag the user-assigned pip", pipName: "pip1", - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, Tags: map[string]*string{"a": ptr.To("b")}, }, }, - expectedPIP: &network.PublicIPAddress{ + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), Tags: map[string]*string{"a": ptr.To("b")}, ID: ptr.To(expectedPIPID), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, @@ -5247,50 +5240,50 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { t.Run(test.desc, func(t *testing.T) { az := GetTestCloud(ctrl) if test.useSLB { - az.LoadBalancerSku = consts.LoadBalancerSkuStandard + az.LoadBalancerSKU = consts.LoadBalancerSKUStandard } service := getTestService("test1", v1.ProtocolTCP, nil, test.isIPv6, 80) service.ObjectMeta.Annotations = test.additionalAnnotations - mockPIPsClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) if test.shouldPutPIP { - mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ string, parameters network.PublicIPAddress) *retry.Error { + mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ string, parameters armnetwork.PublicIPAddress) (*armnetwork.PublicIPAddress, error) { if len(test.existingPIPs) != 0 { - test.existingPIPs[0] = parameters + test.existingPIPs[0] = ¶meters } else { - test.existingPIPs = append(test.existingPIPs, parameters) + test.existingPIPs = append(test.existingPIPs, ¶meters) } - return nil + return nil, nil }).AnyTimes() } - mockPIPsClient.EXPECT().Get(gomock.Any(), "rg", test.pipName, gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ string, _ string) (network.PublicIPAddress, *retry.Error) { + mockPIPsClient.EXPECT().Get(gomock.Any(), "rg", test.pipName, gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ string, _ *string) (*armnetwork.PublicIPAddress, error) { return test.existingPIPs[0], nil }).MaxTimes(1) - mockPIPsClient.EXPECT().List(gomock.Any(), "rg").DoAndReturn(func(_ context.Context, _ string) ([]network.PublicIPAddress, *retry.Error) { - var basicPIP *network.PublicIPAddress + mockPIPsClient.EXPECT().List(gomock.Any(), "rg").DoAndReturn(func(_ context.Context, _ string) ([]*armnetwork.PublicIPAddress, error) { + var basicPIP *armnetwork.PublicIPAddress if len(test.existingPIPs) == 0 { - basicPIP = &network.PublicIPAddress{ + basicPIP = &armnetwork.PublicIPAddress{ Name: ptr.To(test.pipName), } } else { - basicPIP = &test.existingPIPs[0] + basicPIP = test.existingPIPs[0] } basicPIP.ID = ptr.To(rgprefix + "/providers/Microsoft.Network/publicIPAddresses/" + test.pipName) - if basicPIP.PublicIPAddressPropertiesFormat == nil { - return []network.PublicIPAddress{*basicPIP}, nil + if basicPIP.Properties == nil { + return []*armnetwork.PublicIPAddress{basicPIP}, nil } if test.isIPv6 { - basicPIP.PublicIPAddressPropertiesFormat.PublicIPAddressVersion = network.IPv6 - basicPIP.PublicIPAllocationMethod = network.Dynamic + basicPIP.Properties.PublicIPAddressVersion = to.Ptr(armnetwork.IPVersionIPv6) + basicPIP.Properties.PublicIPAllocationMethod = to.Ptr(armnetwork.IPAllocationMethodDynamic) } else { - basicPIP.PublicIPAddressPropertiesFormat.PublicIPAddressVersion = network.IPv4 + basicPIP.Properties.PublicIPAddressVersion = to.Ptr(armnetwork.IPVersionIPv4) } - return []network.PublicIPAddress{*basicPIP}, nil + return []*armnetwork.PublicIPAddress{basicPIP}, nil }).AnyTimes() pip, err := az.ensurePublicIPExists(context.TODO(), &service, test.pipName, test.inputDNSLabel, "", false, test.foundDNSLabelAnnotation, test.isIPv6) @@ -5309,7 +5302,7 @@ func TestEnsurePublicIPExistsWithExtendedLocation(t *testing.T) { defer ctrl.Finish() az := GetTestCloudWithExtendedLocation(ctrl) - az.LoadBalancerSku = consts.LoadBalancerSkuStandard + az.LoadBalancerSKU = consts.LoadBalancerSKUStandard service := getTestServiceDualStack("test1", v1.ProtocolTCP, nil, 80) exLocName := "microsoftlosangeles1" @@ -5317,23 +5310,23 @@ func TestEnsurePublicIPExistsWithExtendedLocation(t *testing.T) { testcases := []struct { desc string pipName string - expectedPIP *network.PublicIPAddress + expectedPIP *armnetwork.PublicIPAddress isIPv6 bool }{ { desc: "should create a pip with extended location", pipName: "pip1", - expectedPIP: &network.PublicIPAddress{ + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1"), Location: &az.Location, - ExtendedLocation: &network.ExtendedLocation{ + ExtendedLocation: &armnetwork.ExtendedLocation{ Name: ptr.To("microsoftlosangeles1"), - Type: network.EdgeZone, + Type: to.Ptr(armnetwork.ExtendedLocationTypesEdgeZone), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAllocationMethod: network.Static, - PublicIPAddressVersion: network.IPv4, - ProvisioningState: "", + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), + ProvisioningState: nil, }, Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("default/test1"), @@ -5345,17 +5338,17 @@ func TestEnsurePublicIPExistsWithExtendedLocation(t *testing.T) { { desc: "should create a pip with extended location for IPv6", pipName: "pip1-IPv6", - expectedPIP: &network.PublicIPAddress{ + expectedPIP: &armnetwork.PublicIPAddress{ Name: ptr.To("pip1-IPv6"), Location: &az.Location, - ExtendedLocation: &network.ExtendedLocation{ + ExtendedLocation: &armnetwork.ExtendedLocation{ Name: ptr.To("microsoftlosangeles1"), - Type: network.EdgeZone, + Type: to.Ptr(armnetwork.ExtendedLocationTypesEdgeZone), }, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAllocationMethod: network.Dynamic, - PublicIPAddressVersion: network.IPv6, - ProvisioningState: "", + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + ProvisioningState: nil, }, Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("default/test1"), @@ -5368,19 +5361,19 @@ func TestEnsurePublicIPExistsWithExtendedLocation(t *testing.T) { for _, tc := range testcases { t.Run(tc.desc, func(t *testing.T) { - mockPIPsClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) - first := mockPIPsClient.EXPECT().List(gomock.Any(), "rg").Return([]network.PublicIPAddress{}, nil).Times(2) - mockPIPsClient.EXPECT().Get(gomock.Any(), "rg", tc.pipName, gomock.Any()).Return(*tc.expectedPIP, nil).After(first) + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + first := mockPIPsClient.EXPECT().List(gomock.Any(), "rg").Return([]*armnetwork.PublicIPAddress{}, nil).Times(2) + mockPIPsClient.EXPECT().Get(gomock.Any(), "rg", tc.pipName, gomock.Any()).Return(tc.expectedPIP, nil).After(first) mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", tc.pipName, gomock.Any()). - DoAndReturn(func(_ context.Context, _ string, _ string, publicIPAddressParameters network.PublicIPAddress) *retry.Error { + DoAndReturn(func(_ context.Context, _ string, _ string, publicIPAddressParameters armnetwork.PublicIPAddress) (*armnetwork.PublicIPAddress, error) { assert.NotNil(t, publicIPAddressParameters) assert.NotNil(t, publicIPAddressParameters.ExtendedLocation) assert.Equal(t, *publicIPAddressParameters.ExtendedLocation.Name, exLocName) - assert.Equal(t, publicIPAddressParameters.ExtendedLocation.Type, network.EdgeZone) + assert.Equal(t, *publicIPAddressParameters.ExtendedLocation.Type, armnetwork.ExtendedLocationTypesEdgeZone) // Edge zones don't support availability zones. assert.Nil(t, publicIPAddressParameters.Zones) - return nil + return nil, nil }).Times(1) pip, err := az.ensurePublicIPExists(context.TODO(), &service, tc.pipName, "", "", false, false, tc.isIPv6) assert.NotNil(t, pip, "ensurePublicIPExists shall create a new pip"+ @@ -5441,36 +5434,35 @@ func TestShouldUpdateLoadBalancer(t *testing.T) { for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { az := GetTestCloud(ctrl) - az.LoadBalancerSku = consts.LoadBalancerSkuBasic + az.LoadBalancerSKU = consts.LoadBalancerSKUBasic service := getTestService("test1", v1.ProtocolTCP, nil, false, 80) v4Enabled, v6Enabled := getIPFamiliesEnabled(&service) service.Spec.Type = test.serviceType - setMockPublicIPs(az, ctrl, 1, v4Enabled, v6Enabled) - mockLBsClient := mockloadbalancerclient.NewMockInterface(ctrl) - az.LoadBalancerClient = mockLBsClient + setMockPublicIPs(az, 1, v4Enabled, v6Enabled) + mockLBsClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) if test.existsLb { - mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) + mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil) } if test.lbHasDeletionTimestamp { service.ObjectMeta.DeletionTimestamp = &metav1.Time{Time: time.Now()} } if test.existsLb { - lb := network.LoadBalancer{ + lb := &armnetwork.LoadBalancer{ Name: ptr.To("vmas"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + FrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("atest1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, }, }, }, }, } - err := az.LoadBalancerClient.CreateOrUpdate(context.TODO(), "rg", *lb.Name, lb, "") - assert.NoError(t, err.Error()) - mockLBsClient.EXPECT().List(gomock.Any(), "rg").Return([]network.LoadBalancer{lb}, nil) + _, err := az.NetworkClientFactory.GetLoadBalancerClient().CreateOrUpdate(context.TODO(), "rg", *lb.Name, *lb) + assert.NoError(t, err) + mockLBsClient.EXPECT().List(gomock.Any(), "rg").Return([]*armnetwork.LoadBalancer{lb}, nil) } else { mockLBsClient.EXPECT().List(gomock.Any(), "rg").Return(nil, nil).Times(2) } @@ -5488,7 +5480,7 @@ func TestShouldUpdateLoadBalancer(t *testing.T) { } mockVMSet := NewMockVMSet(ctrl) - mockVMSet.EXPECT().GetAgentPoolVMSetNames(gomock.Any(), gomock.Any()).Return(&[]string{"vmas"}, nil).MaxTimes(1) + mockVMSet.EXPECT().GetAgentPoolVMSetNames(gomock.Any(), gomock.Any()).Return(to.SliceOfPtrs("vmas"), nil).MaxTimes(1) mockVMSet.EXPECT().GetPrimaryVMSetName().Return(az.Config.PrimaryAvailabilitySetName).MaxTimes(3) az.VMSet = mockVMSet @@ -5599,7 +5591,7 @@ func TestParsePIPServiceTag(t *testing.T) { } func TestBindServicesToPIP(t *testing.T) { - pips := []*network.PublicIPAddress{ + pips := []*armnetwork.PublicIPAddress{ {Tags: nil}, {Tags: map[string]*string{}}, {Tags: map[string]*string{consts.ServiceTagKey: ptr.To("ns1/svc1")}}, @@ -5681,7 +5673,7 @@ func TestUnbindServiceFromPIP(t *testing.T) { svc := getTestService(svcName, v1.ProtocolTCP, nil, false, 80) setServiceLoadBalancerIP(&svc, "1.2.3.4") - pip := &network.PublicIPAddress{ + pip := &armnetwork.PublicIPAddress{ Tags: tt.InputTags, } serviceReferences, err := unbindServiceFromPIP(pip, svcName, tt.InputIsUserAssigned) @@ -5706,20 +5698,20 @@ func TestIsFrontendIPConfigIsUnsafeToDelete(t *testing.T) { testCases := []struct { desc string - existingLB *network.LoadBalancer + existingLB *armnetwork.LoadBalancer unsafe bool }{ { desc: "isFrontendIPConfigUnsafeToDelete should return true if there is a " + "loadBalancing rule from other service referencing the frontend IP config", - existingLB: &network.LoadBalancer{ + existingLB: &armnetwork.LoadBalancer{ Name: ptr.To("lb"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("aservice2-rule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("fip")}, }, }, }, @@ -5730,14 +5722,14 @@ func TestIsFrontendIPConfigIsUnsafeToDelete(t *testing.T) { { desc: "isFrontendIPConfigUnsafeToDelete should return true if there is a " + "outbound rule referencing the frontend IP config", - existingLB: &network.LoadBalancer{ + existingLB: &armnetwork.LoadBalancer{ Name: ptr.To("lb"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - OutboundRules: &[]network.OutboundRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + OutboundRules: []*armnetwork.OutboundRule{ { Name: ptr.To("aservice1-rule"), - OutboundRulePropertiesFormat: &network.OutboundRulePropertiesFormat{ - FrontendIPConfigurations: &[]network.SubResource{ + Properties: &armnetwork.OutboundRulePropertiesFormat{ + FrontendIPConfigurations: []*armnetwork.SubResource{ {ID: ptr.To("fip")}, }, }, @@ -5750,14 +5742,14 @@ func TestIsFrontendIPConfigIsUnsafeToDelete(t *testing.T) { { desc: "isFrontendIPConfigUnsafeToDelete should return false if there is a " + "loadBalancing rule from this service referencing the frontend IP config", - existingLB: &network.LoadBalancer{ + existingLB: &armnetwork.LoadBalancer{ Name: ptr.To("lb"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("aservice1-rule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("fip")}, }, }, }, @@ -5767,14 +5759,14 @@ func TestIsFrontendIPConfigIsUnsafeToDelete(t *testing.T) { { desc: "isFrontendIPConfigUnsafeToDelete should return true if there is a " + "inbound NAT rule referencing the frontend IP config", - existingLB: &network.LoadBalancer{ + existingLB: &armnetwork.LoadBalancer{ Name: ptr.To("lb"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - InboundNatRules: &[]network.InboundNatRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + InboundNatRules: []*armnetwork.InboundNatRule{ { Name: ptr.To("aservice2-rule"), - InboundNatRulePropertiesFormat: &network.InboundNatRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + Properties: &armnetwork.InboundNatRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("fip")}, }, }, }, @@ -5785,14 +5777,14 @@ func TestIsFrontendIPConfigIsUnsafeToDelete(t *testing.T) { { desc: "isFrontendIPConfigUnsafeToDelete should return true if there is a " + "inbound NAT pool referencing the frontend IP config", - existingLB: &network.LoadBalancer{ + existingLB: &armnetwork.LoadBalancer{ Name: ptr.To("lb"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - InboundNatPools: &[]network.InboundNatPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + InboundNatPools: []*armnetwork.InboundNatPool{ { Name: ptr.To("aservice2-rule"), - InboundNatPoolPropertiesFormat: &network.InboundNatPoolPropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + Properties: &armnetwork.InboundNatPoolPropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("fip")}, }, }, }, @@ -5818,31 +5810,31 @@ func TestCheckLoadBalancerResourcesConflicted(t *testing.T) { testCases := []struct { desc string fipID string - existingLB *network.LoadBalancer + existingLB *armnetwork.LoadBalancer expectedErr bool }{ { desc: "checkLoadBalancerResourcesConflicts should report the conflict error if " + "there is a conflicted loadBalancing rule - IPv4", fipID: "fip", - existingLB: &network.LoadBalancer{ + existingLB: &armnetwork.LoadBalancer{ Name: ptr.To("lb"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("aservice2-rule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("fip")}, FrontendPort: ptr.To(int32(80)), - Protocol: network.TransportProtocol(v1.ProtocolTCP), + Protocol: to.Ptr(armnetwork.TransportProtocolTCP), }, }, { Name: ptr.To("aservice2-rule-IPv6"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip-IPv6")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("fip-IPv6")}, FrontendPort: ptr.To(int32(80)), - Protocol: network.TransportProtocol(v1.ProtocolTCP), + Protocol: to.Ptr(armnetwork.TransportProtocolTCP), }, }, }, @@ -5854,24 +5846,24 @@ func TestCheckLoadBalancerResourcesConflicted(t *testing.T) { desc: "checkLoadBalancerResourcesConflicts should report the conflict error if " + "there is a conflicted loadBalancing rule - IPv6", fipID: "fip-IPv6", - existingLB: &network.LoadBalancer{ + existingLB: &armnetwork.LoadBalancer{ Name: ptr.To("lb"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("aservice2-rule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("fip")}, FrontendPort: ptr.To(int32(80)), - Protocol: network.TransportProtocol(v1.ProtocolTCP), + Protocol: to.Ptr(armnetwork.TransportProtocolTCP), }, }, { Name: ptr.To("aservice2-rule-IPv6"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip-IPv6")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("fip-IPv6")}, FrontendPort: ptr.To(int32(80)), - Protocol: network.TransportProtocol(v1.ProtocolTCP), + Protocol: to.Ptr(armnetwork.TransportProtocolTCP), }, }, }, @@ -5883,16 +5875,16 @@ func TestCheckLoadBalancerResourcesConflicted(t *testing.T) { desc: "checkLoadBalancerResourcesConflicts should report the conflict error if " + "there is a conflicted inbound NAT rule", fipID: "fip", - existingLB: &network.LoadBalancer{ + existingLB: &armnetwork.LoadBalancer{ Name: ptr.To("lb"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - InboundNatRules: &[]network.InboundNatRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + InboundNatRules: []*armnetwork.InboundNatRule{ { Name: ptr.To("aservice1-rule"), - InboundNatRulePropertiesFormat: &network.InboundNatRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + Properties: &armnetwork.InboundNatRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("fip")}, FrontendPort: ptr.To(int32(80)), - Protocol: network.TransportProtocol(v1.ProtocolTCP), + Protocol: to.Ptr(armnetwork.TransportProtocolTCP), }, }, }, @@ -5904,17 +5896,17 @@ func TestCheckLoadBalancerResourcesConflicted(t *testing.T) { desc: "checkLoadBalancerResourcesConflicts should report the conflict error if " + "there is a conflicted inbound NAT pool", fipID: "fip", - existingLB: &network.LoadBalancer{ + existingLB: &armnetwork.LoadBalancer{ Name: ptr.To("lb"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - InboundNatPools: &[]network.InboundNatPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + InboundNatPools: []*armnetwork.InboundNatPool{ { Name: ptr.To("aservice1-rule"), - InboundNatPoolPropertiesFormat: &network.InboundNatPoolPropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + Properties: &armnetwork.InboundNatPoolPropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("fip")}, FrontendPortRangeStart: ptr.To(int32(80)), FrontendPortRangeEnd: ptr.To(int32(90)), - Protocol: network.TransportProtocol(v1.ProtocolTCP), + Protocol: to.Ptr(armnetwork.TransportProtocolTCP), }, }, }, @@ -5926,37 +5918,37 @@ func TestCheckLoadBalancerResourcesConflicted(t *testing.T) { desc: "checkLoadBalancerResourcesConflicts should not report the conflict error if there " + "is no conflicted loadBalancer resources", fipID: "fip", - existingLB: &network.LoadBalancer{ + existingLB: &armnetwork.LoadBalancer{ Name: ptr.To("lb"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ { Name: ptr.To("aservice2-rule"), - LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + Properties: &armnetwork.LoadBalancingRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("fip")}, FrontendPort: ptr.To(int32(90)), - Protocol: network.TransportProtocol(v1.ProtocolTCP), + Protocol: to.Ptr(armnetwork.TransportProtocolTCP), }, }, }, - InboundNatRules: &[]network.InboundNatRule{ + InboundNatRules: []*armnetwork.InboundNatRule{ { Name: ptr.To("aservice1-rule"), - InboundNatRulePropertiesFormat: &network.InboundNatRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + Properties: &armnetwork.InboundNatRulePropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("fip")}, FrontendPort: ptr.To(int32(90)), - Protocol: network.TransportProtocol(v1.ProtocolTCP), + Protocol: to.Ptr(armnetwork.TransportProtocolTCP), }, }, }, - InboundNatPools: &[]network.InboundNatPool{ + InboundNatPools: []*armnetwork.InboundNatPool{ { Name: ptr.To("aservice1-rule"), - InboundNatPoolPropertiesFormat: &network.InboundNatPoolPropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + Properties: &armnetwork.InboundNatPoolPropertiesFormat{ + FrontendIPConfiguration: &armnetwork.SubResource{ID: ptr.To("fip")}, FrontendPortRangeStart: ptr.To(int32(800)), FrontendPortRangeEnd: ptr.To(int32(900)), - Protocol: network.TransportProtocol(v1.ProtocolTCP), + Protocol: to.Ptr(armnetwork.TransportProtocolTCP), }, }, }, @@ -5973,15 +5965,15 @@ func TestCheckLoadBalancerResourcesConflicted(t *testing.T) { } } -func buildLBWithVMIPs(clusterName string, vmIPs []string) *network.LoadBalancer { - lb := network.LoadBalancer{ +func buildLBWithVMIPs(clusterName string, vmIPs []string) *armnetwork.LoadBalancer { + lb := armnetwork.LoadBalancer{ Name: ptr.To(clusterName), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To(clusterName), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{}, + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{}, }, }, }, @@ -5990,10 +5982,10 @@ func buildLBWithVMIPs(clusterName string, vmIPs []string) *network.LoadBalancer for _, vmIP := range vmIPs { vmIP := vmIP - *(*lb.BackendAddressPools)[0].LoadBalancerBackendAddresses = append(*(*lb.BackendAddressPools)[0].LoadBalancerBackendAddresses, network.LoadBalancerBackendAddress{ - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + (lb.Properties.BackendAddressPools)[0].Properties.LoadBalancerBackendAddresses = append(lb.Properties.BackendAddressPools[0].Properties.LoadBalancerBackendAddresses, &armnetwork.LoadBalancerBackendAddress{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: &vmIP, - VirtualNetwork: &network.SubResource{ + VirtualNetwork: &armnetwork.SubResource{ ID: ptr.To("vnet"), }, }, @@ -6003,25 +5995,25 @@ func buildLBWithVMIPs(clusterName string, vmIPs []string) *network.LoadBalancer return &lb } -func buildDefaultTestLB(name string, backendIPConfigs []string) network.LoadBalancer { - expectedLB := network.LoadBalancer{ +func buildDefaultTestLB(name string, backendIPConfigs []string) armnetwork.LoadBalancer { + expectedLB := armnetwork.LoadBalancer{ Name: ptr.To(name), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To(name), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &[]network.InterfaceIPConfiguration{}, + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: []*armnetwork.InterfaceIPConfiguration{}, }, }, }, }, } - backendIPConfigurations := make([]network.InterfaceIPConfiguration, 0) + backendIPConfigurations := make([]*armnetwork.InterfaceIPConfiguration, 0) for _, ipConfig := range backendIPConfigs { - backendIPConfigurations = append(backendIPConfigurations, network.InterfaceIPConfiguration{ID: ptr.To(ipConfig)}) + backendIPConfigurations = append(backendIPConfigurations, &armnetwork.InterfaceIPConfiguration{ID: ptr.To(ipConfig)}) } - (*expectedLB.BackendAddressPools)[0].BackendIPConfigurations = &backendIPConfigurations + (expectedLB.Properties.BackendAddressPools)[0].Properties.BackendIPConfigurations = backendIPConfigurations return expectedLB } @@ -6039,7 +6031,7 @@ func TestEnsurePIPTagged(t *testing.T) { }, }, } - pip := network.PublicIPAddress{ + pip := armnetwork.PublicIPAddress{ Tags: map[string]*string{ consts.ClusterNameKey: ptr.To("testCluster"), consts.ServiceTagKey: ptr.To("default/svc1,default/svc2"), @@ -6051,7 +6043,7 @@ func TestEnsurePIPTagged(t *testing.T) { } t.Run("ensurePIPTagged should ensure the pip is tagged as configured", func(t *testing.T) { - expectedPIP := network.PublicIPAddress{ + expectedPIP := armnetwork.PublicIPAddress{ Tags: map[string]*string{ consts.ClusterNameKey: ptr.To("testCluster"), consts.ServiceTagKey: ptr.To("default/svc1,default/svc2"), @@ -6071,7 +6063,7 @@ func TestEnsurePIPTagged(t *testing.T) { t.Run("ensurePIPTagged should delete the old tags if the SystemTags is set", func(t *testing.T) { cloud.SystemTags = "a,foo" - expectedPIP := network.PublicIPAddress{ + expectedPIP := armnetwork.PublicIPAddress{ Tags: map[string]*string{ consts.ClusterNameKey: ptr.To("testCluster"), consts.ServiceTagKey: ptr.To("default/svc1,default/svc2"), @@ -6091,7 +6083,7 @@ func TestEnsurePIPTagged(t *testing.T) { t.Run("ensurePIPTagged should support TagsMap", func(t *testing.T) { cloud.SystemTags = "a,foo" cloud.TagsMap = map[string]string{"a": "c", "a=b": "c=d", "Y": "zz"} - expectedPIP := network.PublicIPAddress{ + expectedPIP := armnetwork.PublicIPAddress{ Tags: map[string]*string{ consts.ClusterNameKey: ptr.To("testCluster"), consts.ServiceTagKey: ptr.To("default/svc1,default/svc2"), @@ -6139,7 +6131,7 @@ func TestEnsureLoadBalancerTagged(t *testing.T) { cloud := GetTestCloud(ctrl) cloud.Tags = tc.newTags cloud.SystemTags = tc.systemTags - lb := &network.LoadBalancer{Tags: tc.existedTags} + lb := &armnetwork.LoadBalancer{Tags: tc.existedTags} changed := cloud.ensureLoadBalancerTagged(lb) assert.Equal(t, tc.expectedChanged, changed) @@ -6152,136 +6144,137 @@ func TestRemoveFrontendIPConfigurationFromLoadBalancerDelete(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() t.Run("removeFrontendIPConfigurationFromLoadBalancer should remove the unwanted frontend IP configuration and delete the orphaned LB", func(t *testing.T) { - fip := &network.FrontendIPConfiguration{ + fip := &armnetwork.FrontendIPConfiguration{ Name: ptr.To("testCluster"), ID: ptr.To("testCluster-fip"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("pipID"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, - PrivateIPAddressVersion: network.IPv4, + PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, } service := getTestService("svc1", v1.ProtocolTCP, nil, false, 80) lb := getTestLoadBalancer(ptr.To("lb"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("testCluster"), service, "standard") bid := "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-0/ipConfigurations/ipconfig1" - lb.BackendAddressPools = &[]network.BackendAddressPool{ + lb.Properties.BackendAddressPools = []*armnetwork.BackendAddressPool{ { Name: ptr.To("testCluster"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: []*armnetwork.InterfaceIPConfiguration{ {ID: ptr.To(bid)}, }, }, }, } cloud := GetTestCloud(ctrl) - mockLBClient := cloud.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) + mockLBClient := cloud.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) mockLBClient.EXPECT().Delete(gomock.Any(), "rg", "lb").Return(nil) mockPLSRepo := cloud.plsRepo.(*privatelinkservice.MockRepository) mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil) - existingLBs := []network.LoadBalancer{{Name: ptr.To("lb")}} - _, err := cloud.removeFrontendIPConfigurationFromLoadBalancer(context.TODO(), &lb, &existingLBs, []*network.FrontendIPConfiguration{fip}, "testCluster", &service) + existingLBs := []*armnetwork.LoadBalancer{{Name: ptr.To("lb")}} + _, err := cloud.removeFrontendIPConfigurationFromLoadBalancer(context.TODO(), lb, existingLBs, []*armnetwork.FrontendIPConfiguration{fip}, "testCluster", &service) assert.NoError(t, err) }) } func TestRemoveFrontendIPConfigurationFromLoadBalancerUpdate(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() + t.Run("removeFrontendIPConfigurationFromLoadBalancer should remove the unwanted frontend IP configuration and update the LB if there are remaining frontend IP configurations", func(t *testing.T) { - fip := &network.FrontendIPConfiguration{ + ctrl := gomock.NewController(t) + defer ctrl.Finish() + cloud := GetTestCloud(ctrl) + fip := &armnetwork.FrontendIPConfiguration{ Name: ptr.To("testCluster"), ID: ptr.To("testCluster-fip"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("pipID"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, - PrivateIPAddressVersion: network.IPv4, + PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, } service := getTestService("svc1", v1.ProtocolTCP, nil, false, 80) lb := getTestLoadBalancer(ptr.To("lb"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("testCluster"), service, "standard") - *lb.FrontendIPConfigurations = append(*lb.FrontendIPConfigurations, network.FrontendIPConfiguration{Name: ptr.To("fip1")}) - cloud := GetTestCloud(ctrl) - mockLBClient := cloud.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) - mockLBClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", "lb", gomock.Any(), gomock.Any()).Return(nil) + lb.Properties.FrontendIPConfigurations = append(lb.Properties.FrontendIPConfigurations, &armnetwork.FrontendIPConfiguration{Name: ptr.To("fip1")}) + mockLBClient := cloud.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", "lb", gomock.Any()).Return(nil, nil) mockPLSRepo := cloud.plsRepo.(*privatelinkservice.MockRepository) mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil) - _, err := cloud.removeFrontendIPConfigurationFromLoadBalancer(context.TODO(), &lb, &[]network.LoadBalancer{}, []*network.FrontendIPConfiguration{fip}, "testCluster", &service) + _, err := cloud.removeFrontendIPConfigurationFromLoadBalancer(context.TODO(), lb, []*armnetwork.LoadBalancer{}, []*armnetwork.FrontendIPConfiguration{fip}, "testCluster", &service) assert.NoError(t, err) }) } func TestCleanOrphanedLoadBalancerLBInUseByVMSS(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() t.Run("cleanOrphanedLoadBalancer should retry deleting lb when meeting LoadBalancerInUseByVirtualMachineScaleSet", func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() cloud := GetTestCloud(ctrl) vmss, err := newScaleSet(cloud) assert.NoError(t, err) cloud.VMSet = vmss - cloud.LoadBalancerSku = consts.LoadBalancerSkuStandard + cloud.LoadBalancerSKU = consts.LoadBalancerSKUStandard - mockLBClient := cloud.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) - mockLBClient.EXPECT().Delete(gomock.Any(), "rg", "test").Return(&retry.Error{RawError: errors.New(LBInUseRawError)}) + mockLBClient := cloud.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBClient.EXPECT().Delete(gomock.Any(), "rg", "test").Return(&azcore.ResponseError{ErrorCode: LBInUseRawError}) mockLBClient.EXPECT().Delete(gomock.Any(), "rg", "test").Return(nil) expectedVMSS := buildTestVMSSWithLB(testVMSSName, "vmss-vm-", []string{testLBBackendpoolID0}, false) - mockVMSSClient := cloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), "rg").Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil) - mockVMSSClient.EXPECT().Get(gomock.Any(), "rg", testVMSSName).Return(expectedVMSS, nil) - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", testVMSSName, gomock.Any()).Return(nil) + mockVMSSClient := cloud.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), "rg").Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil) + mockVMSSClient.EXPECT().Get(gomock.Any(), "rg", testVMSSName, gomock.Any()).Return(expectedVMSS, nil) + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", testVMSSName, gomock.Any()).Return(nil, nil) service := getTestService("test", v1.ProtocolTCP, nil, false, 80) - lb := getTestLoadBalancer(ptr.To("test"), ptr.To("rg"), ptr.To("test"), ptr.To("test"), service, consts.LoadBalancerSkuStandard) - (*lb.BackendAddressPools)[0].ID = ptr.To(testLBBackendpoolID0) + lb := getTestLoadBalancer(ptr.To("test"), ptr.To("rg"), ptr.To("test"), ptr.To("test"), service, consts.LoadBalancerSKUStandard) + (lb.Properties.BackendAddressPools)[0].ID = ptr.To(testLBBackendpoolID0) - existingLBs := []network.LoadBalancer{{Name: ptr.To("test")}} + existingLBs := []*armnetwork.LoadBalancer{{Name: ptr.To("test")}} - err = cloud.cleanOrphanedLoadBalancer(context.TODO(), &lb, existingLBs, &service, "test") + err = cloud.cleanOrphanedLoadBalancer(context.TODO(), lb, existingLBs, &service, "test") assert.NoError(t, err) }) t.Run("cleanupOrphanedLoadBalancer should not call delete api if the lb does not exist", func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() cloud := GetTestCloud(ctrl) vmss, err := newScaleSet(cloud) assert.NoError(t, err) cloud.VMSet = vmss - cloud.LoadBalancerSku = consts.LoadBalancerSkuStandard + cloud.LoadBalancerSKU = consts.LoadBalancerSKUStandard service := getTestService("test", v1.ProtocolTCP, nil, false, 80) - lb := getTestLoadBalancer(ptr.To("test"), ptr.To("rg"), ptr.To("test"), ptr.To("test"), service, consts.LoadBalancerSkuStandard) - (*lb.BackendAddressPools)[0].ID = ptr.To(testLBBackendpoolID0) + lb := getTestLoadBalancer(ptr.To("test"), ptr.To("rg"), ptr.To("test"), ptr.To("test"), service, consts.LoadBalancerSKUStandard) + (lb.Properties.BackendAddressPools)[0].ID = ptr.To(testLBBackendpoolID0) - existingLBs := []network.LoadBalancer{} + existingLBs := []*armnetwork.LoadBalancer{} - err = cloud.cleanOrphanedLoadBalancer(context.TODO(), &lb, existingLBs, &service, "test") + err = cloud.cleanOrphanedLoadBalancer(context.TODO(), lb, existingLBs, &service, "test") assert.NoError(t, err) }) } func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() for _, tc := range []struct { description string service v1.Service - existingFrontendIPConfigs []network.FrontendIPConfiguration - existingPIPV4 network.PublicIPAddress - existingPIPV6 network.PublicIPAddress + existingFrontendIPConfigs []*armnetwork.FrontendIPConfiguration + existingPIPV4 *armnetwork.PublicIPAddress + existingPIPV6 *armnetwork.PublicIPAddress status *v1.LoadBalancerStatus getZoneError error regionZonesMap map[string][]string - expectedZones *[]string + expectedZones []*string expectedDirty bool expectedIPv4 *string expectedIPv6 *string @@ -6290,20 +6283,20 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { { description: "reconcileFrontendIPConfigs should reconcile the zones for the new fip config", service: getTestServiceDualStack("test", v1.ProtocolTCP, nil, 80), - existingFrontendIPConfigs: []network.FrontendIPConfiguration{}, - existingPIPV4: network.PublicIPAddress{Name: ptr.To("testCluster-atest"), Location: ptr.To("eastus")}, - existingPIPV6: network.PublicIPAddress{Name: ptr.To("testCluster-atest-IPv6"), Location: ptr.To("eastus")}, + existingFrontendIPConfigs: []*armnetwork.FrontendIPConfiguration{}, + existingPIPV4: &armnetwork.PublicIPAddress{Name: ptr.To("testCluster-atest"), Location: ptr.To("eastus")}, + existingPIPV6: &armnetwork.PublicIPAddress{Name: ptr.To("testCluster-atest-IPv6"), Location: ptr.To("eastus")}, regionZonesMap: map[string][]string{"westus": {"1", "2", "3"}, "eastus": {"1", "2"}}, expectedDirty: true, }, { description: "reconcileFrontendIPConfigs should reconcile the zones for the new internal fip config", service: getInternalTestServiceDualStack("test", 80), - existingFrontendIPConfigs: []network.FrontendIPConfiguration{}, - existingPIPV4: network.PublicIPAddress{Name: ptr.To("testCluster-atest"), Location: ptr.To("eastus")}, - existingPIPV6: network.PublicIPAddress{Name: ptr.To("testCluster-atest-IPv6"), Location: ptr.To("eastus")}, + existingFrontendIPConfigs: []*armnetwork.FrontendIPConfiguration{}, + existingPIPV4: &armnetwork.PublicIPAddress{Name: ptr.To("testCluster-atest"), Location: ptr.To("eastus")}, + existingPIPV6: &armnetwork.PublicIPAddress{Name: ptr.To("testCluster-atest-IPv6"), Location: ptr.To("eastus")}, regionZonesMap: map[string][]string{"westus": {"1", "2", "3"}, "eastus": {"1", "2"}}, - expectedZones: &[]string{"1", "2", "3"}, + expectedZones: to.SliceOfPtrs("1", "2", "3"), expectedDirty: true, }, { @@ -6318,11 +6311,11 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { consts.ServiceAnnotationLoadBalancerInternalSubnet: "subnet", consts.ServiceAnnotationLoadBalancerInternal: consts.TrueAnnotationValue, }, true, 80), - existingFrontendIPConfigs: []network.FrontendIPConfiguration{ + existingFrontendIPConfigs: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("atest1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - Subnet: &network.Subnet{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + Subnet: &armnetwork.Subnet{ Name: ptr.To("subnet-1"), }, }, @@ -6336,27 +6329,27 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { consts.ServiceAnnotationLoadBalancerInternalSubnet: "subnet", consts.ServiceAnnotationLoadBalancerInternal: consts.TrueAnnotationValue, }, true, 80), - existingFrontendIPConfigs: []network.FrontendIPConfiguration{ + existingFrontendIPConfigs: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("not-this-one"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - Subnet: &network.Subnet{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + Subnet: &armnetwork.Subnet{ Name: ptr.To("subnet-1"), }, }, - Zones: &[]string{"2"}, + Zones: to.SliceOfPtrs("2"), }, { Name: ptr.To("atest1"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - Subnet: &network.Subnet{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + Subnet: &armnetwork.Subnet{ Name: ptr.To("subnet-1"), }, }, - Zones: &[]string{"1"}, + Zones: to.SliceOfPtrs("1"), }, }, - expectedZones: &[]string{"1"}, + expectedZones: to.SliceOfPtrs("1"), expectedDirty: true, }, { @@ -6387,28 +6380,29 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { }, } { t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() cloud := GetTestCloud(ctrl) cloud.regionZonesMap = tc.regionZonesMap - cloud.LoadBalancerSku = string(network.LoadBalancerSkuNameStandard) + cloud.LoadBalancerSKU = string(armnetwork.LoadBalancerSKUNameStandard) lb := getTestLoadBalancer(ptr.To("lb"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("testCluster"), tc.service, "standard") existingFrontendIPConfigs := tc.existingFrontendIPConfigs - lb.FrontendIPConfigurations = &existingFrontendIPConfigs + lb.Properties.FrontendIPConfigurations = existingFrontendIPConfigs - mockPIPClient := cloud.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) - firstV4 := mockPIPClient.EXPECT().List(gomock.Any(), "rg").Return([]network.PublicIPAddress{}, nil).MaxTimes(2) - firstV6 := mockPIPClient.EXPECT().List(gomock.Any(), "rg").Return([]network.PublicIPAddress{}, nil).MaxTimes(2) + mockPIPClient := cloud.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + firstV4 := mockPIPClient.EXPECT().List(gomock.Any(), "rg").Return([]*armnetwork.PublicIPAddress{}, nil).MaxTimes(2) + firstV6 := mockPIPClient.EXPECT().List(gomock.Any(), "rg").Return([]*armnetwork.PublicIPAddress{}, nil).MaxTimes(2) mockPIPClient.EXPECT().Get(gomock.Any(), "rg", gomock.Any(), gomock.Any()).Return(tc.existingPIPV4, nil).MaxTimes(1).After(firstV4) mockPIPClient.EXPECT().Get(gomock.Any(), "rg", gomock.Any(), gomock.Any()).Return(tc.existingPIPV6, nil).MaxTimes(1).After(firstV6) - mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", gomock.Any(), gomock.Any()).Return(nil).MaxTimes(2) + mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", gomock.Any(), gomock.Any()).Return(nil, nil).MaxTimes(2) - subnetClient := cloud.SubnetsClient.(*mocksubnetclient.MockInterface) - subnetClient.EXPECT().Get(gomock.Any(), "rg", "vnet", "subnet", gomock.Any()).Return( - network.Subnet{ID: ptr.To("subnet0"), SubnetPropertiesFormat: &network.SubnetPropertiesFormat{AddressPrefixes: &[]string{"1.2.3.4/31", "2001::1/127"}}}, nil).MaxTimes(1) + subnetClient := cloud.subnetRepo.(*subnet.MockRepository) + subnetClient.EXPECT().Get(gomock.Any(), "rg", "vnet", "subnet").Return( + &armnetwork.Subnet{ID: ptr.To("subnet0"), Properties: &armnetwork.SubnetPropertiesFormat{AddressPrefixes: to.SliceOfPtrs("1.2.3.4/31", "2001::1/127")}}, nil).MaxTimes(1) - zoneMock := zone.NewMockRepository(ctrl) + zoneMock := cloud.zoneRepo.(*zone.MockRepository) zoneMock.EXPECT().ListZones(gomock.Any()).Return(map[string][]string{}, tc.getZoneError).MaxTimes(2) - cloud.zoneRepo = zoneMock service := tc.service isDualStack := isServiceDualStack(&service) @@ -6417,7 +6411,7 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { consts.IPVersionIPv4: getResourceByIPFamily(defaultLBFrontendIPConfigName, isDualStack, consts.IPVersionIPv4), consts.IPVersionIPv6: getResourceByIPFamily(defaultLBFrontendIPConfigName, isDualStack, consts.IPVersionIPv6), } - _, _, dirty, err := cloud.reconcileFrontendIPConfigs(context.TODO(), "testCluster", &service, &lb, tc.status, true, lbFrontendIPConfigNames) + _, _, dirty, err := cloud.reconcileFrontendIPConfigs(context.TODO(), "testCluster", &service, lb, tc.status, true, lbFrontendIPConfigNames) if tc.expectedErr == nil { assert.NoError(t, err) } else { @@ -6425,7 +6419,7 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { } assert.Equal(t, tc.expectedDirty, dirty) - for _, fip := range *lb.FrontendIPConfigurations { + for _, fip := range lb.Properties.FrontendIPConfigurations { if strings.EqualFold(ptr.Deref(fip.Name, ""), defaultLBFrontendIPConfigName) { assert.Equal(t, tc.expectedZones, fip.Zones) } @@ -6433,13 +6427,13 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { checkExpectedIP := func(isIPv6 bool, expectedIP *string) { if expectedIP != nil { - for _, fip := range *lb.FrontendIPConfigurations { + for _, fip := range lb.Properties.FrontendIPConfigurations { if strings.EqualFold(ptr.Deref(fip.Name, ""), lbFrontendIPConfigNames[isIPv6]) { - assert.Equal(t, *expectedIP, ptr.Deref(fip.PrivateIPAddress, "")) + assert.Equal(t, *expectedIP, ptr.Deref(fip.Properties.PrivateIPAddress, "")) if *expectedIP != "" { - assert.Equal(t, network.Static, (*lb.FrontendIPConfigurations)[0].PrivateIPAllocationMethod) + assert.Equal(t, to.Ptr(armnetwork.IPAllocationMethodStatic), (lb.Properties.FrontendIPConfigurations)[0].Properties.PrivateIPAllocationMethod) } else { - assert.Equal(t, network.Dynamic, (*lb.FrontendIPConfigurations)[0].PrivateIPAllocationMethod) + assert.Equal(t, to.Ptr(armnetwork.IPAllocationMethodDynamic), (lb.Properties.FrontendIPConfigurations)[0].Properties.PrivateIPAllocationMethod) } } } @@ -6458,25 +6452,25 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { testcases := []struct { desc string service v1.Service - existingFIPs []network.FrontendIPConfiguration - existingPIPs []network.PublicIPAddress + existingFIPs []*armnetwork.FrontendIPConfiguration + existingPIPs []*armnetwork.PublicIPAddress status *v1.LoadBalancerStatus wantLB bool expectedDirty bool - expectedFIPs []network.FrontendIPConfiguration + expectedFIPs []*armnetwork.FrontendIPConfiguration expectedErr error }{ { desc: "DualStack Service reconciles existing FIPs and does not touch others, not dirty", service: getTestServiceDualStack("test", v1.ProtocolTCP, nil, 80), - existingFIPs: []network.FrontendIPConfiguration{ + existingFIPs: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("fipV4"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ Name: ptr.To("pipV4"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, @@ -6484,11 +6478,11 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { }, { Name: ptr.To("fipV6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ Name: ptr.To("pipV6"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), IPAddress: ptr.To("fe::1"), }, }, @@ -6497,8 +6491,8 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { { Name: ptr.To("atest"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("testCluster-atest-id"), }, }, @@ -6506,43 +6500,43 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { { Name: ptr.To("atest-IPv6"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("testCluster-atest-id-IPv6"), }, }, }, }, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("testCluster-atest"), ID: ptr.To("testCluster-atest-id"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, - PublicIPAllocationMethod: network.Static, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), IPAddress: ptr.To("1.2.3.5"), }, }, { Name: ptr.To("testCluster-atest-IPv6"), ID: ptr.To("testCluster-atest-id-IPv6"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Static, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), IPAddress: ptr.To("fe::2"), }, }, { Name: ptr.To("pipV4"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, { Name: ptr.To("pipV6"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), IPAddress: ptr.To("fe::1"), }, }, @@ -6550,14 +6544,14 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { status: nil, wantLB: true, expectedDirty: false, - expectedFIPs: []network.FrontendIPConfiguration{ + expectedFIPs: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("fipV4"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ Name: ptr.To("pipV4"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, @@ -6565,11 +6559,11 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { }, { Name: ptr.To("fipV6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ Name: ptr.To("pipV6"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), IPAddress: ptr.To("fe::1"), }, }, @@ -6578,8 +6572,8 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { { Name: ptr.To("atest"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("testCluster-atest-id"), }, }, @@ -6587,8 +6581,8 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { { Name: ptr.To("atest-IPv6"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("testCluster-atest-id-IPv6"), }, }, @@ -6598,11 +6592,11 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { { desc: "DualStack Service reconciles existing FIPs, wantLB == false, but an FIP ID is empty, should return error", service: getTestServiceDualStack("test", v1.ProtocolTCP, nil, 80), - existingFIPs: []network.FrontendIPConfiguration{ + existingFIPs: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("atest"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("testCluster-atest-id"), }, }, @@ -6610,8 +6604,8 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { { Name: ptr.To("atest-IPv6"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("testCluster-atest-id-IPv6"), }, }, @@ -6624,34 +6618,34 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { { desc: "IPv6 Service with existing IPv4 FIP", service: getTestService("test", v1.ProtocolTCP, nil, true, 80), - existingFIPs: []network.FrontendIPConfiguration{ + existingFIPs: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("fipV4"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ Name: ptr.To("pipV4"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, }, }, }, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("testCluster-atest"), ID: ptr.To("testCluster-atest-id"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Static, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), IPAddress: ptr.To("fe::1"), }, }, { Name: ptr.To("pipV4"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, @@ -6659,14 +6653,14 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { status: nil, wantLB: true, expectedDirty: true, - expectedFIPs: []network.FrontendIPConfiguration{ + expectedFIPs: []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To("fipV4"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ Name: ptr.To("pipV4"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("1.2.3.4"), }, }, @@ -6675,8 +6669,8 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { { Name: ptr.To("atest"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("testCluster-atest-id"), }, }, @@ -6688,13 +6682,13 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { for _, tc := range testcases { t.Run(tc.desc, func(t *testing.T) { cloud := GetTestCloud(ctrl) - cloud.LoadBalancerSku = string(network.LoadBalancerSkuNameStandard) + cloud.LoadBalancerSKU = string(armnetwork.LoadBalancerSKUNameStandard) lb := getTestLoadBalancer(ptr.To("lb"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("testCluster"), tc.service, "standard") existingFIPs := tc.existingFIPs - lb.FrontendIPConfigurations = &existingFIPs + lb.Properties.FrontendIPConfigurations = existingFIPs - mockPIPClient := cloud.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) + mockPIPClient := cloud.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) mockPIPClient.EXPECT().List(gomock.Any(), "rg").Return(tc.existingPIPs, nil).MaxTimes(2) for _, pip := range tc.existingPIPs { mockPIPClient.EXPECT().Get(gomock.Any(), "rg", *pip.Name, gomock.Any()).Return(pip, nil).MaxTimes(1) @@ -6707,13 +6701,13 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { false: getResourceByIPFamily(defaultLBFrontendIPConfigName, isDualStack, false), true: getResourceByIPFamily(defaultLBFrontendIPConfigName, isDualStack, true), } - _, _, dirty, err := cloud.reconcileFrontendIPConfigs(context.TODO(), "testCluster", &service, &lb, tc.status, tc.wantLB, lbFrontendIPConfigNames) + _, _, dirty, err := cloud.reconcileFrontendIPConfigs(context.TODO(), "testCluster", &service, lb, tc.status, tc.wantLB, lbFrontendIPConfigNames) if tc.expectedErr != nil { assert.Equal(t, tc.expectedErr, err) } else { assert.Nil(t, err) assert.Equal(t, tc.expectedDirty, dirty) - assert.Equal(t, tc.expectedFIPs, *lb.FrontendIPConfigurations) + assert.Equal(t, tc.expectedFIPs, lb.Properties.FrontendIPConfigurations) } }) } @@ -6725,87 +6719,87 @@ func TestReconcileIPSettings(t *testing.T) { testcases := []struct { desc string - sku string - pip *network.PublicIPAddress + SKU string + pip *armnetwork.PublicIPAddress service v1.Service isIPv6 bool expectedChanged bool - expectedIPVersion network.IPVersion - expectedAllocationMethod network.IPAllocationMethod + expectedIPVersion armnetwork.IPVersion + expectedAllocationMethod armnetwork.IPAllocationMethod }{ { desc: "correct IPv4 PIP", - sku: consts.LoadBalancerSkuStandard, - pip: &network.PublicIPAddress{ - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, - PublicIPAllocationMethod: network.Static, + SKU: consts.LoadBalancerSKUStandard, + pip: &armnetwork.PublicIPAddress{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), }, }, service: getTestService("test", v1.ProtocolTCP, nil, false, 80), isIPv6: false, expectedChanged: false, - expectedIPVersion: network.IPv4, - expectedAllocationMethod: network.Static, + expectedIPVersion: armnetwork.IPVersionIPv4, + expectedAllocationMethod: armnetwork.IPAllocationMethodStatic, }, { desc: "IPv4 PIP but IP version is IPv6", - sku: consts.LoadBalancerSkuStandard, - pip: &network.PublicIPAddress{ - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Static, + SKU: consts.LoadBalancerSKUStandard, + pip: &armnetwork.PublicIPAddress{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), }, }, service: getTestService("test", v1.ProtocolTCP, nil, false, 80), isIPv6: false, expectedChanged: true, - expectedIPVersion: network.IPv4, - expectedAllocationMethod: network.Static, + expectedIPVersion: armnetwork.IPVersionIPv4, + expectedAllocationMethod: armnetwork.IPAllocationMethodStatic, }, { - desc: "IPv6 PIP but allocation method is dynamic with standard sku", - sku: consts.LoadBalancerSkuStandard, - pip: &network.PublicIPAddress{ - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Dynamic, + desc: "IPv6 PIP but allocation method is dynamic with standard SKU", + SKU: consts.LoadBalancerSKUStandard, + pip: &armnetwork.PublicIPAddress{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), }, }, service: getTestService("test", v1.ProtocolTCP, nil, true, 80), isIPv6: true, expectedChanged: true, - expectedIPVersion: network.IPv6, - expectedAllocationMethod: network.Static, + expectedIPVersion: armnetwork.IPVersionIPv6, + expectedAllocationMethod: armnetwork.IPAllocationMethodStatic, }, { - desc: "IPv6 PIP but allocation method is static with basic sku", - sku: consts.LoadBalancerSkuBasic, - pip: &network.PublicIPAddress{ - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, - PublicIPAllocationMethod: network.Static, + desc: "IPv6 PIP but allocation method is static with basic SKU", + SKU: consts.LoadBalancerSKUBasic, + pip: &armnetwork.PublicIPAddress{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), }, }, service: getTestService("test", v1.ProtocolTCP, nil, true, 80), isIPv6: true, expectedChanged: true, - expectedIPVersion: network.IPv6, - expectedAllocationMethod: network.Dynamic, + expectedIPVersion: armnetwork.IPVersionIPv6, + expectedAllocationMethod: armnetwork.IPAllocationMethodDynamic, }, } for _, tc := range testcases { t.Run(tc.desc, func(t *testing.T) { az := GetTestCloud(ctrl) - az.LoadBalancerSku = tc.sku + az.LoadBalancerSKU = tc.SKU pip := tc.pip pip.Name = ptr.To("pip") service := tc.service changed := az.reconcileIPSettings(pip, &service, tc.isIPv6) assert.Equal(t, tc.expectedChanged, changed) - assert.NotNil(t, pip.PublicIPAddressPropertiesFormat) - assert.Equal(t, pip.PublicIPAddressPropertiesFormat.PublicIPAddressVersion, tc.expectedIPVersion) - assert.Equal(t, pip.PublicIPAddressPropertiesFormat.PublicIPAllocationMethod, tc.expectedAllocationMethod) + assert.NotNil(t, pip.Properties) + assert.Equal(t, *pip.Properties.PublicIPAddressVersion, tc.expectedIPVersion) + assert.Equal(t, *pip.Properties.PublicIPAllocationMethod, tc.expectedAllocationMethod) }) } } @@ -6911,7 +6905,7 @@ func TestSafeDeleteLoadBalancer(t *testing.T) { nodesWithCorrectVMSet *utilsets.IgnoreCaseSet expectedMultiSLBConfigs []config.MultipleStandardLoadBalancerConfiguration expectedNodesWithCorrectVMSet *utilsets.IgnoreCaseSet - expectedErr *retry.Error + expectedErr error }{ { desc: "Standard SKU: should delete the load balancer", @@ -6922,10 +6916,7 @@ func TestSafeDeleteLoadBalancer(t *testing.T) { desc: "Standard SKU: should not delete the load balancer if failed to ensure backend pool deleted", expectedDeleteCall: false, expectedDecoupleErr: errors.New("error"), - expectedErr: retry.NewError( - false, - fmt.Errorf("safeDeleteLoadBalancer: failed to EnsureBackendPoolDeleted: %w", errors.New("error")), - ), + expectedErr: fmt.Errorf("safeDeleteLoadBalancer: failed to EnsureBackendPoolDeleted: error"), }, { desc: "should cleanup active nodes when using multi-slb", @@ -6965,7 +6956,7 @@ func TestSafeDeleteLoadBalancer(t *testing.T) { for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { - mockLBClient := mockloadbalancerclient.NewMockInterface(ctrl) + mockLBClient := cloud.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) if tc.expectedDeleteCall { mockLBClient.EXPECT().Delete(gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.expectedErr).Times(1) } @@ -6979,7 +6970,7 @@ func TestSafeDeleteLoadBalancer(t *testing.T) { gomock.Any(), ).Return(false, tc.expectedDecoupleErr) cloud.VMSet = mockVMSet - cloud.LoadBalancerClient = mockLBClient + if len(tc.multiSLBConfigs) > 0 { cloud.MultipleStandardLoadBalancerConfigurations = tc.multiSLBConfigs for _, nodeName := range tc.nodesWithCorrectVMSet.UnsortedList() { @@ -6987,14 +6978,16 @@ func TestSafeDeleteLoadBalancer(t *testing.T) { } } svc := getTestService("svc", v1.ProtocolTCP, nil, false, 80) - lb := network.LoadBalancer{ + lb := armnetwork.LoadBalancer{ Name: ptr.To("test"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{}, + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{}, }, } err := cloud.safeDeleteLoadBalancer(context.TODO(), lb, "cluster", "vmss", &svc) - assert.Equal(t, tc.expectedErr, err) + if tc.expectedErr != nil { + assert.Contains(t, err.Error(), tc.expectedErr.Error()) + } if len(tc.multiSLBConfigs) > 0 { assert.Equal(t, tc.expectedMultiSLBConfigs, cloud.MultipleStandardLoadBalancerConfigurations) actualNodesWithCorrectLoadBalancerByPrimaryVMSet := utilsets.NewString() @@ -7011,8 +7004,8 @@ func TestSafeDeleteLoadBalancer(t *testing.T) { func TestEqualSubResource(t *testing.T) { testcases := []struct { desc string - subResource1 *network.SubResource - subResource2 *network.SubResource + subResource1 *armnetwork.SubResource + subResource2 *armnetwork.SubResource expected bool }{ { @@ -7023,14 +7016,14 @@ func TestEqualSubResource(t *testing.T) { }, { desc: "one nil", - subResource1: &network.SubResource{}, + subResource1: &armnetwork.SubResource{}, subResource2: nil, expected: false, }, { desc: "equal", - subResource1: &network.SubResource{ID: ptr.To("id")}, - subResource2: &network.SubResource{ID: ptr.To("id")}, + subResource1: &armnetwork.SubResource{ID: ptr.To("id")}, + subResource2: &armnetwork.SubResource{ID: ptr.To("id")}, expected: true, }, } @@ -7530,9 +7523,9 @@ func TestGetAzureLoadBalancerName(t *testing.T) { for _, c := range cases { t.Run(c.description, func(t *testing.T) { if c.useStandardLB { - az.Config.LoadBalancerSku = consts.LoadBalancerSkuStandard + az.Config.LoadBalancerSKU = consts.LoadBalancerSKUStandard } else { - az.Config.LoadBalancerSku = consts.LoadBalancerSkuBasic + az.Config.LoadBalancerSKU = consts.LoadBalancerSKUBasic } if len(c.multiSLBConfigs) > 0 { @@ -7544,7 +7537,7 @@ func TestGetAzureLoadBalancerName(t *testing.T) { if c.serviceLabel != nil { svc.Labels = c.serviceLabel } - loadbalancerName, err := az.getAzureLoadBalancerName(context.TODO(), &svc, &[]network.LoadBalancer{}, c.clusterName, c.vmSet, c.isInternal) + loadbalancerName, err := az.getAzureLoadBalancerName(context.TODO(), &svc, []*armnetwork.LoadBalancer{}, c.clusterName, c.vmSet, c.isInternal) assert.Equal(t, c.expected, loadbalancerName) if c.expectedErr != nil { assert.EqualError(t, err, c.expectedErr.Error()) @@ -7558,7 +7551,7 @@ func TestGetMostEligibleLBName(t *testing.T) { description string currentLBName string eligibleLBs []string - existingLBs *[]network.LoadBalancer + existingLBs []*armnetwork.LoadBalancer isInternal bool expectedLBName string }{ @@ -7572,11 +7565,11 @@ func TestGetMostEligibleLBName(t *testing.T) { description: "should return eligible LBs with fewest rules", currentLBName: "lb1", eligibleLBs: []string{"lb2", "lb3"}, - existingLBs: &[]network.LoadBalancer{ + existingLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("lb2"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ {}, {}, {}, @@ -7585,8 +7578,8 @@ func TestGetMostEligibleLBName(t *testing.T) { }, { Name: ptr.To("lb3"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ {}, {}, }, @@ -7594,8 +7587,8 @@ func TestGetMostEligibleLBName(t *testing.T) { }, { Name: ptr.To("lb4"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ {}, }, }, @@ -7611,11 +7604,11 @@ func TestGetMostEligibleLBName(t *testing.T) { { description: "should return the first eligible LB that does not exist", eligibleLBs: []string{"lb1", "lb2", "lb3"}, - existingLBs: &[]network.LoadBalancer{ + existingLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("lb3"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{}, + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{}, }, }, }, @@ -7624,25 +7617,25 @@ func TestGetMostEligibleLBName(t *testing.T) { { description: "should respect internal load balancers", eligibleLBs: []string{"lb1", "lb2", "lb3"}, - existingLBs: &[]network.LoadBalancer{ + existingLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("lb1-internal"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ {}, }, }, }, { Name: ptr.To("lb2-internal"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{}, + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{}, }, }, { Name: ptr.To("lb3-internal"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{}, + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{}, }, }, }, @@ -7688,7 +7681,7 @@ func TestReconcileMultipleStandardLoadBalancerConfigurations(t *testing.T) { }, } { az := GetTestCloud(ctrl) - az.LoadBalancerSku = consts.LoadBalancerSkuStandard + az.LoadBalancerSKU = consts.LoadBalancerSKUStandard t.Run(tc.description, func(t *testing.T) { existingSvcs := []v1.Service{ @@ -7732,27 +7725,27 @@ func TestReconcileMultipleStandardLoadBalancerConfigurations(t *testing.T) { lbSvcOnKubernetesRuleName := az.getLoadBalancerRuleName(&existingSvcs[1], v1.ProtocolTCP, 80, false) lbSvcOnLB1RuleName := az.getLoadBalancerRuleName(&existingSvcs[2], v1.ProtocolTCP, 80, false) - existingLBs := []network.LoadBalancer{ + existingLBs := []*armnetwork.LoadBalancer{ { Name: ptr.To("kubernetes-internal"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ {Name: &lbSvcOnKubernetesRuleName}, }, }, }, { Name: ptr.To("lb1"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{ {Name: &lbSvcOnLB1RuleName}, }, }, }, { Name: ptr.To("lb2"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - LoadBalancingRules: &[]network.LoadBalancingRule{}, + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + LoadBalancingRules: []*armnetwork.LoadBalancingRule{}, }, }, } @@ -7769,7 +7762,7 @@ func TestReconcileMultipleStandardLoadBalancerConfigurations(t *testing.T) { } svc := getTestService("test", v1.ProtocolTCP, nil, false) - err := az.reconcileMultipleStandardLoadBalancerConfigurations(context.TODO(), &existingLBs, &svc, "kubernetes", &existingLBs, tc.nodes) + err := az.reconcileMultipleStandardLoadBalancerConfigurations(context.TODO(), existingLBs, &svc, "kubernetes", existingLBs, tc.nodes) assert.Equal(t, err, tc.expectedErr) activeServices := make(map[string]*utilsets.IgnoreCaseSet) @@ -7853,9 +7846,9 @@ func TestGetFrontendIPConfigName(t *testing.T) { for _, c := range cases { t.Run(c.description, func(t *testing.T) { if c.useStandardLB { - az.Config.LoadBalancerSku = consts.LoadBalancerSkuStandard + az.Config.LoadBalancerSKU = consts.LoadBalancerSKUStandard } else { - az.Config.LoadBalancerSku = consts.LoadBalancerSkuBasic + az.Config.LoadBalancerSKU = consts.LoadBalancerSKUBasic } svc.Annotations[consts.ServiceAnnotationLoadBalancerInternalSubnet] = c.subnetName svc.Annotations[consts.ServiceAnnotationLoadBalancerInternal] = strconv.FormatBool(c.isInternal) @@ -7907,9 +7900,9 @@ func TestGetFrontendIPConfigNames(t *testing.T) { c := c t.Run(c.description, func(t *testing.T) { if c.useStandardLB { - az.Config.LoadBalancerSku = consts.LoadBalancerSkuStandard + az.Config.LoadBalancerSKU = consts.LoadBalancerSKUStandard } else { - az.Config.LoadBalancerSku = consts.LoadBalancerSkuBasic + az.Config.LoadBalancerSKU = consts.LoadBalancerSKUBasic } svc.Annotations[consts.ServiceAnnotationLoadBalancerInternalSubnet] = c.subnetName svc.Annotations[consts.ServiceAnnotationLoadBalancerInternal] = strconv.FormatBool(c.isInternal) @@ -7927,17 +7920,17 @@ func TestServiceOwnsFrontendIP(t *testing.T) { testCases := []struct { desc string - existingPIPs []network.PublicIPAddress - fip network.FrontendIPConfiguration + existingPIPs []*armnetwork.PublicIPAddress + fip *armnetwork.FrontendIPConfiguration service *v1.Service isOwned bool isPrimary bool - expectedFIPIPVersion network.IPVersion - listError *retry.Error + expectedFIPIPVersion armnetwork.IPVersion + listError error }{ { desc: "serviceOwnsFrontendIP should detect the primary service", - fip: network.FrontendIPConfiguration{ + fip: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("auid"), }, service: &v1.Service{ @@ -7950,7 +7943,7 @@ func TestServiceOwnsFrontendIP(t *testing.T) { }, { desc: "serviceOwnsFrontendIP should return false if the secondary external service doesn't set it's loadBalancer IP", - fip: network.FrontendIPConfiguration{ + fip: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("auid"), }, service: &v1.Service{ @@ -7962,18 +7955,18 @@ func TestServiceOwnsFrontendIP(t *testing.T) { { desc: "serviceOwnsFrontendIP should report a not found error if there is no public IP " + "found according to the external service's loadBalancer IP but do not return the error", - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { ID: ptr.To("pip"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("4.3.2.1"), }, }, }, - fip: network.FrontendIPConfiguration{ + fip: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("auid"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("pip"), }, }, @@ -7987,19 +7980,19 @@ func TestServiceOwnsFrontendIP(t *testing.T) { }, { desc: "serviceOwnsFrontendIP should return correct FIP IP version", - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { ID: ptr.To("pip"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("4.3.2.1"), - PublicIPAddressVersion: network.IPv4, + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, - fip: network.FrontendIPConfiguration{ + fip: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("auid"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("pip"), }, }, @@ -8010,24 +8003,24 @@ func TestServiceOwnsFrontendIP(t *testing.T) { Annotations: map[string]string{consts.ServiceAnnotationLoadBalancerIPDualStack[false]: "4.3.2.1"}, }, }, - expectedFIPIPVersion: network.IPv4, + expectedFIPIPVersion: armnetwork.IPVersionIPv4, isOwned: true, }, { desc: "serviceOwnsFrontendIP should return false if there is a mismatch between the PIP's ID and " + "the counterpart on the frontend IP config", - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { ID: ptr.To("pip"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("4.3.2.1"), }, }, }, - fip: network.FrontendIPConfiguration{ + fip: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("auid"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("pip1"), }, }, @@ -8041,18 +8034,18 @@ func TestServiceOwnsFrontendIP(t *testing.T) { }, { desc: "serviceOwnsFrontendIP should return false if there is no public IP address in the frontend IP config", - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { ID: ptr.To("pip"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("4.3.2.1"), }, }, }, - fip: network.FrontendIPConfiguration{ + fip: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("auid"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPPrefix: &network.SubResource{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPPrefix: &armnetwork.SubResource{ ID: ptr.To("pip1"), }, }, @@ -8068,18 +8061,18 @@ func TestServiceOwnsFrontendIP(t *testing.T) { }, { desc: "serviceOwnsFrontendIP should detect the secondary external service", - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { ID: ptr.To("pip"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("4.3.2.1"), }, }, }, - fip: network.FrontendIPConfiguration{ + fip: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("auid"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("pip"), }, }, @@ -8097,30 +8090,30 @@ func TestServiceOwnsFrontendIP(t *testing.T) { }, { desc: "serviceOwnsFrontendIP should detect the secondary external service dual-stack", - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip"), ID: ptr.To("pip"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), IPAddress: ptr.To("4.3.2.1"), }, }, { Name: ptr.To("pip1"), ID: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), IPAddress: ptr.To("fd00::eef0"), }, }, }, - fip: network.FrontendIPConfiguration{ + fip: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("auid"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv6, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), }, ID: ptr.To("pip1"), }, @@ -8140,9 +8133,9 @@ func TestServiceOwnsFrontendIP(t *testing.T) { }, { desc: "serviceOwnsFrontendIP should detect the secondary internal service", - fip: network.FrontendIPConfiguration{ + fip: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("auid"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ PrivateIPAddress: ptr.To("4.3.2.1"), }, }, @@ -8159,9 +8152,9 @@ func TestServiceOwnsFrontendIP(t *testing.T) { }, { desc: "serviceOwnsFrontendIP should detect the secondary internal service - dualstack", - fip: network.FrontendIPConfiguration{ + fip: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("auid"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ PrivateIPAddress: ptr.To("fd00::eef0"), }, }, @@ -8180,7 +8173,7 @@ func TestServiceOwnsFrontendIP(t *testing.T) { { desc: "serviceOwnsFrontendIP should return false if failed to find matched pip by name", service: &v1.Service{}, - listError: retry.NewError(false, errors.New("error")), + listError: &azcore.ResponseError{ErrorCode: "error"}, }, { desc: "serviceOwnsFrontnedIP should support search pip by name", @@ -8189,19 +8182,19 @@ func TestServiceOwnsFrontendIP(t *testing.T) { Annotations: map[string]string{consts.ServiceAnnotationPIPNameDualStack[false]: "pip1"}, }, }, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ { Name: ptr.To("pip1"), ID: ptr.To("pip1"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, }, }, - fip: network.FrontendIPConfiguration{ + fip: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("test"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("pip1"), }, }, @@ -8215,12 +8208,12 @@ func TestServiceOwnsFrontendIP(t *testing.T) { t.Run(test.desc, func(t *testing.T) { cloud := GetTestCloud(ctrl) if test.existingPIPs != nil { - mockPIPsClient := cloud.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) + mockPIPsClient := cloud.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) mockPIPsClient.EXPECT().List(gomock.Any(), "rg").Return(test.existingPIPs, test.listError).MaxTimes(2) } isOwned, isPrimary, fipIPVersion := cloud.serviceOwnsFrontendIP(context.TODO(), test.fip, test.service) if test.expectedFIPIPVersion != "" { - assert.Equal(t, test.expectedFIPIPVersion, fipIPVersion) + assert.Equal(t, test.expectedFIPIPVersion, *fipIPVersion) } assert.Equal(t, test.isOwned, isOwned) assert.Equal(t, test.isPrimary, isPrimary) @@ -8238,7 +8231,7 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { init bool existingLBConfigs []config.MultipleStandardLoadBalancerConfiguration existingNodes []*v1.Node - existingLBs []network.LoadBalancer + existingLBs []*armnetwork.LoadBalancer expectedPutLBTimes int expectedLBToNodesMap map[string]*utilsets.IgnoreCaseSet }{ @@ -8269,24 +8262,24 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { getTestNodeWithMetadata("node2", "vmss-2", nil, "10.1.0.2"), getTestNodeWithMetadata("node3", "vmss-2", nil, "10.1.0.3"), }, - existingLBs: []network.LoadBalancer{ + existingLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("lb1-internal"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("kubernetes"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { Name: ptr.To("node1"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.1.0.1"), }, }, { Name: ptr.To("node2"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.1.0.2"), }, }, @@ -8298,21 +8291,21 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { }, { Name: ptr.To("lb2"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("kubernetes"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { Name: ptr.To("node3"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.1.0.3"), }, }, { Name: ptr.To("node4"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.1.0.4"), }, }, @@ -8380,24 +8373,24 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { getTestNodeWithMetadata("node5", "vmss-3", map[string]string{"k2": "v2"}, "10.1.0.5"), getTestNodeWithMetadata("node6", "vmss-3", map[string]string{"k3": "v3"}, "10.1.0.6"), }, - existingLBs: []network.LoadBalancer{ + existingLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("lb1-internal"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("kubernetes"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { Name: ptr.To("node1"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.1.0.1"), }, }, { Name: ptr.To("node2"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.1.0.2"), }, }, @@ -8409,8 +8402,8 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { }, { Name: ptr.To("lb3"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("kubernetes"), }, @@ -8419,8 +8412,8 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { }, { Name: ptr.To("lb4"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("kubernetes"), }, @@ -8492,19 +8485,19 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { Name: "lb4", }, }, - existingLBs: []network.LoadBalancer{ + existingLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("lb2-internal"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ {Name: ptr.To("kubernetes")}, }, }, }, { Name: ptr.To("lb4"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("kubernetes"), }, @@ -8560,11 +8553,11 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { Name: "lb4", }, }, - existingLBs: []network.LoadBalancer{ + existingLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("lb2-internal"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ {Name: ptr.To("kubernetes")}, }, }, @@ -8608,18 +8601,18 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { getTestNodeWithMetadata("node5", "vmss-5", map[string]string{"k2": "v2"}, "10.1.0.5"), getTestNodeWithMetadata("node6", "vmss-6", map[string]string{"k3": "v3"}, "10.1.0.6"), }, - existingLBs: []network.LoadBalancer{ + existingLBs: []*armnetwork.LoadBalancer{ { Name: ptr.To("lb1-internal"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("kubernetes"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { Name: ptr.To("node2"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.1.0.2"), }, }, @@ -8631,27 +8624,27 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { }, { Name: ptr.To("lb2"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("kubernetes"), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{ { Name: ptr.To("node3"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.1.0.3"), }, }, { Name: ptr.To("node4"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.1.0.4"), }, }, { Name: ptr.To("node5"), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.1.0.5"), }, }, @@ -8685,7 +8678,7 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { az.LoadBalancerBackendPool = newBackendPoolTypeNodeIP(az) az.MultipleStandardLoadBalancerConfigurations = tc.existingLBConfigs svc := getTestService("test", v1.ProtocolTCP, nil, false) - _ = az.reconcileMultipleStandardLoadBalancerBackendNodes(context.TODO(), "kubernetes", tc.lbName, &tc.existingLBs, &svc, tc.existingNodes, tc.init) + _ = az.reconcileMultipleStandardLoadBalancerBackendNodes(context.TODO(), "kubernetes", tc.lbName, tc.existingLBs, &svc, tc.existingNodes, tc.init) expectedLBToNodesMap := make(map[string]*utilsets.IgnoreCaseSet) for _, multiSLBConfig := range az.MultipleStandardLoadBalancerConfigurations { @@ -8717,70 +8710,70 @@ func getTestNodeWithMetadata(nodeName, vmssName string, labels map[string]string } func TestAddOrUpdateLBInList(t *testing.T) { - existingLBs := []network.LoadBalancer{ + existingLBs := []*armnetwork.LoadBalancer{ { Name: ptr.To("lb1"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ {Name: ptr.To("kubernetes")}, }, }, }, { Name: ptr.To("lb2"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ {Name: ptr.To("kubernetes")}, }, }, }, } - targetLB := network.LoadBalancer{ + targetLB := &armnetwork.LoadBalancer{ Name: ptr.To("lb1"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ {Name: ptr.To("lb1")}, }, }, } - expectedLBs := []network.LoadBalancer{ + expectedLBs := []*armnetwork.LoadBalancer{ { Name: ptr.To("lb1"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ {Name: ptr.To("lb1")}, }, }, }, { Name: ptr.To("lb2"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ {Name: ptr.To("kubernetes")}, }, }, }, } - addOrUpdateLBInList(&existingLBs, &targetLB) + addOrUpdateLBInList(&existingLBs, targetLB) assert.Equal(t, expectedLBs, existingLBs) - targetLB = network.LoadBalancer{ + targetLB = &armnetwork.LoadBalancer{ Name: ptr.To("lb3"), } - expectedLBs = []network.LoadBalancer{ + expectedLBs = []*armnetwork.LoadBalancer{ { Name: ptr.To("lb1"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ {Name: ptr.To("lb1")}, }, }, }, { Name: ptr.To("lb2"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ {Name: ptr.To("kubernetes")}, }, }, @@ -8788,7 +8781,7 @@ func TestAddOrUpdateLBInList(t *testing.T) { {Name: ptr.To("lb3")}, } - addOrUpdateLBInList(&existingLBs, &targetLB) + addOrUpdateLBInList(&existingLBs, targetLB) assert.Equal(t, expectedLBs, existingLBs) } @@ -8804,25 +8797,25 @@ func TestReconcileBackendPoolHosts(t *testing.T) { bp2 := buildTestLoadBalancerBackendPoolWithIPs(clusterName, ips) ips = []string{"10.0.0.2", "10.0.0.3"} bp3 := buildTestLoadBalancerBackendPoolWithIPs(clusterName, ips) - lb1 := &network.LoadBalancer{ + lb1 := &armnetwork.LoadBalancer{ Name: ptr.To(clusterName), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{bp1}, + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{bp1}, }, } - lb2 := &network.LoadBalancer{ + lb2 := &armnetwork.LoadBalancer{ Name: ptr.To("lb2"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{bp2}, + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{bp2}, }, } - expectedLB := &network.LoadBalancer{ + expectedLB := &armnetwork.LoadBalancer{ Name: ptr.To(clusterName), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{bp3}, + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{bp3}, }, } - existingLBs := []network.LoadBalancer{*lb1, *lb2} + existingLBs := []*armnetwork.LoadBalancer{lb1, lb2} cloud := GetTestCloud(ctrl) mockLBBackendPool := NewMockBackendPool(ctrl) @@ -8840,16 +8833,16 @@ func TestReconcileBackendPoolHosts(t *testing.T) { assert.Equal(t, errors.New("error"), err) } -func fakeEnsureHostsInPool() func(context.Context, *v1.Service, []*v1.Node, string, string, string, string, network.BackendAddressPool) error { - return func(_ context.Context, _ *v1.Service, _ []*v1.Node, _, _, _, _ string, backendPool network.BackendAddressPool) error { - backendPool.LoadBalancerBackendAddresses = &[]network.LoadBalancerBackendAddress{ +func fakeEnsureHostsInPool() func(context.Context, *v1.Service, []*v1.Node, string, string, string, string, *armnetwork.BackendAddressPool) error { + return func(_ context.Context, _ *v1.Service, _ []*v1.Node, _, _, _, _ string, backendPool *armnetwork.BackendAddressPool) error { + backendPool.Properties.LoadBalancerBackendAddresses = []*armnetwork.LoadBalancerBackendAddress{ { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.2"), }, }, { - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To("10.0.0.3"), }, }, diff --git a/pkg/provider/azure_local_services.go b/pkg/provider/azure_local_services.go index 0febc94edb..5abf546c26 100644 --- a/pkg/provider/azure_local_services.go +++ b/pkg/provider/azure_local_services.go @@ -23,8 +23,7 @@ import ( "sync" "time" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" v1 "k8s.io/api/core/v1" discovery_v1 "k8s.io/api/discovery/v1" "k8s.io/apimachinery/pkg/util/sets" @@ -36,7 +35,7 @@ import ( "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" + "sigs.k8s.io/cloud-provider-azure/pkg/util/errutils" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) @@ -198,9 +197,9 @@ func (updater *loadBalancerBackendPoolUpdater) process(ctx context.Context) { parts := strings.Split(key, ":") lbName, poolName := parts[0], parts[1] operationName := fmt.Sprintf("%s/%s", lbName, poolName) - bp, rerr := updater.az.LoadBalancerClient.GetLBBackendPool(ctx, updater.az.ResourceGroup, lbName, poolName, "") - if rerr != nil { - updater.processError(rerr, operationName, ops...) + bp, err := updater.az.NetworkClientFactory.GetBackendAddressPoolClient().Get(ctx, updater.az.ResourceGroup, lbName, poolName) + if err != nil { + updater.processError(err, operationName, ops...) continue } @@ -212,7 +211,7 @@ func (updater *loadBalancerBackendPoolUpdater) process(ctx context.Context) { removed := removeNodeIPAddressesFromBackendPool(bp, lbOp.nodeIPs, false, true, true) changed = changed || removed case consts.LoadBalancerBackendPoolUpdateOperationAdd: - added := updater.az.addNodeIPAddressesToBackendPool(&bp, lbOp.nodeIPs) + added := updater.az.addNodeIPAddressesToBackendPool(bp, lbOp.nodeIPs) changed = changed || added default: panic("loadBalancerBackendPoolUpdater.process: unknown operation type") @@ -222,9 +221,9 @@ func (updater *loadBalancerBackendPoolUpdater) process(ctx context.Context) { // but the backend pool object is not changed after multiple times of removal and re-adding. if changed { klog.V(2).Infof("loadBalancerBackendPoolUpdater.process: updating backend pool %s/%s", lbName, poolName) - rerr = updater.az.LoadBalancerClient.CreateOrUpdateBackendPools(ctx, updater.az.ResourceGroup, lbName, poolName, bp, ptr.Deref(bp.Etag, "")) - if rerr != nil { - updater.processError(rerr, operationName, ops...) + _, err = updater.az.NetworkClientFactory.GetBackendAddressPoolClient().CreateOrUpdate(ctx, updater.az.ResourceGroup, lbName, poolName, *bp) + if err != nil { + updater.processError(err, operationName, ops...) continue } } @@ -235,22 +234,18 @@ func (updater *loadBalancerBackendPoolUpdater) process(ctx context.Context) { // processError mark the operations as retriable if the error is retriable, // and fail all operations if the error is not retriable. func (updater *loadBalancerBackendPoolUpdater) processError( - rerr *retry.Error, + rerr error, operationName string, operations ...batchOperation, ) { - if rerr.IsNotFound() { + if exists, err := errutils.CheckResourceExistsFromAzcoreError(rerr); !exists && err == nil { klog.V(4).Infof("backend pool not found for operation %s, skip updating", operationName) return } - if rerr.Retriable { - // Retry if retriable. - updater.operations = append(updater.operations, operations...) - } else { - // Fail all operations if not retriable. - updater.notify(newBatchOperationResult(operationName, false, rerr.Error()), operations...) - } + // Fail all operations if not retriable. + updater.notify(newBatchOperationResult(operationName, false, rerr), operations...) + } // notify notifies the operations with the result. @@ -496,26 +491,25 @@ func (az *Cloud) cleanupLocalServiceBackendPool( ctx context.Context, svc *v1.Service, nodes []*v1.Node, - lbs *[]network.LoadBalancer, + lbs []*armnetwork.LoadBalancer, clusterName string, -) (newLBs *[]network.LoadBalancer, err error) { +) (newLBs []*armnetwork.LoadBalancer, err error) { var changed bool - if lbs != nil { - for _, lb := range *lbs { - lbName := ptr.Deref(lb.Name, "") - if lb.BackendAddressPools != nil { - for _, bp := range *lb.BackendAddressPools { - bpName := ptr.Deref(bp.Name, "") - if localServiceOwnsBackendPool(getServiceName(svc), bpName) { - if err := az.DeleteLBBackendPool(ctx, lbName, bpName); err != nil { - return nil, err - } - changed = true + for _, lb := range lbs { + lbName := ptr.Deref(lb.Name, "") + if lb.Properties.BackendAddressPools != nil { + for _, bp := range lb.Properties.BackendAddressPools { + bpName := ptr.Deref(bp.Name, "") + if localServiceOwnsBackendPool(getServiceName(svc), bpName) { + if err := az.DeleteLBBackendPool(ctx, lbName, bpName); err != nil { + return nil, err } + changed = true } } } } + if changed { // Refresh the list of existing LBs after cleanup to update etags for the LBs. klog.V(4).Info("Refreshing the list of existing LBs") @@ -529,7 +523,7 @@ func (az *Cloud) cleanupLocalServiceBackendPool( // checkAndApplyLocalServiceBackendPoolUpdates if the IPs in the backend pool are aligned // with the corresponding endpointslice, and update the backend pool if necessary. -func (az *Cloud) checkAndApplyLocalServiceBackendPoolUpdates(lb network.LoadBalancer, service *v1.Service) error { +func (az *Cloud) checkAndApplyLocalServiceBackendPoolUpdates(lb armnetwork.LoadBalancer, service *v1.Service) error { serviceName := getServiceName(service) endpointsNodeNames := az.getLocalServiceEndpointsNodeNames(service) if endpointsNodeNames == nil { @@ -542,12 +536,12 @@ func (az *Cloud) checkAndApplyLocalServiceBackendPoolUpdates(lb network.LoadBala expectedIPs = append(expectedIPs, ips.UnsortedList()...) } currentIPsInBackendPools := make(map[string][]string) - for _, bp := range *lb.BackendAddressPools { + for _, bp := range lb.Properties.BackendAddressPools { bpName := ptr.Deref(bp.Name, "") if localServiceOwnsBackendPool(serviceName, bpName) { var currentIPs []string - for _, address := range *bp.LoadBalancerBackendAddresses { - currentIPs = append(currentIPs, *address.IPAddress) + for _, address := range bp.Properties.LoadBalancerBackendAddresses { + currentIPs = append(currentIPs, *address.Properties.IPAddress) } currentIPsInBackendPools[bpName] = currentIPs } diff --git a/pkg/provider/azure_local_services_test.go b/pkg/provider/azure_local_services_test.go index f248467990..e7050c7502 100644 --- a/pkg/provider/azure_local_services_test.go +++ b/pkg/provider/azure_local_services_test.go @@ -18,14 +18,14 @@ package provider import ( "context" - "errors" "fmt" "net/http" "sync" "testing" "time" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -37,10 +37,9 @@ import ( "k8s.io/client-go/kubernetes/fake" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient/mockloadbalancerclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/backendaddresspoolclient/mock_backendaddresspoolclient" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) @@ -55,53 +54,53 @@ func TestLoadBalancerBackendPoolUpdater(t *testing.T) { testCases := []struct { name string operations []batchOperation - existingBackendPools []network.BackendAddressPool - expectedGetBackendPool network.BackendAddressPool + existingBackendPools []*armnetwork.BackendAddressPool + expectedGetBackendPool *armnetwork.BackendAddressPool extraWait bool notLocal bool changeLB bool removeOperationServiceName string - expectedCreateOrUpdateBackendPools []network.BackendAddressPool - expectedBackendPools []network.BackendAddressPool + expectedCreateOrUpdateBackendPools []*armnetwork.BackendAddressPool + expectedBackendPools []*armnetwork.BackendAddressPool }{ { name: "Add node IPs to backend pool", operations: []batchOperation{addOperationPool1}, - existingBackendPools: []network.BackendAddressPool{ + existingBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), }, - expectedCreateOrUpdateBackendPools: []network.BackendAddressPool{ + expectedCreateOrUpdateBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{"10.0.0.1", "10.0.0.2"}), }, - expectedBackendPools: []network.BackendAddressPool{ + expectedBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{"10.0.0.1", "10.0.0.2"}), }, }, { name: "Remove node IPs from backend pool", operations: []batchOperation{addOperationPool1, removeOperationPool1}, - existingBackendPools: []network.BackendAddressPool{ + existingBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), }, - expectedCreateOrUpdateBackendPools: []network.BackendAddressPool{ + expectedCreateOrUpdateBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), }, - expectedBackendPools: []network.BackendAddressPool{ + expectedBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), }, }, { name: "Multiple operations targeting different backend pools", operations: []batchOperation{addOperationPool1, addOperationPool2, removeOperationPool1}, - existingBackendPools: []network.BackendAddressPool{ + existingBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), getTestBackendAddressPoolWithIPs("lb1", "pool2", []string{}), }, - expectedCreateOrUpdateBackendPools: []network.BackendAddressPool{ + expectedCreateOrUpdateBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), getTestBackendAddressPoolWithIPs("lb1", "pool2", []string{"10.0.0.1", "10.0.0.2"}), }, - expectedBackendPools: []network.BackendAddressPool{ + expectedBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), getTestBackendAddressPoolWithIPs("lb1", "pool2", []string{"10.0.0.1", "10.0.0.2"}), }, @@ -110,15 +109,15 @@ func TestLoadBalancerBackendPoolUpdater(t *testing.T) { name: "Multiple operations in two batches", operations: []batchOperation{addOperationPool1, removeOperationPool1}, extraWait: true, - existingBackendPools: []network.BackendAddressPool{ + existingBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), }, - expectedCreateOrUpdateBackendPools: []network.BackendAddressPool{ + expectedCreateOrUpdateBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{"10.0.0.1", "10.0.0.2"}), getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), }, expectedGetBackendPool: getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{"10.0.0.1", "10.0.0.2"}), - expectedBackendPools: []network.BackendAddressPool{ + expectedBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), }, }, @@ -153,55 +152,49 @@ func TestLoadBalancerBackendPoolUpdater(t *testing.T) { client := fake.NewSimpleClientset(&svc) informerFactory := informers.NewSharedInformerFactory(client, 0) cloud.serviceLister = informerFactory.Core().V1().Services().Lister() - mockLBClient := mockloadbalancerclient.NewMockInterface(ctrl) + mockbpClient := cloud.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) if len(tc.existingBackendPools) > 0 { - mockLBClient.EXPECT().GetLBBackendPool( + mockbpClient.EXPECT().Get( gomock.Any(), gomock.Any(), "lb1", *tc.existingBackendPools[0].Name, - gomock.Any(), ).Return(tc.existingBackendPools[0], nil) } if len(tc.existingBackendPools) == 2 { - mockLBClient.EXPECT().GetLBBackendPool( + mockbpClient.EXPECT().Get( gomock.Any(), gomock.Any(), "lb1", *tc.existingBackendPools[1].Name, - gomock.Any(), ).Return(tc.existingBackendPools[1], nil) } if tc.extraWait { - mockLBClient.EXPECT().GetLBBackendPool( + mockbpClient.EXPECT().Get( gomock.Any(), gomock.Any(), "lb1", *tc.expectedGetBackendPool.Name, - gomock.Any(), ).Return(tc.expectedGetBackendPool, nil) } if len(tc.expectedCreateOrUpdateBackendPools) > 0 { - mockLBClient.EXPECT().CreateOrUpdateBackendPools( + mockbpClient.EXPECT().CreateOrUpdate( gomock.Any(), gomock.Any(), "lb1", *tc.expectedCreateOrUpdateBackendPools[0].Name, - tc.expectedCreateOrUpdateBackendPools[0], - gomock.Any(), - ).Return(nil) + *tc.expectedCreateOrUpdateBackendPools[0], + ).Return(nil, nil) } if len(tc.existingBackendPools) == 2 || tc.extraWait { - mockLBClient.EXPECT().CreateOrUpdateBackendPools( + mockbpClient.EXPECT().CreateOrUpdate( gomock.Any(), gomock.Any(), "lb1", *tc.expectedCreateOrUpdateBackendPools[1].Name, - tc.expectedCreateOrUpdateBackendPools[1], - gomock.Any(), - ).Return(nil) + *tc.expectedCreateOrUpdateBackendPools[1], + ).Return(nil, nil) } - cloud.LoadBalancerClient = mockLBClient u := newLoadBalancerBackendPoolUpdater(cloud, time.Second) ctx, cancel := context.WithCancel(context.Background()) @@ -230,90 +223,57 @@ func TestLoadBalancerBackendPoolUpdater(t *testing.T) { } func TestLoadBalancerBackendPoolUpdaterFailed(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() addOperationPool1 := getAddIPsToBackendPoolOperation("ns1/svc1", "lb1", "pool1", []string{"10.0.0.1", "10.0.0.2"}) testCases := []struct { name string operations []batchOperation - existingBackendPools []network.BackendAddressPool - expectedGetBackendPool network.BackendAddressPool - getBackendPoolErr *retry.Error - putBackendPoolErr *retry.Error - expectedCreateOrUpdateBackendPools []network.BackendAddressPool - expectedBackendPools []network.BackendAddressPool + existingBackendPools []*armnetwork.BackendAddressPool + expectedGetBackendPool *armnetwork.BackendAddressPool + getBackendPoolErr error + putBackendPoolErr error + expectedCreateOrUpdateBackendPools []*armnetwork.BackendAddressPool + expectedBackendPools []*armnetwork.BackendAddressPool }{ - { - name: "Retriable error when getting backend pool", - operations: []batchOperation{addOperationPool1}, - existingBackendPools: []network.BackendAddressPool{ - getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), - }, - getBackendPoolErr: retry.NewError(true, errors.New("error")), - expectedCreateOrUpdateBackendPools: []network.BackendAddressPool{ - getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{"10.0.0.1", "10.0.0.2"}), - }, - expectedBackendPools: []network.BackendAddressPool{ - getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{"10.0.0.1", "10.0.0.2"}), - }, - }, - { - name: "Retriable error when updating backend pool", - operations: []batchOperation{addOperationPool1}, - existingBackendPools: []network.BackendAddressPool{ - getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), - }, - expectedGetBackendPool: getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), - putBackendPoolErr: retry.NewError(true, errors.New("error")), - expectedCreateOrUpdateBackendPools: []network.BackendAddressPool{ - getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{"10.0.0.1", "10.0.0.2"}), - getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{"10.0.0.1", "10.0.0.2"}), - }, - expectedBackendPools: []network.BackendAddressPool{ - getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{"10.0.0.1", "10.0.0.2"}), - }, - }, { name: "Non-retriable error when getting backend pool", operations: []batchOperation{addOperationPool1}, - existingBackendPools: []network.BackendAddressPool{ + existingBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), }, - getBackendPoolErr: retry.NewError(false, fmt.Errorf("error")), - expectedBackendPools: []network.BackendAddressPool{ + getBackendPoolErr: &azcore.ResponseError{ErrorCode: "error"}, + expectedBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), }, }, { name: "Non-retriable error when updating backend pool", operations: []batchOperation{addOperationPool1}, - existingBackendPools: []network.BackendAddressPool{ + existingBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), }, expectedGetBackendPool: getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), - putBackendPoolErr: retry.NewError(false, fmt.Errorf("error")), - expectedCreateOrUpdateBackendPools: []network.BackendAddressPool{ + putBackendPoolErr: &azcore.ResponseError{ErrorCode: "error"}, + expectedCreateOrUpdateBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{"10.0.0.1", "10.0.0.2"}), }, }, { name: "Backend pool not found", operations: []batchOperation{addOperationPool1}, - existingBackendPools: []network.BackendAddressPool{ + existingBackendPools: []*armnetwork.BackendAddressPool{ getTestBackendAddressPoolWithIPs("lb1", "pool1", []string{}), }, - getBackendPoolErr: &retry.Error{ - HTTPStatusCode: http.StatusNotFound, - Retriable: false, - RawError: errors.New("error"), - }, + getBackendPoolErr: &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: "error"}, }, } for _, tc := range testCases { t.Run(tc.name, func(_ *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + cloud := GetTestCloud(ctrl) cloud.localServiceNameToServiceInfoMap = sync.Map{} cloud.localServiceNameToServiceInfoMap.Store("ns1/svc1", &serviceInfo{lbName: "lb1"}) @@ -321,62 +281,40 @@ func TestLoadBalancerBackendPoolUpdaterFailed(t *testing.T) { client := fake.NewSimpleClientset(&svc) informerFactory := informers.NewSharedInformerFactory(client, 0) cloud.serviceLister = informerFactory.Core().V1().Services().Lister() - mockLBClient := mockloadbalancerclient.NewMockInterface(ctrl) - mockLBClient.EXPECT().GetLBBackendPool( + mockLBClient := cloud.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) + mockBPClient := cloud.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) + mockLBClient.EXPECT().Get( gomock.Any(), gomock.Any(), "lb1", *tc.existingBackendPools[0].Name, - gomock.Any(), ).Return(tc.existingBackendPools[0], tc.getBackendPoolErr) - if tc.getBackendPoolErr != nil && tc.getBackendPoolErr.Retriable { - mockLBClient.EXPECT().GetLBBackendPool( - gomock.Any(), - gomock.Any(), - "lb1", - *tc.existingBackendPools[0].Name, - gomock.Any(), - ).Return(tc.existingBackendPools[0], nil) - } if len(tc.existingBackendPools) == 2 { - mockLBClient.EXPECT().GetLBBackendPool( + mockLBClient.EXPECT().Get( gomock.Any(), gomock.Any(), "lb1", *tc.existingBackendPools[1].Name, - gomock.Any(), ).Return(tc.existingBackendPools[1], nil) } - if tc.putBackendPoolErr != nil && tc.putBackendPoolErr.Retriable { - mockLBClient.EXPECT().GetLBBackendPool( - gomock.Any(), - gomock.Any(), - "lb1", - *tc.expectedGetBackendPool.Name, - gomock.Any(), - ).Return(tc.expectedGetBackendPool, nil) - } if len(tc.expectedCreateOrUpdateBackendPools) > 0 { - mockLBClient.EXPECT().CreateOrUpdateBackendPools( + mockBPClient.EXPECT().CreateOrUpdate( gomock.Any(), gomock.Any(), "lb1", *tc.expectedCreateOrUpdateBackendPools[0].Name, - tc.expectedCreateOrUpdateBackendPools[0], - gomock.Any(), - ).Return(tc.putBackendPoolErr) + *tc.expectedCreateOrUpdateBackendPools[0], + ).Return(nil, tc.putBackendPoolErr) } if len(tc.expectedCreateOrUpdateBackendPools) == 2 { - mockLBClient.EXPECT().CreateOrUpdateBackendPools( + mockLBClient.EXPECT().CreateOrUpdate( gomock.Any(), gomock.Any(), "lb1", *tc.expectedCreateOrUpdateBackendPools[1].Name, - tc.expectedCreateOrUpdateBackendPools[1], - gomock.Any(), - ).Return(nil) + *tc.expectedCreateOrUpdateBackendPools[1], + ).Return(nil, nil) } - cloud.LoadBalancerClient = mockLBClient u := newLoadBalancerBackendPoolUpdater(cloud, time.Second) ctx, cancel := context.WithCancel(context.Background()) @@ -393,23 +331,23 @@ func TestLoadBalancerBackendPoolUpdaterFailed(t *testing.T) { } } -func getTestBackendAddressPoolWithIPs(lbName, bpName string, ips []string) network.BackendAddressPool { - bp := network.BackendAddressPool{ +func getTestBackendAddressPoolWithIPs(lbName, bpName string, ips []string) *armnetwork.BackendAddressPool { + bp := &armnetwork.BackendAddressPool{ ID: ptr.To(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/%s/backendAddressPools/%s", lbName, bpName)), Name: ptr.To(bpName), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - VirtualNetwork: &network.SubResource{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + VirtualNetwork: &armnetwork.SubResource{ ID: ptr.To("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet"), }, Location: ptr.To("eastus"), - LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{}, + LoadBalancerBackendAddresses: []*armnetwork.LoadBalancerBackendAddress{}, }, } for _, ip := range ips { if len(ip) > 0 { - *bp.LoadBalancerBackendAddresses = append(*bp.LoadBalancerBackendAddresses, network.LoadBalancerBackendAddress{ + bp.Properties.LoadBalancerBackendAddresses = append(bp.Properties.LoadBalancerBackendAddresses, &armnetwork.LoadBalancerBackendAddress{ Name: ptr.To(""), - LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ + Properties: &armnetwork.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: ptr.To(ip), }, }) @@ -485,7 +423,7 @@ func TestEndpointSlicesInformer(t *testing.T) { informerFactory := informers.NewSharedInformerFactory(client, 0) cloud.serviceLister = informerFactory.Core().V1().Services().Lister() cloud.LoadBalancerBackendPoolUpdateIntervalInSeconds = 1 - cloud.LoadBalancerSku = consts.LoadBalancerSkuStandard + cloud.LoadBalancerSKU = consts.LoadBalancerSKUStandard cloud.MultipleStandardLoadBalancerConfigurations = []config.MultipleStandardLoadBalancerConfiguration{ { Name: "lb1", @@ -499,10 +437,9 @@ func TestEndpointSlicesInformer(t *testing.T) { existingBackendPool := getTestBackendAddressPoolWithIPs("lb1", "test-svc1", []string{"10.0.0.1"}) expectedBackendPool := getTestBackendAddressPoolWithIPs("lb1", "test-svc1", []string{"10.0.0.2"}) - mockLBClient := mockloadbalancerclient.NewMockInterface(ctrl) - mockLBClient.EXPECT().GetLBBackendPool(gomock.Any(), gomock.Any(), "lb1", "test-svc1", "").Return(existingBackendPool, nil).Times(tc.expectedGetBackendPoolCount) - mockLBClient.EXPECT().CreateOrUpdateBackendPools(gomock.Any(), gomock.Any(), "lb1", "test-svc1", expectedBackendPool, "").Return(nil).Times(tc.expectedPutBackendPoolCount) - cloud.LoadBalancerClient = mockLBClient + mockLBClient := cloud.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) + mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), "lb1", "test-svc1").Return(existingBackendPool, nil).Times(tc.expectedGetBackendPoolCount) + mockLBClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), "lb1", "test-svc1", *expectedBackendPool).Return(nil, nil).Times(tc.expectedPutBackendPoolCount) u := newLoadBalancerBackendPoolUpdater(cloud, time.Second) ctx, cancel := context.WithCancel(context.Background()) @@ -564,7 +501,7 @@ func TestCheckAndApplyLocalServiceBackendPoolUpdates(t *testing.T) { informerFactory := informers.NewSharedInformerFactory(client, 0) cloud.serviceLister = informerFactory.Core().V1().Services().Lister() cloud.LoadBalancerBackendPoolUpdateIntervalInSeconds = 1 - cloud.LoadBalancerSku = consts.LoadBalancerSkuStandard + cloud.LoadBalancerSKU = consts.LoadBalancerSKUStandard cloud.MultipleStandardLoadBalancerConfigurations = []config.MultipleStandardLoadBalancerConfiguration{ { Name: "lb1", @@ -581,10 +518,10 @@ func TestCheckAndApplyLocalServiceBackendPoolUpdates(t *testing.T) { existingBackendPool := getTestBackendAddressPoolWithIPs("lb1", "default-svc1", []string{"10.0.0.1"}) existingBackendPoolIPv6 := getTestBackendAddressPoolWithIPs("lb1", "default-svc1-ipv6", []string{"fd00::1"}) - existingLB := network.LoadBalancer{ + existingLB := armnetwork.LoadBalancer{ Name: ptr.To("lb1"), - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ existingBackendPool, existingBackendPoolIPv6, }, @@ -592,14 +529,13 @@ func TestCheckAndApplyLocalServiceBackendPoolUpdates(t *testing.T) { } expectedBackendPool := getTestBackendAddressPoolWithIPs("lb1", "default-svc1", []string{"10.0.0.2"}) expectedBackendPoolIPv6 := getTestBackendAddressPoolWithIPs("lb1", "default-svc1-ipv6", []string{"fd00::2"}) - mockLBClient := mockloadbalancerclient.NewMockInterface(ctrl) + mockLBClient := cloud.NetworkClientFactory.GetBackendAddressPoolClient().(*mock_backendaddresspoolclient.MockInterface) if tc.existingEPS != nil { - mockLBClient.EXPECT().GetLBBackendPool(gomock.Any(), gomock.Any(), "lb1", "default-svc1", "").Return(existingBackendPool, nil) - mockLBClient.EXPECT().GetLBBackendPool(gomock.Any(), gomock.Any(), "lb1", "default-svc1-ipv6", "").Return(existingBackendPoolIPv6, nil) - mockLBClient.EXPECT().CreateOrUpdateBackendPools(gomock.Any(), gomock.Any(), "lb1", "default-svc1", expectedBackendPool, "").Return(nil) - mockLBClient.EXPECT().CreateOrUpdateBackendPools(gomock.Any(), gomock.Any(), "lb1", "default-svc1-ipv6", expectedBackendPoolIPv6, "").Return(nil) + mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), "lb1", "default-svc1").Return(existingBackendPool, nil) + mockLBClient.EXPECT().Get(gomock.Any(), gomock.Any(), "lb1", "default-svc1-ipv6").Return(existingBackendPoolIPv6, nil) + mockLBClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), "lb1", "default-svc1", *expectedBackendPool).Return(nil, nil) + mockLBClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), "lb1", "default-svc1-ipv6", *expectedBackendPoolIPv6).Return(nil, nil) } - cloud.LoadBalancerClient = mockLBClient u := newLoadBalancerBackendPoolUpdater(cloud, time.Second) ctx, cancel := context.WithCancel(context.Background()) diff --git a/pkg/provider/azure_mock_loadbalancer_backendpool.go b/pkg/provider/azure_mock_loadbalancer_backendpool.go index 4772be9a81..7cf8a3aec1 100644 --- a/pkg/provider/azure_mock_loadbalancer_backendpool.go +++ b/pkg/provider/azure_mock_loadbalancer_backendpool.go @@ -20,7 +20,7 @@ // // Generated by this command: // -// mockgen -package provider -source azure_loadbalancer_backendpool.go -self_package sigs.k8s.io/cloud-provider-azure/pkg/provider -copyright_file ../../hack/boilerplate/boilerplate.generatego.txt +// mockgen -destination azure_mock_loadbalancer_backendpool.go -source azure_loadbalancer_backendpool.go -self_package sigs.k8s.io/cloud-provider-azure/pkg/provider -package=provider -copyright_file ../../hack/boilerplate/boilerplate.generatego.txt -typed BackendPool // // Package provider is a generated GoMock package. @@ -30,7 +30,7 @@ import ( context "context" reflect "reflect" - network "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + armnetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" gomock "go.uber.org/mock/gomock" v1 "k8s.io/api/core/v1" ) @@ -39,6 +39,7 @@ import ( type MockBackendPool struct { ctrl *gomock.Controller recorder *MockBackendPoolMockRecorder + isgomock struct{} } // MockBackendPoolMockRecorder is the mock recorder for MockBackendPool. @@ -59,22 +60,46 @@ func (m *MockBackendPool) EXPECT() *MockBackendPoolMockRecorder { } // CleanupVMSetFromBackendPoolByCondition mocks base method. -func (m *MockBackendPool) CleanupVMSetFromBackendPoolByCondition(ctx context.Context, slb *network.LoadBalancer, service *v1.Service, nodes []*v1.Node, clusterName string, shouldRemoveVMSetFromSLB func(string) bool) (*network.LoadBalancer, error) { +func (m *MockBackendPool) CleanupVMSetFromBackendPoolByCondition(ctx context.Context, slb *armnetwork.LoadBalancer, service *v1.Service, nodes []*v1.Node, clusterName string, shouldRemoveVMSetFromSLB func(string) bool) (*armnetwork.LoadBalancer, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CleanupVMSetFromBackendPoolByCondition", ctx, slb, service, nodes, clusterName, shouldRemoveVMSetFromSLB) - ret0, _ := ret[0].(*network.LoadBalancer) + ret0, _ := ret[0].(*armnetwork.LoadBalancer) ret1, _ := ret[1].(error) return ret0, ret1 } // CleanupVMSetFromBackendPoolByCondition indicates an expected call of CleanupVMSetFromBackendPoolByCondition. -func (mr *MockBackendPoolMockRecorder) CleanupVMSetFromBackendPoolByCondition(ctx, slb, service, nodes, clusterName, shouldRemoveVMSetFromSLB any) *gomock.Call { +func (mr *MockBackendPoolMockRecorder) CleanupVMSetFromBackendPoolByCondition(ctx, slb, service, nodes, clusterName, shouldRemoveVMSetFromSLB any) *MockBackendPoolCleanupVMSetFromBackendPoolByConditionCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CleanupVMSetFromBackendPoolByCondition", reflect.TypeOf((*MockBackendPool)(nil).CleanupVMSetFromBackendPoolByCondition), ctx, slb, service, nodes, clusterName, shouldRemoveVMSetFromSLB) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CleanupVMSetFromBackendPoolByCondition", reflect.TypeOf((*MockBackendPool)(nil).CleanupVMSetFromBackendPoolByCondition), ctx, slb, service, nodes, clusterName, shouldRemoveVMSetFromSLB) + return &MockBackendPoolCleanupVMSetFromBackendPoolByConditionCall{Call: call} +} + +// MockBackendPoolCleanupVMSetFromBackendPoolByConditionCall wrap *gomock.Call +type MockBackendPoolCleanupVMSetFromBackendPoolByConditionCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockBackendPoolCleanupVMSetFromBackendPoolByConditionCall) Return(arg0 *armnetwork.LoadBalancer, arg1 error) *MockBackendPoolCleanupVMSetFromBackendPoolByConditionCall { + c.Call = c.Call.Return(arg0, arg1) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockBackendPoolCleanupVMSetFromBackendPoolByConditionCall) Do(f func(context.Context, *armnetwork.LoadBalancer, *v1.Service, []*v1.Node, string, func(string) bool) (*armnetwork.LoadBalancer, error)) *MockBackendPoolCleanupVMSetFromBackendPoolByConditionCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockBackendPoolCleanupVMSetFromBackendPoolByConditionCall) DoAndReturn(f func(context.Context, *armnetwork.LoadBalancer, *v1.Service, []*v1.Node, string, func(string) bool) (*armnetwork.LoadBalancer, error)) *MockBackendPoolCleanupVMSetFromBackendPoolByConditionCall { + c.Call = c.Call.DoAndReturn(f) + return c } // EnsureHostsInPool mocks base method. -func (m *MockBackendPool) EnsureHostsInPool(ctx context.Context, service *v1.Service, nodes []*v1.Node, backendPoolID, vmSetName, clusterName, lbName string, backendPool network.BackendAddressPool) error { +func (m *MockBackendPool) EnsureHostsInPool(ctx context.Context, service *v1.Service, nodes []*v1.Node, backendPoolID, vmSetName, clusterName, lbName string, backendPool *armnetwork.BackendAddressPool) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "EnsureHostsInPool", ctx, service, nodes, backendPoolID, vmSetName, clusterName, lbName, backendPool) ret0, _ := ret[0].(error) @@ -82,13 +107,37 @@ func (m *MockBackendPool) EnsureHostsInPool(ctx context.Context, service *v1.Ser } // EnsureHostsInPool indicates an expected call of EnsureHostsInPool. -func (mr *MockBackendPoolMockRecorder) EnsureHostsInPool(ctx, service, nodes, backendPoolID, vmSetName, clusterName, lbName, backendPool any) *gomock.Call { +func (mr *MockBackendPoolMockRecorder) EnsureHostsInPool(ctx, service, nodes, backendPoolID, vmSetName, clusterName, lbName, backendPool any) *MockBackendPoolEnsureHostsInPoolCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureHostsInPool", reflect.TypeOf((*MockBackendPool)(nil).EnsureHostsInPool), ctx, service, nodes, backendPoolID, vmSetName, clusterName, lbName, backendPool) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureHostsInPool", reflect.TypeOf((*MockBackendPool)(nil).EnsureHostsInPool), ctx, service, nodes, backendPoolID, vmSetName, clusterName, lbName, backendPool) + return &MockBackendPoolEnsureHostsInPoolCall{Call: call} +} + +// MockBackendPoolEnsureHostsInPoolCall wrap *gomock.Call +type MockBackendPoolEnsureHostsInPoolCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockBackendPoolEnsureHostsInPoolCall) Return(arg0 error) *MockBackendPoolEnsureHostsInPoolCall { + c.Call = c.Call.Return(arg0) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockBackendPoolEnsureHostsInPoolCall) Do(f func(context.Context, *v1.Service, []*v1.Node, string, string, string, string, *armnetwork.BackendAddressPool) error) *MockBackendPoolEnsureHostsInPoolCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockBackendPoolEnsureHostsInPoolCall) DoAndReturn(f func(context.Context, *v1.Service, []*v1.Node, string, string, string, string, *armnetwork.BackendAddressPool) error) *MockBackendPoolEnsureHostsInPoolCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetBackendPrivateIPs mocks base method. -func (m *MockBackendPool) GetBackendPrivateIPs(ctx context.Context, clusterName string, service *v1.Service, lb *network.LoadBalancer) ([]string, []string) { +func (m *MockBackendPool) GetBackendPrivateIPs(ctx context.Context, clusterName string, service *v1.Service, lb *armnetwork.LoadBalancer) ([]string, []string) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetBackendPrivateIPs", ctx, clusterName, service, lb) ret0, _ := ret[0].([]string) @@ -97,24 +146,72 @@ func (m *MockBackendPool) GetBackendPrivateIPs(ctx context.Context, clusterName } // GetBackendPrivateIPs indicates an expected call of GetBackendPrivateIPs. -func (mr *MockBackendPoolMockRecorder) GetBackendPrivateIPs(ctx, clusterName, service, lb any) *gomock.Call { +func (mr *MockBackendPoolMockRecorder) GetBackendPrivateIPs(ctx, clusterName, service, lb any) *MockBackendPoolGetBackendPrivateIPsCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBackendPrivateIPs", reflect.TypeOf((*MockBackendPool)(nil).GetBackendPrivateIPs), ctx, clusterName, service, lb) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBackendPrivateIPs", reflect.TypeOf((*MockBackendPool)(nil).GetBackendPrivateIPs), ctx, clusterName, service, lb) + return &MockBackendPoolGetBackendPrivateIPsCall{Call: call} +} + +// MockBackendPoolGetBackendPrivateIPsCall wrap *gomock.Call +type MockBackendPoolGetBackendPrivateIPsCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockBackendPoolGetBackendPrivateIPsCall) Return(arg0, arg1 []string) *MockBackendPoolGetBackendPrivateIPsCall { + c.Call = c.Call.Return(arg0, arg1) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockBackendPoolGetBackendPrivateIPsCall) Do(f func(context.Context, string, *v1.Service, *armnetwork.LoadBalancer) ([]string, []string)) *MockBackendPoolGetBackendPrivateIPsCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockBackendPoolGetBackendPrivateIPsCall) DoAndReturn(f func(context.Context, string, *v1.Service, *armnetwork.LoadBalancer) ([]string, []string)) *MockBackendPoolGetBackendPrivateIPsCall { + c.Call = c.Call.DoAndReturn(f) + return c } // ReconcileBackendPools mocks base method. -func (m *MockBackendPool) ReconcileBackendPools(ctx context.Context, clusterName string, service *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { +func (m *MockBackendPool) ReconcileBackendPools(ctx context.Context, clusterName string, service *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReconcileBackendPools", ctx, clusterName, service, lb) ret0, _ := ret[0].(bool) ret1, _ := ret[1].(bool) - ret2, _ := ret[2].(*network.LoadBalancer) + ret2, _ := ret[2].(*armnetwork.LoadBalancer) ret3, _ := ret[3].(error) return ret0, ret1, ret2, ret3 } // ReconcileBackendPools indicates an expected call of ReconcileBackendPools. -func (mr *MockBackendPoolMockRecorder) ReconcileBackendPools(ctx, clusterName, service, lb any) *gomock.Call { +func (mr *MockBackendPoolMockRecorder) ReconcileBackendPools(ctx, clusterName, service, lb any) *MockBackendPoolReconcileBackendPoolsCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReconcileBackendPools", reflect.TypeOf((*MockBackendPool)(nil).ReconcileBackendPools), ctx, clusterName, service, lb) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReconcileBackendPools", reflect.TypeOf((*MockBackendPool)(nil).ReconcileBackendPools), ctx, clusterName, service, lb) + return &MockBackendPoolReconcileBackendPoolsCall{Call: call} +} + +// MockBackendPoolReconcileBackendPoolsCall wrap *gomock.Call +type MockBackendPoolReconcileBackendPoolsCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockBackendPoolReconcileBackendPoolsCall) Return(arg0, arg1 bool, arg2 *armnetwork.LoadBalancer, arg3 error) *MockBackendPoolReconcileBackendPoolsCall { + c.Call = c.Call.Return(arg0, arg1, arg2, arg3) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockBackendPoolReconcileBackendPoolsCall) Do(f func(context.Context, string, *v1.Service, *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error)) *MockBackendPoolReconcileBackendPoolsCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockBackendPoolReconcileBackendPoolsCall) DoAndReturn(f func(context.Context, string, *v1.Service, *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error)) *MockBackendPoolReconcileBackendPoolsCall { + c.Call = c.Call.DoAndReturn(f) + return c } diff --git a/pkg/provider/azure_mock_vmsets.go b/pkg/provider/azure_mock_vmsets.go index 5476b3b6b2..71a15b34a7 100644 --- a/pkg/provider/azure_mock_vmsets.go +++ b/pkg/provider/azure_mock_vmsets.go @@ -16,11 +16,11 @@ // // Code generated by MockGen. DO NOT EDIT. -// Source: /Users/niqi/go/src/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmsets.go +// Source: azure_vmsets.go // // Generated by this command: // -// mockgen -destination=/Users/niqi/go/src/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_mock_vmsets.go -source=/Users/niqi/go/src/sigs.k8s.io/cloud-provider-azure/pkg/provider/azure_vmsets.go -package=provider VMSet +// mockgen -destination azure_mock_vmsets.go -source azure_vmsets.go -package=provider -copyright_file ../../hack/boilerplate/boilerplate.generatego.txt -typed VMSet // // Package provider is a generated GoMock package. @@ -30,13 +30,12 @@ import ( context "context" reflect "reflect" - armcompute "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" - compute "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - network "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + v6 "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" + v60 "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" gomock "go.uber.org/mock/gomock" v1 "k8s.io/api/core/v1" types "k8s.io/apimachinery/pkg/types" - cloudprovider "k8s.io/cloud-provider" + cloud_provider "k8s.io/cloud-provider" cache "sigs.k8s.io/cloud-provider-azure/pkg/cache" ) @@ -44,6 +43,7 @@ import ( type MockVMSet struct { ctrl *gomock.Controller recorder *MockVMSetMockRecorder + isgomock struct{} } // MockVMSetMockRecorder is the mock recorder for MockVMSet. @@ -72,9 +72,33 @@ func (m *MockVMSet) AttachDisk(ctx context.Context, nodeName types.NodeName, dis } // AttachDisk indicates an expected call of AttachDisk. -func (mr *MockVMSetMockRecorder) AttachDisk(ctx, nodeName, diskMap any) *gomock.Call { +func (mr *MockVMSetMockRecorder) AttachDisk(ctx, nodeName, diskMap any) *MockVMSetAttachDiskCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AttachDisk", reflect.TypeOf((*MockVMSet)(nil).AttachDisk), ctx, nodeName, diskMap) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AttachDisk", reflect.TypeOf((*MockVMSet)(nil).AttachDisk), ctx, nodeName, diskMap) + return &MockVMSetAttachDiskCall{Call: call} +} + +// MockVMSetAttachDiskCall wrap *gomock.Call +type MockVMSetAttachDiskCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetAttachDiskCall) Return(arg0 error) *MockVMSetAttachDiskCall { + c.Call = c.Call.Return(arg0) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetAttachDiskCall) Do(f func(context.Context, types.NodeName, map[string]*AttachDiskOptions) error) *MockVMSetAttachDiskCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetAttachDiskCall) DoAndReturn(f func(context.Context, types.NodeName, map[string]*AttachDiskOptions) error) *MockVMSetAttachDiskCall { + c.Call = c.Call.DoAndReturn(f) + return c } // DeleteCacheForNode mocks base method. @@ -86,9 +110,33 @@ func (m *MockVMSet) DeleteCacheForNode(ctx context.Context, nodeName string) err } // DeleteCacheForNode indicates an expected call of DeleteCacheForNode. -func (mr *MockVMSetMockRecorder) DeleteCacheForNode(ctx, nodeName any) *gomock.Call { +func (mr *MockVMSetMockRecorder) DeleteCacheForNode(ctx, nodeName any) *MockVMSetDeleteCacheForNodeCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCacheForNode", reflect.TypeOf((*MockVMSet)(nil).DeleteCacheForNode), ctx, nodeName) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCacheForNode", reflect.TypeOf((*MockVMSet)(nil).DeleteCacheForNode), ctx, nodeName) + return &MockVMSetDeleteCacheForNodeCall{Call: call} +} + +// MockVMSetDeleteCacheForNodeCall wrap *gomock.Call +type MockVMSetDeleteCacheForNodeCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetDeleteCacheForNodeCall) Return(arg0 error) *MockVMSetDeleteCacheForNodeCall { + c.Call = c.Call.Return(arg0) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetDeleteCacheForNodeCall) Do(f func(context.Context, string) error) *MockVMSetDeleteCacheForNodeCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetDeleteCacheForNodeCall) DoAndReturn(f func(context.Context, string) error) *MockVMSetDeleteCacheForNodeCall { + c.Call = c.Call.DoAndReturn(f) + return c } // DetachDisk mocks base method. @@ -100,13 +148,37 @@ func (m *MockVMSet) DetachDisk(ctx context.Context, nodeName types.NodeName, dis } // DetachDisk indicates an expected call of DetachDisk. -func (mr *MockVMSetMockRecorder) DetachDisk(ctx, nodeName, diskMap, forceDetach any) *gomock.Call { +func (mr *MockVMSetMockRecorder) DetachDisk(ctx, nodeName, diskMap, forceDetach any) *MockVMSetDetachDiskCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DetachDisk", reflect.TypeOf((*MockVMSet)(nil).DetachDisk), ctx, nodeName, diskMap, forceDetach) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DetachDisk", reflect.TypeOf((*MockVMSet)(nil).DetachDisk), ctx, nodeName, diskMap, forceDetach) + return &MockVMSetDetachDiskCall{Call: call} +} + +// MockVMSetDetachDiskCall wrap *gomock.Call +type MockVMSetDetachDiskCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetDetachDiskCall) Return(arg0 error) *MockVMSetDetachDiskCall { + c.Call = c.Call.Return(arg0) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetDetachDiskCall) Do(f func(context.Context, types.NodeName, map[string]string, bool) error) *MockVMSetDetachDiskCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetDetachDiskCall) DoAndReturn(f func(context.Context, types.NodeName, map[string]string, bool) error) *MockVMSetDetachDiskCall { + c.Call = c.Call.DoAndReturn(f) + return c } // EnsureBackendPoolDeleted mocks base method. -func (m *MockVMSet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Service, backendPoolIDs []string, vmSetName string, backendAddressPools *[]network.BackendAddressPool, deleteFromVMSet bool) (bool, error) { +func (m *MockVMSet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Service, backendPoolIDs []string, vmSetName string, backendAddressPools []*v60.BackendAddressPool, deleteFromVMSet bool) (bool, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "EnsureBackendPoolDeleted", ctx, service, backendPoolIDs, vmSetName, backendAddressPools, deleteFromVMSet) ret0, _ := ret[0].(bool) @@ -115,9 +187,33 @@ func (m *MockVMSet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Se } // EnsureBackendPoolDeleted indicates an expected call of EnsureBackendPoolDeleted. -func (mr *MockVMSetMockRecorder) EnsureBackendPoolDeleted(ctx, service, backendPoolIDs, vmSetName, backendAddressPools, deleteFromVMSet any) *gomock.Call { +func (mr *MockVMSetMockRecorder) EnsureBackendPoolDeleted(ctx, service, backendPoolIDs, vmSetName, backendAddressPools, deleteFromVMSet any) *MockVMSetEnsureBackendPoolDeletedCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureBackendPoolDeleted", reflect.TypeOf((*MockVMSet)(nil).EnsureBackendPoolDeleted), ctx, service, backendPoolIDs, vmSetName, backendAddressPools, deleteFromVMSet) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureBackendPoolDeleted", reflect.TypeOf((*MockVMSet)(nil).EnsureBackendPoolDeleted), ctx, service, backendPoolIDs, vmSetName, backendAddressPools, deleteFromVMSet) + return &MockVMSetEnsureBackendPoolDeletedCall{Call: call} +} + +// MockVMSetEnsureBackendPoolDeletedCall wrap *gomock.Call +type MockVMSetEnsureBackendPoolDeletedCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetEnsureBackendPoolDeletedCall) Return(arg0 bool, arg1 error) *MockVMSetEnsureBackendPoolDeletedCall { + c.Call = c.Call.Return(arg0, arg1) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetEnsureBackendPoolDeletedCall) Do(f func(context.Context, *v1.Service, []string, string, []*v60.BackendAddressPool, bool) (bool, error)) *MockVMSetEnsureBackendPoolDeletedCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetEnsureBackendPoolDeletedCall) DoAndReturn(f func(context.Context, *v1.Service, []string, string, []*v60.BackendAddressPool, bool) (bool, error)) *MockVMSetEnsureBackendPoolDeletedCall { + c.Call = c.Call.DoAndReturn(f) + return c } // EnsureBackendPoolDeletedFromVMSets mocks base method. @@ -129,27 +225,75 @@ func (m *MockVMSet) EnsureBackendPoolDeletedFromVMSets(ctx context.Context, vmSe } // EnsureBackendPoolDeletedFromVMSets indicates an expected call of EnsureBackendPoolDeletedFromVMSets. -func (mr *MockVMSetMockRecorder) EnsureBackendPoolDeletedFromVMSets(ctx, vmSetNamesMap, backendPoolIDs any) *gomock.Call { +func (mr *MockVMSetMockRecorder) EnsureBackendPoolDeletedFromVMSets(ctx, vmSetNamesMap, backendPoolIDs any) *MockVMSetEnsureBackendPoolDeletedFromVMSetsCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureBackendPoolDeletedFromVMSets", reflect.TypeOf((*MockVMSet)(nil).EnsureBackendPoolDeletedFromVMSets), ctx, vmSetNamesMap, backendPoolIDs) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureBackendPoolDeletedFromVMSets", reflect.TypeOf((*MockVMSet)(nil).EnsureBackendPoolDeletedFromVMSets), ctx, vmSetNamesMap, backendPoolIDs) + return &MockVMSetEnsureBackendPoolDeletedFromVMSetsCall{Call: call} +} + +// MockVMSetEnsureBackendPoolDeletedFromVMSetsCall wrap *gomock.Call +type MockVMSetEnsureBackendPoolDeletedFromVMSetsCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetEnsureBackendPoolDeletedFromVMSetsCall) Return(arg0 error) *MockVMSetEnsureBackendPoolDeletedFromVMSetsCall { + c.Call = c.Call.Return(arg0) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetEnsureBackendPoolDeletedFromVMSetsCall) Do(f func(context.Context, map[string]bool, []string) error) *MockVMSetEnsureBackendPoolDeletedFromVMSetsCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetEnsureBackendPoolDeletedFromVMSetsCall) DoAndReturn(f func(context.Context, map[string]bool, []string) error) *MockVMSetEnsureBackendPoolDeletedFromVMSetsCall { + c.Call = c.Call.DoAndReturn(f) + return c } // EnsureHostInPool mocks base method. -func (m *MockVMSet) EnsureHostInPool(ctx context.Context, service *v1.Service, nodeName types.NodeName, backendPoolID, vmSetName string) (string, string, string, *compute.VirtualMachineScaleSetVM, error) { +func (m *MockVMSet) EnsureHostInPool(ctx context.Context, service *v1.Service, nodeName types.NodeName, backendPoolID, vmSetName string) (string, string, string, *v6.VirtualMachineScaleSetVM, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "EnsureHostInPool", ctx, service, nodeName, backendPoolID, vmSetName) ret0, _ := ret[0].(string) ret1, _ := ret[1].(string) ret2, _ := ret[2].(string) - ret3, _ := ret[3].(*compute.VirtualMachineScaleSetVM) + ret3, _ := ret[3].(*v6.VirtualMachineScaleSetVM) ret4, _ := ret[4].(error) return ret0, ret1, ret2, ret3, ret4 } // EnsureHostInPool indicates an expected call of EnsureHostInPool. -func (mr *MockVMSetMockRecorder) EnsureHostInPool(ctx, service, nodeName, backendPoolID, vmSetName any) *gomock.Call { +func (mr *MockVMSetMockRecorder) EnsureHostInPool(ctx, service, nodeName, backendPoolID, vmSetName any) *MockVMSetEnsureHostInPoolCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureHostInPool", reflect.TypeOf((*MockVMSet)(nil).EnsureHostInPool), ctx, service, nodeName, backendPoolID, vmSetName) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureHostInPool", reflect.TypeOf((*MockVMSet)(nil).EnsureHostInPool), ctx, service, nodeName, backendPoolID, vmSetName) + return &MockVMSetEnsureHostInPoolCall{Call: call} +} + +// MockVMSetEnsureHostInPoolCall wrap *gomock.Call +type MockVMSetEnsureHostInPoolCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetEnsureHostInPoolCall) Return(arg0, arg1, arg2 string, arg3 *v6.VirtualMachineScaleSetVM, arg4 error) *MockVMSetEnsureHostInPoolCall { + c.Call = c.Call.Return(arg0, arg1, arg2, arg3, arg4) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetEnsureHostInPoolCall) Do(f func(context.Context, *v1.Service, types.NodeName, string, string) (string, string, string, *v6.VirtualMachineScaleSetVM, error)) *MockVMSetEnsureHostInPoolCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetEnsureHostInPoolCall) DoAndReturn(f func(context.Context, *v1.Service, types.NodeName, string, string) (string, string, string, *v6.VirtualMachineScaleSetVM, error)) *MockVMSetEnsureHostInPoolCall { + c.Call = c.Call.DoAndReturn(f) + return c } // EnsureHostsInPool mocks base method. @@ -161,40 +305,112 @@ func (m *MockVMSet) EnsureHostsInPool(ctx context.Context, service *v1.Service, } // EnsureHostsInPool indicates an expected call of EnsureHostsInPool. -func (mr *MockVMSetMockRecorder) EnsureHostsInPool(ctx, service, nodes, backendPoolID, vmSetName any) *gomock.Call { +func (mr *MockVMSetMockRecorder) EnsureHostsInPool(ctx, service, nodes, backendPoolID, vmSetName any) *MockVMSetEnsureHostsInPoolCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureHostsInPool", reflect.TypeOf((*MockVMSet)(nil).EnsureHostsInPool), ctx, service, nodes, backendPoolID, vmSetName) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnsureHostsInPool", reflect.TypeOf((*MockVMSet)(nil).EnsureHostsInPool), ctx, service, nodes, backendPoolID, vmSetName) + return &MockVMSetEnsureHostsInPoolCall{Call: call} +} + +// MockVMSetEnsureHostsInPoolCall wrap *gomock.Call +type MockVMSetEnsureHostsInPoolCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetEnsureHostsInPoolCall) Return(arg0 error) *MockVMSetEnsureHostsInPoolCall { + c.Call = c.Call.Return(arg0) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetEnsureHostsInPoolCall) Do(f func(context.Context, *v1.Service, []*v1.Node, string, string) error) *MockVMSetEnsureHostsInPoolCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetEnsureHostsInPoolCall) DoAndReturn(f func(context.Context, *v1.Service, []*v1.Node, string, string) error) *MockVMSetEnsureHostsInPoolCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetAgentPoolVMSetNames mocks base method. -func (m *MockVMSet) GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1.Node) (*[]string, error) { +func (m *MockVMSet) GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1.Node) ([]*string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAgentPoolVMSetNames", ctx, nodes) - ret0, _ := ret[0].(*[]string) + ret0, _ := ret[0].([]*string) ret1, _ := ret[1].(error) return ret0, ret1 } // GetAgentPoolVMSetNames indicates an expected call of GetAgentPoolVMSetNames. -func (mr *MockVMSetMockRecorder) GetAgentPoolVMSetNames(ctx, nodes any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetAgentPoolVMSetNames(ctx, nodes any) *MockVMSetGetAgentPoolVMSetNamesCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAgentPoolVMSetNames", reflect.TypeOf((*MockVMSet)(nil).GetAgentPoolVMSetNames), ctx, nodes) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAgentPoolVMSetNames", reflect.TypeOf((*MockVMSet)(nil).GetAgentPoolVMSetNames), ctx, nodes) + return &MockVMSetGetAgentPoolVMSetNamesCall{Call: call} +} + +// MockVMSetGetAgentPoolVMSetNamesCall wrap *gomock.Call +type MockVMSetGetAgentPoolVMSetNamesCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetAgentPoolVMSetNamesCall) Return(arg0 []*string, arg1 error) *MockVMSetGetAgentPoolVMSetNamesCall { + c.Call = c.Call.Return(arg0, arg1) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetAgentPoolVMSetNamesCall) Do(f func(context.Context, []*v1.Node) ([]*string, error)) *MockVMSetGetAgentPoolVMSetNamesCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetAgentPoolVMSetNamesCall) DoAndReturn(f func(context.Context, []*v1.Node) ([]*string, error)) *MockVMSetGetAgentPoolVMSetNamesCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetDataDisks mocks base method. -func (m *MockVMSet) GetDataDisks(ctx context.Context, nodeName types.NodeName, crt cache.AzureCacheReadType) ([]*armcompute.DataDisk, *string, error) { +func (m *MockVMSet) GetDataDisks(ctx context.Context, nodeName types.NodeName, crt cache.AzureCacheReadType) ([]*v6.DataDisk, *string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetDataDisks", ctx, nodeName, crt) - ret0, _ := ret[0].([]*armcompute.DataDisk) + ret0, _ := ret[0].([]*v6.DataDisk) ret1, _ := ret[1].(*string) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // GetDataDisks indicates an expected call of GetDataDisks. -func (mr *MockVMSetMockRecorder) GetDataDisks(ctx, nodeName, crt any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetDataDisks(ctx, nodeName, crt any) *MockVMSetGetDataDisksCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDataDisks", reflect.TypeOf((*MockVMSet)(nil).GetDataDisks), ctx, nodeName, crt) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDataDisks", reflect.TypeOf((*MockVMSet)(nil).GetDataDisks), ctx, nodeName, crt) + return &MockVMSetGetDataDisksCall{Call: call} +} + +// MockVMSetGetDataDisksCall wrap *gomock.Call +type MockVMSetGetDataDisksCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetDataDisksCall) Return(arg0 []*v6.DataDisk, arg1 *string, arg2 error) *MockVMSetGetDataDisksCall { + c.Call = c.Call.Return(arg0, arg1, arg2) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetDataDisksCall) Do(f func(context.Context, types.NodeName, cache.AzureCacheReadType) ([]*v6.DataDisk, *string, error)) *MockVMSetGetDataDisksCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetDataDisksCall) DoAndReturn(f func(context.Context, types.NodeName, cache.AzureCacheReadType) ([]*v6.DataDisk, *string, error)) *MockVMSetGetDataDisksCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetIPByNodeName mocks base method. @@ -208,9 +424,33 @@ func (m *MockVMSet) GetIPByNodeName(ctx context.Context, name string) (string, s } // GetIPByNodeName indicates an expected call of GetIPByNodeName. -func (mr *MockVMSetMockRecorder) GetIPByNodeName(ctx, name any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetIPByNodeName(ctx, name any) *MockVMSetGetIPByNodeNameCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetIPByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetIPByNodeName), ctx, name) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetIPByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetIPByNodeName), ctx, name) + return &MockVMSetGetIPByNodeNameCall{Call: call} +} + +// MockVMSetGetIPByNodeNameCall wrap *gomock.Call +type MockVMSetGetIPByNodeNameCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetIPByNodeNameCall) Return(arg0, arg1 string, arg2 error) *MockVMSetGetIPByNodeNameCall { + c.Call = c.Call.Return(arg0, arg1, arg2) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetIPByNodeNameCall) Do(f func(context.Context, string) (string, string, error)) *MockVMSetGetIPByNodeNameCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetIPByNodeNameCall) DoAndReturn(f func(context.Context, string) (string, string, error)) *MockVMSetGetIPByNodeNameCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetInstanceIDByNodeName mocks base method. @@ -223,9 +463,33 @@ func (m *MockVMSet) GetInstanceIDByNodeName(ctx context.Context, name string) (s } // GetInstanceIDByNodeName indicates an expected call of GetInstanceIDByNodeName. -func (mr *MockVMSetMockRecorder) GetInstanceIDByNodeName(ctx, name any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetInstanceIDByNodeName(ctx, name any) *MockVMSetGetInstanceIDByNodeNameCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstanceIDByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetInstanceIDByNodeName), ctx, name) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstanceIDByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetInstanceIDByNodeName), ctx, name) + return &MockVMSetGetInstanceIDByNodeNameCall{Call: call} +} + +// MockVMSetGetInstanceIDByNodeNameCall wrap *gomock.Call +type MockVMSetGetInstanceIDByNodeNameCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetInstanceIDByNodeNameCall) Return(arg0 string, arg1 error) *MockVMSetGetInstanceIDByNodeNameCall { + c.Call = c.Call.Return(arg0, arg1) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetInstanceIDByNodeNameCall) Do(f func(context.Context, string) (string, error)) *MockVMSetGetInstanceIDByNodeNameCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetInstanceIDByNodeNameCall) DoAndReturn(f func(context.Context, string) (string, error)) *MockVMSetGetInstanceIDByNodeNameCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetInstanceTypeByNodeName mocks base method. @@ -238,9 +502,33 @@ func (m *MockVMSet) GetInstanceTypeByNodeName(ctx context.Context, name string) } // GetInstanceTypeByNodeName indicates an expected call of GetInstanceTypeByNodeName. -func (mr *MockVMSetMockRecorder) GetInstanceTypeByNodeName(ctx, name any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetInstanceTypeByNodeName(ctx, name any) *MockVMSetGetInstanceTypeByNodeNameCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstanceTypeByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetInstanceTypeByNodeName), ctx, name) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstanceTypeByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetInstanceTypeByNodeName), ctx, name) + return &MockVMSetGetInstanceTypeByNodeNameCall{Call: call} +} + +// MockVMSetGetInstanceTypeByNodeNameCall wrap *gomock.Call +type MockVMSetGetInstanceTypeByNodeNameCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetInstanceTypeByNodeNameCall) Return(arg0 string, arg1 error) *MockVMSetGetInstanceTypeByNodeNameCall { + c.Call = c.Call.Return(arg0, arg1) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetInstanceTypeByNodeNameCall) Do(f func(context.Context, string) (string, error)) *MockVMSetGetInstanceTypeByNodeNameCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetInstanceTypeByNodeNameCall) DoAndReturn(f func(context.Context, string) (string, error)) *MockVMSetGetInstanceTypeByNodeNameCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetNodeCIDRMasksByProviderID mocks base method. @@ -254,9 +542,33 @@ func (m *MockVMSet) GetNodeCIDRMasksByProviderID(ctx context.Context, providerID } // GetNodeCIDRMasksByProviderID indicates an expected call of GetNodeCIDRMasksByProviderID. -func (mr *MockVMSetMockRecorder) GetNodeCIDRMasksByProviderID(ctx, providerID any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetNodeCIDRMasksByProviderID(ctx, providerID any) *MockVMSetGetNodeCIDRMasksByProviderIDCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNodeCIDRMasksByProviderID", reflect.TypeOf((*MockVMSet)(nil).GetNodeCIDRMasksByProviderID), ctx, providerID) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNodeCIDRMasksByProviderID", reflect.TypeOf((*MockVMSet)(nil).GetNodeCIDRMasksByProviderID), ctx, providerID) + return &MockVMSetGetNodeCIDRMasksByProviderIDCall{Call: call} +} + +// MockVMSetGetNodeCIDRMasksByProviderIDCall wrap *gomock.Call +type MockVMSetGetNodeCIDRMasksByProviderIDCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetNodeCIDRMasksByProviderIDCall) Return(arg0, arg1 int, arg2 error) *MockVMSetGetNodeCIDRMasksByProviderIDCall { + c.Call = c.Call.Return(arg0, arg1, arg2) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetNodeCIDRMasksByProviderIDCall) Do(f func(context.Context, string) (int, int, error)) *MockVMSetGetNodeCIDRMasksByProviderIDCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetNodeCIDRMasksByProviderIDCall) DoAndReturn(f func(context.Context, string) (int, int, error)) *MockVMSetGetNodeCIDRMasksByProviderIDCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetNodeNameByIPConfigurationID mocks base method. @@ -270,9 +582,33 @@ func (m *MockVMSet) GetNodeNameByIPConfigurationID(ctx context.Context, ipConfig } // GetNodeNameByIPConfigurationID indicates an expected call of GetNodeNameByIPConfigurationID. -func (mr *MockVMSetMockRecorder) GetNodeNameByIPConfigurationID(ctx, ipConfigurationID any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetNodeNameByIPConfigurationID(ctx, ipConfigurationID any) *MockVMSetGetNodeNameByIPConfigurationIDCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNodeNameByIPConfigurationID", reflect.TypeOf((*MockVMSet)(nil).GetNodeNameByIPConfigurationID), ctx, ipConfigurationID) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNodeNameByIPConfigurationID", reflect.TypeOf((*MockVMSet)(nil).GetNodeNameByIPConfigurationID), ctx, ipConfigurationID) + return &MockVMSetGetNodeNameByIPConfigurationIDCall{Call: call} +} + +// MockVMSetGetNodeNameByIPConfigurationIDCall wrap *gomock.Call +type MockVMSetGetNodeNameByIPConfigurationIDCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetNodeNameByIPConfigurationIDCall) Return(arg0, arg1 string, arg2 error) *MockVMSetGetNodeNameByIPConfigurationIDCall { + c.Call = c.Call.Return(arg0, arg1, arg2) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetNodeNameByIPConfigurationIDCall) Do(f func(context.Context, string) (string, string, error)) *MockVMSetGetNodeNameByIPConfigurationIDCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetNodeNameByIPConfigurationIDCall) DoAndReturn(f func(context.Context, string) (string, string, error)) *MockVMSetGetNodeNameByIPConfigurationIDCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetNodeNameByProviderID mocks base method. @@ -285,9 +621,33 @@ func (m *MockVMSet) GetNodeNameByProviderID(ctx context.Context, providerID stri } // GetNodeNameByProviderID indicates an expected call of GetNodeNameByProviderID. -func (mr *MockVMSetMockRecorder) GetNodeNameByProviderID(ctx, providerID any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetNodeNameByProviderID(ctx, providerID any) *MockVMSetGetNodeNameByProviderIDCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNodeNameByProviderID", reflect.TypeOf((*MockVMSet)(nil).GetNodeNameByProviderID), ctx, providerID) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNodeNameByProviderID", reflect.TypeOf((*MockVMSet)(nil).GetNodeNameByProviderID), ctx, providerID) + return &MockVMSetGetNodeNameByProviderIDCall{Call: call} +} + +// MockVMSetGetNodeNameByProviderIDCall wrap *gomock.Call +type MockVMSetGetNodeNameByProviderIDCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetNodeNameByProviderIDCall) Return(arg0 types.NodeName, arg1 error) *MockVMSetGetNodeNameByProviderIDCall { + c.Call = c.Call.Return(arg0, arg1) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetNodeNameByProviderIDCall) Do(f func(context.Context, string) (types.NodeName, error)) *MockVMSetGetNodeNameByProviderIDCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetNodeNameByProviderIDCall) DoAndReturn(f func(context.Context, string) (types.NodeName, error)) *MockVMSetGetNodeNameByProviderIDCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetNodeVMSetName mocks base method. @@ -300,9 +660,33 @@ func (m *MockVMSet) GetNodeVMSetName(ctx context.Context, node *v1.Node) (string } // GetNodeVMSetName indicates an expected call of GetNodeVMSetName. -func (mr *MockVMSetMockRecorder) GetNodeVMSetName(ctx, node any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetNodeVMSetName(ctx, node any) *MockVMSetGetNodeVMSetNameCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNodeVMSetName", reflect.TypeOf((*MockVMSet)(nil).GetNodeVMSetName), ctx, node) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNodeVMSetName", reflect.TypeOf((*MockVMSet)(nil).GetNodeVMSetName), ctx, node) + return &MockVMSetGetNodeVMSetNameCall{Call: call} +} + +// MockVMSetGetNodeVMSetNameCall wrap *gomock.Call +type MockVMSetGetNodeVMSetNameCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetNodeVMSetNameCall) Return(arg0 string, arg1 error) *MockVMSetGetNodeVMSetNameCall { + c.Call = c.Call.Return(arg0, arg1) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetNodeVMSetNameCall) Do(f func(context.Context, *v1.Node) (string, error)) *MockVMSetGetNodeVMSetNameCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetNodeVMSetNameCall) DoAndReturn(f func(context.Context, *v1.Node) (string, error)) *MockVMSetGetNodeVMSetNameCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetPowerStatusByNodeName mocks base method. @@ -315,24 +699,72 @@ func (m *MockVMSet) GetPowerStatusByNodeName(ctx context.Context, name string) ( } // GetPowerStatusByNodeName indicates an expected call of GetPowerStatusByNodeName. -func (mr *MockVMSetMockRecorder) GetPowerStatusByNodeName(ctx, name any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetPowerStatusByNodeName(ctx, name any) *MockVMSetGetPowerStatusByNodeNameCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPowerStatusByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetPowerStatusByNodeName), ctx, name) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPowerStatusByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetPowerStatusByNodeName), ctx, name) + return &MockVMSetGetPowerStatusByNodeNameCall{Call: call} +} + +// MockVMSetGetPowerStatusByNodeNameCall wrap *gomock.Call +type MockVMSetGetPowerStatusByNodeNameCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetPowerStatusByNodeNameCall) Return(arg0 string, arg1 error) *MockVMSetGetPowerStatusByNodeNameCall { + c.Call = c.Call.Return(arg0, arg1) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetPowerStatusByNodeNameCall) Do(f func(context.Context, string) (string, error)) *MockVMSetGetPowerStatusByNodeNameCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetPowerStatusByNodeNameCall) DoAndReturn(f func(context.Context, string) (string, error)) *MockVMSetGetPowerStatusByNodeNameCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetPrimaryInterface mocks base method. -func (m *MockVMSet) GetPrimaryInterface(ctx context.Context, nodeName string) (network.Interface, error) { +func (m *MockVMSet) GetPrimaryInterface(ctx context.Context, nodeName string) (*v60.Interface, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetPrimaryInterface", ctx, nodeName) - ret0, _ := ret[0].(network.Interface) + ret0, _ := ret[0].(*v60.Interface) ret1, _ := ret[1].(error) return ret0, ret1 } // GetPrimaryInterface indicates an expected call of GetPrimaryInterface. -func (mr *MockVMSetMockRecorder) GetPrimaryInterface(ctx, nodeName any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetPrimaryInterface(ctx, nodeName any) *MockVMSetGetPrimaryInterfaceCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPrimaryInterface", reflect.TypeOf((*MockVMSet)(nil).GetPrimaryInterface), ctx, nodeName) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPrimaryInterface", reflect.TypeOf((*MockVMSet)(nil).GetPrimaryInterface), ctx, nodeName) + return &MockVMSetGetPrimaryInterfaceCall{Call: call} +} + +// MockVMSetGetPrimaryInterfaceCall wrap *gomock.Call +type MockVMSetGetPrimaryInterfaceCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetPrimaryInterfaceCall) Return(arg0 *v60.Interface, arg1 error) *MockVMSetGetPrimaryInterfaceCall { + c.Call = c.Call.Return(arg0, arg1) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetPrimaryInterfaceCall) Do(f func(context.Context, string) (*v60.Interface, error)) *MockVMSetGetPrimaryInterfaceCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetPrimaryInterfaceCall) DoAndReturn(f func(context.Context, string) (*v60.Interface, error)) *MockVMSetGetPrimaryInterfaceCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetPrimaryVMSetName mocks base method. @@ -344,9 +776,33 @@ func (m *MockVMSet) GetPrimaryVMSetName() string { } // GetPrimaryVMSetName indicates an expected call of GetPrimaryVMSetName. -func (mr *MockVMSetMockRecorder) GetPrimaryVMSetName() *gomock.Call { +func (mr *MockVMSetMockRecorder) GetPrimaryVMSetName() *MockVMSetGetPrimaryVMSetNameCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPrimaryVMSetName", reflect.TypeOf((*MockVMSet)(nil).GetPrimaryVMSetName)) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPrimaryVMSetName", reflect.TypeOf((*MockVMSet)(nil).GetPrimaryVMSetName)) + return &MockVMSetGetPrimaryVMSetNameCall{Call: call} +} + +// MockVMSetGetPrimaryVMSetNameCall wrap *gomock.Call +type MockVMSetGetPrimaryVMSetNameCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetPrimaryVMSetNameCall) Return(arg0 string) *MockVMSetGetPrimaryVMSetNameCall { + c.Call = c.Call.Return(arg0) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetPrimaryVMSetNameCall) Do(f func() string) *MockVMSetGetPrimaryVMSetNameCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetPrimaryVMSetNameCall) DoAndReturn(f func() string) *MockVMSetGetPrimaryVMSetNameCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetPrivateIPsByNodeName mocks base method. @@ -359,9 +815,33 @@ func (m *MockVMSet) GetPrivateIPsByNodeName(ctx context.Context, name string) ([ } // GetPrivateIPsByNodeName indicates an expected call of GetPrivateIPsByNodeName. -func (mr *MockVMSetMockRecorder) GetPrivateIPsByNodeName(ctx, name any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetPrivateIPsByNodeName(ctx, name any) *MockVMSetGetPrivateIPsByNodeNameCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPrivateIPsByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetPrivateIPsByNodeName), ctx, name) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPrivateIPsByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetPrivateIPsByNodeName), ctx, name) + return &MockVMSetGetPrivateIPsByNodeNameCall{Call: call} +} + +// MockVMSetGetPrivateIPsByNodeNameCall wrap *gomock.Call +type MockVMSetGetPrivateIPsByNodeNameCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetPrivateIPsByNodeNameCall) Return(arg0 []string, arg1 error) *MockVMSetGetPrivateIPsByNodeNameCall { + c.Call = c.Call.Return(arg0, arg1) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetPrivateIPsByNodeNameCall) Do(f func(context.Context, string) ([]string, error)) *MockVMSetGetPrivateIPsByNodeNameCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetPrivateIPsByNodeNameCall) DoAndReturn(f func(context.Context, string) ([]string, error)) *MockVMSetGetPrivateIPsByNodeNameCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetProvisioningStateByNodeName mocks base method. @@ -374,39 +854,111 @@ func (m *MockVMSet) GetProvisioningStateByNodeName(ctx context.Context, name str } // GetProvisioningStateByNodeName indicates an expected call of GetProvisioningStateByNodeName. -func (mr *MockVMSetMockRecorder) GetProvisioningStateByNodeName(ctx, name any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetProvisioningStateByNodeName(ctx, name any) *MockVMSetGetProvisioningStateByNodeNameCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProvisioningStateByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetProvisioningStateByNodeName), ctx, name) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProvisioningStateByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetProvisioningStateByNodeName), ctx, name) + return &MockVMSetGetProvisioningStateByNodeNameCall{Call: call} +} + +// MockVMSetGetProvisioningStateByNodeNameCall wrap *gomock.Call +type MockVMSetGetProvisioningStateByNodeNameCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetProvisioningStateByNodeNameCall) Return(arg0 string, arg1 error) *MockVMSetGetProvisioningStateByNodeNameCall { + c.Call = c.Call.Return(arg0, arg1) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetProvisioningStateByNodeNameCall) Do(f func(context.Context, string) (string, error)) *MockVMSetGetProvisioningStateByNodeNameCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetProvisioningStateByNodeNameCall) DoAndReturn(f func(context.Context, string) (string, error)) *MockVMSetGetProvisioningStateByNodeNameCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetVMSetNames mocks base method. -func (m *MockVMSet) GetVMSetNames(ctx context.Context, service *v1.Service, nodes []*v1.Node) (*[]string, error) { +func (m *MockVMSet) GetVMSetNames(ctx context.Context, service *v1.Service, nodes []*v1.Node) ([]*string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetVMSetNames", ctx, service, nodes) - ret0, _ := ret[0].(*[]string) + ret0, _ := ret[0].([]*string) ret1, _ := ret[1].(error) return ret0, ret1 } // GetVMSetNames indicates an expected call of GetVMSetNames. -func (mr *MockVMSetMockRecorder) GetVMSetNames(ctx, service, nodes any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetVMSetNames(ctx, service, nodes any) *MockVMSetGetVMSetNamesCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetVMSetNames", reflect.TypeOf((*MockVMSet)(nil).GetVMSetNames), ctx, service, nodes) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetVMSetNames", reflect.TypeOf((*MockVMSet)(nil).GetVMSetNames), ctx, service, nodes) + return &MockVMSetGetVMSetNamesCall{Call: call} +} + +// MockVMSetGetVMSetNamesCall wrap *gomock.Call +type MockVMSetGetVMSetNamesCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetVMSetNamesCall) Return(availabilitySetNames []*string, err error) *MockVMSetGetVMSetNamesCall { + c.Call = c.Call.Return(availabilitySetNames, err) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetVMSetNamesCall) Do(f func(context.Context, *v1.Service, []*v1.Node) ([]*string, error)) *MockVMSetGetVMSetNamesCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetVMSetNamesCall) DoAndReturn(f func(context.Context, *v1.Service, []*v1.Node) ([]*string, error)) *MockVMSetGetVMSetNamesCall { + c.Call = c.Call.DoAndReturn(f) + return c } // GetZoneByNodeName mocks base method. -func (m *MockVMSet) GetZoneByNodeName(ctx context.Context, name string) (cloudprovider.Zone, error) { +func (m *MockVMSet) GetZoneByNodeName(ctx context.Context, name string) (cloud_provider.Zone, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetZoneByNodeName", ctx, name) - ret0, _ := ret[0].(cloudprovider.Zone) + ret0, _ := ret[0].(cloud_provider.Zone) ret1, _ := ret[1].(error) return ret0, ret1 } // GetZoneByNodeName indicates an expected call of GetZoneByNodeName. -func (mr *MockVMSetMockRecorder) GetZoneByNodeName(ctx, name any) *gomock.Call { +func (mr *MockVMSetMockRecorder) GetZoneByNodeName(ctx, name any) *MockVMSetGetZoneByNodeNameCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetZoneByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetZoneByNodeName), ctx, name) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetZoneByNodeName", reflect.TypeOf((*MockVMSet)(nil).GetZoneByNodeName), ctx, name) + return &MockVMSetGetZoneByNodeNameCall{Call: call} +} + +// MockVMSetGetZoneByNodeNameCall wrap *gomock.Call +type MockVMSetGetZoneByNodeNameCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetGetZoneByNodeNameCall) Return(arg0 cloud_provider.Zone, arg1 error) *MockVMSetGetZoneByNodeNameCall { + c.Call = c.Call.Return(arg0, arg1) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetGetZoneByNodeNameCall) Do(f func(context.Context, string) (cloud_provider.Zone, error)) *MockVMSetGetZoneByNodeNameCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetGetZoneByNodeNameCall) DoAndReturn(f func(context.Context, string) (cloud_provider.Zone, error)) *MockVMSetGetZoneByNodeNameCall { + c.Call = c.Call.DoAndReturn(f) + return c } // RefreshCaches mocks base method. @@ -418,9 +970,33 @@ func (m *MockVMSet) RefreshCaches() error { } // RefreshCaches indicates an expected call of RefreshCaches. -func (mr *MockVMSetMockRecorder) RefreshCaches() *gomock.Call { +func (mr *MockVMSetMockRecorder) RefreshCaches() *MockVMSetRefreshCachesCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RefreshCaches", reflect.TypeOf((*MockVMSet)(nil).RefreshCaches)) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RefreshCaches", reflect.TypeOf((*MockVMSet)(nil).RefreshCaches)) + return &MockVMSetRefreshCachesCall{Call: call} +} + +// MockVMSetRefreshCachesCall wrap *gomock.Call +type MockVMSetRefreshCachesCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetRefreshCachesCall) Return(arg0 error) *MockVMSetRefreshCachesCall { + c.Call = c.Call.Return(arg0) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetRefreshCachesCall) Do(f func() error) *MockVMSetRefreshCachesCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetRefreshCachesCall) DoAndReturn(f func() error) *MockVMSetRefreshCachesCall { + c.Call = c.Call.DoAndReturn(f) + return c } // UpdateVM mocks base method. @@ -432,7 +1008,31 @@ func (m *MockVMSet) UpdateVM(ctx context.Context, nodeName types.NodeName) error } // UpdateVM indicates an expected call of UpdateVM. -func (mr *MockVMSetMockRecorder) UpdateVM(ctx, nodeName any) *gomock.Call { +func (mr *MockVMSetMockRecorder) UpdateVM(ctx, nodeName any) *MockVMSetUpdateVMCall { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateVM", reflect.TypeOf((*MockVMSet)(nil).UpdateVM), ctx, nodeName) + call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateVM", reflect.TypeOf((*MockVMSet)(nil).UpdateVM), ctx, nodeName) + return &MockVMSetUpdateVMCall{Call: call} +} + +// MockVMSetUpdateVMCall wrap *gomock.Call +type MockVMSetUpdateVMCall struct { + *gomock.Call +} + +// Return rewrite *gomock.Call.Return +func (c *MockVMSetUpdateVMCall) Return(arg0 error) *MockVMSetUpdateVMCall { + c.Call = c.Call.Return(arg0) + return c +} + +// Do rewrite *gomock.Call.Do +func (c *MockVMSetUpdateVMCall) Do(f func(context.Context, types.NodeName) error) *MockVMSetUpdateVMCall { + c.Call = c.Call.Do(f) + return c +} + +// DoAndReturn rewrite *gomock.Call.DoAndReturn +func (c *MockVMSetUpdateVMCall) DoAndReturn(f func(context.Context, types.NodeName) error) *MockVMSetUpdateVMCall { + c.Call = c.Call.DoAndReturn(f) + return c } diff --git a/pkg/provider/azure_privatelinkservice.go b/pkg/provider/azure_privatelinkservice.go index a4c386268e..08f5efc96e 100644 --- a/pkg/provider/azure_privatelinkservice.go +++ b/pkg/provider/azure_privatelinkservice.go @@ -27,7 +27,6 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" @@ -45,16 +44,16 @@ func (az *Cloud) reconcilePrivateLinkService( ctx context.Context, clusterName string, service *v1.Service, - fipConfig *network.FrontendIPConfiguration, + fipConfig *armnetwork.FrontendIPConfiguration, wantPLS bool, ) error { isinternal := requiresInternalLoadBalancer(service) - _, _, fipIPVersion := az.serviceOwnsFrontendIP(ctx, *fipConfig, service) + _, _, fipIPVersion := az.serviceOwnsFrontendIP(ctx, fipConfig, service) serviceName := getServiceName(service) var isIPv6 bool var err error - if fipIPVersion != "" { - isIPv6 = fipIPVersion == network.IPv6 + if fipIPVersion != nil { + isIPv6 = *fipIPVersion == armnetwork.IPVersionIPv6 } else { if isIPv6, err = az.isFIPIPv6(service, fipConfig); err != nil { klog.Errorf("reconcilePrivateLinkService for service(%s): failed to get FIP IP family: %v", serviceName, err) @@ -266,7 +265,7 @@ func (az *Cloud) safeDeletePLS(ctx context.Context, pls *armnetwork.PrivateLinkS func (az *Cloud) getPrivateLinkServiceName( existingPLS *armnetwork.PrivateLinkService, service *v1.Service, - fipConfig *network.FrontendIPConfiguration, + fipConfig *armnetwork.FrontendIPConfiguration, ) (string, error) { existingName := existingPLS.Name serviceName := getServiceName(service) @@ -299,7 +298,7 @@ func (az *Cloud) getExpectedPrivateLinkService( plsName *string, clusterName *string, service *v1.Service, - fipConfig *network.FrontendIPConfiguration, + fipConfig *armnetwork.FrontendIPConfiguration, ) (dirtyPLS bool, err error) { dirtyPLS = false diff --git a/pkg/provider/azure_privatelinkservice_test.go b/pkg/provider/azure_privatelinkservice_test.go index ac1202b8df..6c82927645 100644 --- a/pkg/provider/azure_privatelinkservice_test.go +++ b/pkg/provider/azure_privatelinkservice_test.go @@ -25,7 +25,6 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" v1 "k8s.io/api/core/v1" @@ -326,17 +325,17 @@ func TestReconcilePrivateLinkService(t *testing.T) { t.Run(test.desc, func(t *testing.T) { az := GetTestCloud(ctrl) service := getTestServiceWithAnnotation("test", test.annotations, false, 80) - fipConfig := &network.FrontendIPConfiguration{ + fipConfig := &armnetwork.FrontendIPConfiguration{ Name: ptr.To("fipConfig"), ID: ptr.To("fipConfigID"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("pipID"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, - PrivateIPAddressVersion: network.IPv4, + PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, } clusterName := testClusterName @@ -497,7 +496,7 @@ func TestGetPrivateLinkServiceName(t *testing.T) { desc string annotations map[string]string pls *armnetwork.PrivateLinkService - fipConfig *network.FrontendIPConfiguration + fipConfig *armnetwork.FrontendIPConfiguration expectedName string expectedErr bool }{ @@ -512,7 +511,7 @@ func TestGetPrivateLinkServiceName(t *testing.T) { { desc: "If pls name does not set, and service does not configure, sets it as default(pls-fipConfigName)", pls: &armnetwork.PrivateLinkService{}, - fipConfig: &network.FrontendIPConfiguration{ + fipConfig: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("fipname"), }, expectedName: "pls-fipname", @@ -574,7 +573,7 @@ func TestGetExpectedPrivateLinkService(t *testing.T) { } plsName := "testPLS" clusterName := testClusterName - fipConfig := &network.FrontendIPConfiguration{ID: ptr.To("fipConfigID")} + fipConfig := &armnetwork.FrontendIPConfiguration{ID: ptr.To("fipConfigID")} pls := &armnetwork.PrivateLinkService{Properties: &armnetwork.PrivateLinkServiceProperties{}} subnetClient := cloud.subnetRepo.(*subnet.MockRepository) subnetClient.EXPECT().Get(gomock.Any(), "rg", "vnet", "subnet").Return( diff --git a/pkg/provider/azure_publicip_repo.go b/pkg/provider/azure_publicip_repo.go index 8c9d4dfa03..7ce90dadbd 100644 --- a/pkg/provider/azure_publicip_repo.go +++ b/pkg/provider/azure_publicip_repo.go @@ -19,14 +19,15 @@ package provider import ( "context" "encoding/json" + "errors" "fmt" "net/http" "strings" "sync" "time" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" "k8s.io/utils/ptr" @@ -36,13 +37,13 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/util/deepcopy" ) -// CreateOrUpdatePIP invokes az.PublicIPAddressesClient.CreateOrUpdate with exponential backoff retry -func (az *Cloud) CreateOrUpdatePIP(service *v1.Service, pipResourceGroup string, pip network.PublicIPAddress) error { +// CreateOrUpdatePIP invokes az.NetworkClientFactory.GetPublicIPAddressClient().CreateOrUpdate with exponential backoff retry +func (az *Cloud) CreateOrUpdatePIP(service *v1.Service, pipResourceGroup string, pip *armnetwork.PublicIPAddress) error { ctx, cancel := getContextWithCancel() defer cancel() - rerr := az.PublicIPAddressesClient.CreateOrUpdate(ctx, pipResourceGroup, ptr.Deref(pip.Name, ""), pip) - klog.V(10).Infof("PublicIPAddressesClient.CreateOrUpdate(%s, %s): end", pipResourceGroup, ptr.Deref(pip.Name, "")) + _, rerr := az.NetworkClientFactory.GetPublicIPAddressClient().CreateOrUpdate(ctx, pipResourceGroup, ptr.Deref(pip.Name, ""), *pip) + klog.V(10).Infof("NetworkClientFactory.GetPublicIPAddressClient().CreateOrUpdate(%s, %s): end", pipResourceGroup, ptr.Deref(pip.Name, "")) if rerr == nil { // Invalidate the cache right after updating _ = az.pipCache.Delete(pipResourceGroup) @@ -50,40 +51,43 @@ func (az *Cloud) CreateOrUpdatePIP(service *v1.Service, pipResourceGroup string, } pipJSON, _ := json.Marshal(pip) - klog.Warningf("PublicIPAddressesClient.CreateOrUpdate(%s, %s) failed: %s, PublicIP request: %s", pipResourceGroup, ptr.Deref(pip.Name, ""), rerr.Error().Error(), string(pipJSON)) - az.Event(service, v1.EventTypeWarning, "CreateOrUpdatePublicIPAddress", rerr.Error().Error()) + klog.Warningf("NetworkClientFactory.GetPublicIPAddressClient().CreateOrUpdate(%s, %s) failed: %s, PublicIP request: %s", pipResourceGroup, ptr.Deref(pip.Name, ""), rerr.Error(), string(pipJSON)) + az.Event(service, v1.EventTypeWarning, "CreateOrUpdatePublicIPAddress", rerr.Error()) // Invalidate the cache because ETAG precondition mismatch. - if rerr.HTTPStatusCode == http.StatusPreconditionFailed { - klog.V(3).Infof("PublicIP cache for (%s, %s) is cleanup because of http.StatusPreconditionFailed", pipResourceGroup, ptr.Deref(pip.Name, "")) - _ = az.pipCache.Delete(pipResourceGroup) + var respError *azcore.ResponseError + if errors.As(rerr, &respError) && respError != nil { + if respError.StatusCode == http.StatusPreconditionFailed { + klog.V(3).Infof("PublicIP cache for (%s, %s) is cleanup because of http.StatusPreconditionFailed", pipResourceGroup, ptr.Deref(pip.Name, "")) + _ = az.pipCache.Delete(pipResourceGroup) + } } - retryErrorMessage := rerr.Error().Error() + retryErrorMessage := rerr.Error() // Invalidate the cache because another new operation has canceled the current request. if strings.Contains(strings.ToLower(retryErrorMessage), consts.OperationCanceledErrorMessage) { klog.V(3).Infof("PublicIP cache for (%s, %s) is cleanup because CreateOrUpdate is canceled by another operation", pipResourceGroup, ptr.Deref(pip.Name, "")) _ = az.pipCache.Delete(pipResourceGroup) } - return rerr.Error() + return rerr } -// DeletePublicIP invokes az.PublicIPAddressesClient.Delete with exponential backoff retry +// DeletePublicIP invokes az.NetworkClientFactory.GetPublicIPAddressClient().Delete with exponential backoff retry func (az *Cloud) DeletePublicIP(service *v1.Service, pipResourceGroup string, pipName string) error { ctx, cancel := getContextWithCancel() defer cancel() - rerr := az.PublicIPAddressesClient.Delete(ctx, pipResourceGroup, pipName) + rerr := az.NetworkClientFactory.GetPublicIPAddressClient().Delete(ctx, pipResourceGroup, pipName) if rerr != nil { - klog.Errorf("PublicIPAddressesClient.Delete(%s) failed: %s", pipName, rerr.Error().Error()) - az.Event(service, v1.EventTypeWarning, "DeletePublicIPAddress", rerr.Error().Error()) + klog.Errorf("NetworkClientFactory.GetPublicIPAddressClient().Delete(%s) failed: %s", pipName, rerr.Error()) + az.Event(service, v1.EventTypeWarning, "DeletePublicIPAddress", rerr.Error()) - if strings.Contains(rerr.Error().Error(), consts.CannotDeletePublicIPErrorMessageCode) { - klog.Warningf("DeletePublicIP for public IP %s failed with error %v, this is because other resources are referencing the public IP. The deletion of the service will continue.", pipName, rerr.Error()) + if strings.Contains(rerr.Error(), consts.CannotDeletePublicIPErrorMessageCode) { + klog.Warningf("DeletePublicIP for public IP %s failed with error %v, this is because other resources are referencing the public IP. The deletion of the service will continue.", pipName, rerr) return nil } - return rerr.Error() + return rerr } // Invalidate the cache right after deleting @@ -94,15 +98,15 @@ func (az *Cloud) DeletePublicIP(service *v1.Service, pipResourceGroup string, pi func (az *Cloud) newPIPCache() (azcache.Resource, error) { getter := func(ctx context.Context, key string) (interface{}, error) { pipResourceGroup := key - pipList, rerr := az.PublicIPAddressesClient.List(ctx, pipResourceGroup) + pipList, rerr := az.NetworkClientFactory.GetPublicIPAddressClient().List(ctx, pipResourceGroup) if rerr != nil { - return nil, rerr.Error() + return nil, rerr } pipMap := &sync.Map{} for _, pip := range pipList { pip := pip - pipMap.Store(strings.ToLower(ptr.Deref(pip.Name, "")), &pip) + pipMap.Store(strings.ToLower(ptr.Deref(pip.Name, "")), pip) } return pipMap, nil } @@ -113,10 +117,10 @@ func (az *Cloud) newPIPCache() (azcache.Resource, error) { return azcache.NewTimedCache(time.Duration(az.PublicIPCacheTTLInSeconds)*time.Second, getter, az.Config.DisableAPICallCache) } -func (az *Cloud) getPublicIPAddress(ctx context.Context, pipResourceGroup string, pipName string, crt azcache.AzureCacheReadType) (network.PublicIPAddress, bool, error) { +func (az *Cloud) getPublicIPAddress(ctx context.Context, pipResourceGroup string, pipName string, crt azcache.AzureCacheReadType) (*armnetwork.PublicIPAddress, bool, error) { cached, err := az.pipCache.Get(ctx, pipResourceGroup, crt) if err != nil { - return network.PublicIPAddress{}, false, err + return nil, false, err } pips := cached.(*sync.Map) @@ -125,42 +129,42 @@ func (az *Cloud) getPublicIPAddress(ctx context.Context, pipResourceGroup string // pip not found, refresh cache and retry cached, err = az.pipCache.Get(ctx, pipResourceGroup, azcache.CacheReadTypeForceRefresh) if err != nil { - return network.PublicIPAddress{}, false, err + return nil, false, err } pips = cached.(*sync.Map) pip, ok = pips.Load(strings.ToLower(pipName)) if !ok { - return network.PublicIPAddress{}, false, nil + return nil, false, nil } } - pip = pip.(*network.PublicIPAddress) - return *(deepcopy.Copy(pip).(*network.PublicIPAddress)), true, nil + pip = pip.(*armnetwork.PublicIPAddress) + return (deepcopy.Copy(pip).(*armnetwork.PublicIPAddress)), true, nil } -func (az *Cloud) listPIP(ctx context.Context, pipResourceGroup string, crt azcache.AzureCacheReadType) ([]network.PublicIPAddress, error) { +func (az *Cloud) listPIP(ctx context.Context, pipResourceGroup string, crt azcache.AzureCacheReadType) ([]*armnetwork.PublicIPAddress, error) { cached, err := az.pipCache.Get(ctx, pipResourceGroup, crt) if err != nil { return nil, err } pips := cached.(*sync.Map) - var ret []network.PublicIPAddress + var ret []*armnetwork.PublicIPAddress pips.Range(func(_, value interface{}) bool { - pip := value.(*network.PublicIPAddress) - ret = append(ret, *pip) + pip := value.(*armnetwork.PublicIPAddress) + ret = append(ret, pip) return true }) return ret, nil } -func (az *Cloud) findMatchedPIP(ctx context.Context, loadBalancerIP, pipName, pipResourceGroup string) (pip *network.PublicIPAddress, err error) { +func (az *Cloud) findMatchedPIP(ctx context.Context, loadBalancerIP, pipName, pipResourceGroup string) (pip *armnetwork.PublicIPAddress, err error) { pips, err := az.listPIP(ctx, pipResourceGroup, azcache.CacheReadTypeDefault) if err != nil { return nil, fmt.Errorf("findMatchedPIPByLoadBalancerIP: failed to listPIP: %w", err) } if loadBalancerIP != "" { - pip, err = az.findMatchedPIPByLoadBalancerIP(ctx, &pips, loadBalancerIP, pipResourceGroup) + pip, err = az.findMatchedPIPByLoadBalancerIP(ctx, pips, loadBalancerIP, pipResourceGroup) if err != nil { return nil, err } @@ -168,7 +172,7 @@ func (az *Cloud) findMatchedPIP(ctx context.Context, loadBalancerIP, pipName, pi } if pipResourceGroup != "" { - pip, err = az.findMatchedPIPByName(ctx, &pips, pipName, pipResourceGroup) + pip, err = az.findMatchedPIPByName(ctx, pips, pipName, pipResourceGroup) if err != nil { return nil, err } @@ -176,10 +180,10 @@ func (az *Cloud) findMatchedPIP(ctx context.Context, loadBalancerIP, pipName, pi return pip, nil } -func (az *Cloud) findMatchedPIPByName(ctx context.Context, pips *[]network.PublicIPAddress, pipName, pipResourceGroup string) (*network.PublicIPAddress, error) { - for _, pip := range *pips { +func (az *Cloud) findMatchedPIPByName(ctx context.Context, pips []*armnetwork.PublicIPAddress, pipName, pipResourceGroup string) (*armnetwork.PublicIPAddress, error) { + for _, pip := range pips { if strings.EqualFold(ptr.Deref(pip.Name, ""), pipName) { - return &pip, nil + return pip, nil } } @@ -189,15 +193,15 @@ func (az *Cloud) findMatchedPIPByName(ctx context.Context, pips *[]network.Publi } for _, pip := range pipList { if strings.EqualFold(ptr.Deref(pip.Name, ""), pipName) { - return &pip, nil + return pip, nil } } return nil, fmt.Errorf("findMatchedPIPByName: failed to find PIP %s in resource group %s", pipName, pipResourceGroup) } -func (az *Cloud) findMatchedPIPByLoadBalancerIP(ctx context.Context, pips *[]network.PublicIPAddress, loadBalancerIP, pipResourceGroup string) (*network.PublicIPAddress, error) { - pip, err := getExpectedPIPFromListByIPAddress(*pips, loadBalancerIP) +func (az *Cloud) findMatchedPIPByLoadBalancerIP(ctx context.Context, pips []*armnetwork.PublicIPAddress, loadBalancerIP, pipResourceGroup string) (*armnetwork.PublicIPAddress, error) { + pip, err := getExpectedPIPFromListByIPAddress(pips, loadBalancerIP) if err != nil { pipList, err := az.listPIP(ctx, pipResourceGroup, azcache.CacheReadTypeForceRefresh) if err != nil { @@ -213,11 +217,11 @@ func (az *Cloud) findMatchedPIPByLoadBalancerIP(ctx context.Context, pips *[]net return pip, nil } -func getExpectedPIPFromListByIPAddress(pips []network.PublicIPAddress, ip string) (*network.PublicIPAddress, error) { +func getExpectedPIPFromListByIPAddress(pips []*armnetwork.PublicIPAddress, ip string) (*armnetwork.PublicIPAddress, error) { for _, pip := range pips { - if pip.PublicIPAddressPropertiesFormat.IPAddress != nil && - *pip.PublicIPAddressPropertiesFormat.IPAddress == ip { - return &pip, nil + if pip.Properties.IPAddress != nil && + *pip.Properties.IPAddress == ip { + return pip, nil } } diff --git a/pkg/provider/azure_publicip_repo_test.go b/pkg/provider/azure_publicip_repo_test.go index 58cdb3eedd..a12b4c34e1 100644 --- a/pkg/provider/azure_publicip_repo_test.go +++ b/pkg/provider/azure_publicip_repo_test.go @@ -24,7 +24,8 @@ import ( "sync" "testing" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -32,11 +33,10 @@ import ( v1 "k8s.io/api/core/v1" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipaddressclient/mock_publicipaddressclient" "sigs.k8s.io/cloud-provider-azure/pkg/cache" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) func TestCreateOrUpdatePIP(t *testing.T) { @@ -44,38 +44,38 @@ func TestCreateOrUpdatePIP(t *testing.T) { defer ctrl.Finish() tests := []struct { - clientErr *retry.Error + clientErr error expectedErr error cacheExpectedEmpty bool }{ { - clientErr: &retry.Error{HTTPStatusCode: http.StatusPreconditionFailed}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 412, RawError: %w", error(nil)), + clientErr: &azcore.ResponseError{StatusCode: http.StatusPreconditionFailed}, + expectedErr: fmt.Errorf("UNAVAILABLE"), cacheExpectedEmpty: true, }, { - clientErr: &retry.Error{RawError: fmt.Errorf(consts.OperationCanceledErrorMessage)}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", fmt.Errorf("canceledandsupersededduetoanotheroperation")), + clientErr: &azcore.ResponseError{ErrorCode: consts.OperationCanceledErrorMessage}, + expectedErr: fmt.Errorf("canceledandsupersededduetoanotheroperation"), cacheExpectedEmpty: true, }, { - clientErr: &retry.Error{HTTPStatusCode: http.StatusInternalServerError}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil)), + clientErr: &azcore.ResponseError{StatusCode: http.StatusInternalServerError}, + expectedErr: fmt.Errorf("UNAVAILABLE"), cacheExpectedEmpty: false, }, } for _, test := range tests { az := GetTestCloud(ctrl) - az.pipCache.Set(az.ResourceGroup, []network.PublicIPAddress{{Name: ptr.To("test")}}) - mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) - mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(test.clientErr) + az.pipCache.Set(az.ResourceGroup, []*armnetwork.PublicIPAddress{{Name: ptr.To("test")}}) + mockPIPClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(nil, test.clientErr) if test.cacheExpectedEmpty { - mockPIPClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]network.PublicIPAddress{}, nil) + mockPIPClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]*armnetwork.PublicIPAddress{}, nil) } - err := az.CreateOrUpdatePIP(&v1.Service{}, az.ResourceGroup, network.PublicIPAddress{Name: ptr.To("nic")}) - assert.EqualError(t, test.expectedErr, err.Error()) + err := az.CreateOrUpdatePIP(&v1.Service{}, az.ResourceGroup, &armnetwork.PublicIPAddress{Name: ptr.To("nic")}) + assert.Contains(t, err.Error(), test.expectedErr.Error()) cachedPIP, err := az.pipCache.GetWithDeepCopy(context.TODO(), az.ResourceGroup, cache.CacheReadTypeDefault) assert.NoError(t, err) @@ -92,30 +92,27 @@ func TestDeletePublicIP(t *testing.T) { defer ctrl.Finish() az := GetTestCloud(ctrl) - mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) - mockPIPClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, "pip").Return(&retry.Error{HTTPStatusCode: http.StatusInternalServerError}) + mockPIPClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + mockPIPClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, "pip").Return(&azcore.ResponseError{StatusCode: http.StatusInternalServerError}) err := az.DeletePublicIP(&v1.Service{}, az.ResourceGroup, "pip") - assert.EqualError(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil)), err.Error()) + assert.Contains(t, err.Error(), "UNAVAILABLE") } func TestListPIP(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - tests := []struct { desc string - pipCache []network.PublicIPAddress + pipCache []*armnetwork.PublicIPAddress expectPIPList bool - existingPIPs []network.PublicIPAddress + existingPIPs []*armnetwork.PublicIPAddress }{ { desc: "listPIP should return data from cache, when data is empty slice", - pipCache: []network.PublicIPAddress{}, + pipCache: []*armnetwork.PublicIPAddress{}, }, { desc: "listPIP should return data from cache", - pipCache: []network.PublicIPAddress{ + pipCache: []*armnetwork.PublicIPAddress{ {Name: ptr.To("pip1")}, {Name: ptr.To("pip2")}, }, @@ -123,21 +120,23 @@ func TestListPIP(t *testing.T) { { desc: "listPIP should return data from arm list call", expectPIPList: true, - existingPIPs: []network.PublicIPAddress{{Name: ptr.To("pip")}}, + existingPIPs: []*armnetwork.PublicIPAddress{{Name: ptr.To("pip")}}, }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() az := GetTestCloud(ctrl) if test.pipCache != nil { pipCache := &sync.Map{} for _, pip := range test.pipCache { pip := pip - pipCache.Store(ptr.Deref(pip.Name, ""), &pip) + pipCache.Store(ptr.Deref(pip.Name, ""), pip) } az.pipCache.Set(az.ResourceGroup, pipCache) } - mockPIPsClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) if test.expectPIPList { mockPIPsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(test.existingPIPs, nil).MaxTimes(2) } @@ -153,57 +152,59 @@ func TestListPIP(t *testing.T) { } func TestGetPublicIPAddress(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() tests := []struct { desc string - pipCache []network.PublicIPAddress + pipCache []*armnetwork.PublicIPAddress expectPIPList bool - existingPIPs []network.PublicIPAddress + existingPIPs []*armnetwork.PublicIPAddress expectExists bool - expectedPIP network.PublicIPAddress + expectedPIP *armnetwork.PublicIPAddress }{ { desc: "getPublicIPAddress should return pip from cache when it exists", - pipCache: []network.PublicIPAddress{{Name: ptr.To("pip")}}, + pipCache: []*armnetwork.PublicIPAddress{{Name: ptr.To("pip")}}, expectExists: true, - expectedPIP: network.PublicIPAddress{Name: ptr.To("pip")}, + expectedPIP: &armnetwork.PublicIPAddress{Name: ptr.To("pip")}, }, { desc: "getPublicIPAddress should from list call when cache is empty", expectPIPList: true, - existingPIPs: []network.PublicIPAddress{ + existingPIPs: []*armnetwork.PublicIPAddress{ {Name: ptr.To("pip")}, {Name: ptr.To("pip1")}, }, expectExists: true, - expectedPIP: network.PublicIPAddress{Name: ptr.To("pip")}, + expectedPIP: &armnetwork.PublicIPAddress{Name: ptr.To("pip")}, }, { desc: "getPublicIPAddress should try listing when pip does not exist", - pipCache: []network.PublicIPAddress{{Name: ptr.To("pip1")}}, + pipCache: []*armnetwork.PublicIPAddress{{Name: ptr.To("pip1")}}, expectPIPList: true, - existingPIPs: []network.PublicIPAddress{{Name: ptr.To("pip1")}}, + existingPIPs: []*armnetwork.PublicIPAddress{{Name: ptr.To("pip1")}}, expectExists: false, - expectedPIP: network.PublicIPAddress{}, + expectedPIP: nil, }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() pipCache := &sync.Map{} for _, pip := range test.pipCache { pip := pip - pipCache.Store(ptr.Deref(pip.Name, ""), &pip) + pipCache.Store(ptr.Deref(pip.Name, ""), pip) } az := GetTestCloud(ctrl) az.pipCache.Set(az.ResourceGroup, pipCache) - mockPIPsClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) if test.expectPIPList { mockPIPsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(test.existingPIPs, nil).MaxTimes(2) } pip, pipExists, err := az.getPublicIPAddress(context.TODO(), az.ResourceGroup, "PIP", azcache.CacheReadTypeDefault) - assert.Equal(t, test.expectedPIP, pip) + if test.expectedPIP != nil { + assert.Equal(t, *test.expectedPIP, *pip) + } assert.Equal(t, test.expectExists, pipExists) assert.NoError(t, err) }) @@ -214,29 +215,29 @@ func TestFindMatchedPIP(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - testPIP := network.PublicIPAddress{ + testPIP := &armnetwork.PublicIPAddress{ Name: ptr.To("pipName"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, } for _, tc := range []struct { description string - pips []network.PublicIPAddress - pipsSecondTime []network.PublicIPAddress + pips []*armnetwork.PublicIPAddress + pipsSecondTime []*armnetwork.PublicIPAddress pipName string loadBalancerIP string shouldRefreshCache bool - listError *retry.Error - listErrorSecondTime *retry.Error - expectedPIP *network.PublicIPAddress + listError error + listErrorSecondTime error + expectedPIP *armnetwork.PublicIPAddress expectedError error }{ { description: "should ignore pipName if loadBalancerIP is specified", - pips: []network.PublicIPAddress{testPIP}, - pipsSecondTime: []network.PublicIPAddress{testPIP}, + pips: []*armnetwork.PublicIPAddress{testPIP}, + pipsSecondTime: []*armnetwork.PublicIPAddress{testPIP}, shouldRefreshCache: true, loadBalancerIP: "2.3.4.5", pipName: "pipName", @@ -244,34 +245,34 @@ func TestFindMatchedPIP(t *testing.T) { }, { description: "should report an error if failed to list pip", - listError: retry.NewError(false, errors.New("list error")), - expectedError: errors.New("findMatchedPIPByLoadBalancerIP: failed to listPIP: Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: list error"), + listError: &azcore.ResponseError{ErrorCode: "list error"}, + expectedError: errors.New("list error"), }, { description: "should refresh the cache if failed to search by name", - pips: []network.PublicIPAddress{}, - pipsSecondTime: []network.PublicIPAddress{testPIP}, + pips: []*armnetwork.PublicIPAddress{}, + pipsSecondTime: []*armnetwork.PublicIPAddress{testPIP}, shouldRefreshCache: true, pipName: "pipName", - expectedPIP: &testPIP, + expectedPIP: testPIP, }, { description: "should return the expected pip by name", - pips: []network.PublicIPAddress{testPIP}, + pips: []*armnetwork.PublicIPAddress{testPIP}, pipName: "pipName", - expectedPIP: &testPIP, + expectedPIP: testPIP, }, { description: "should report an error if failed to list pip second time", - pips: []network.PublicIPAddress{}, - listErrorSecondTime: retry.NewError(false, errors.New("list error")), + pips: []*armnetwork.PublicIPAddress{}, + listErrorSecondTime: &azcore.ResponseError{ErrorCode: "list error"}, shouldRefreshCache: true, - expectedError: errors.New("findMatchedPIPByName: failed to listPIP force refresh: Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: list error"), + expectedError: errors.New("list error"), }, } { t.Run(tc.description, func(t *testing.T) { az := GetTestCloud(ctrl) - mockPIPsClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) mockPIPsClient.EXPECT().List(gomock.Any(), "rg").Return(tc.pips, tc.listError) if tc.shouldRefreshCache { mockPIPsClient.EXPECT().List(gomock.Any(), "rg").Return(tc.pipsSecondTime, tc.listErrorSecondTime) @@ -280,7 +281,7 @@ func TestFindMatchedPIP(t *testing.T) { pip, err := az.findMatchedPIP(context.TODO(), tc.loadBalancerIP, tc.pipName, "rg") assert.Equal(t, tc.expectedPIP, pip) if tc.expectedError != nil { - assert.Equal(t, tc.expectedError.Error(), err.Error()) + assert.Contains(t, err.Error(), tc.expectedError.Error()) } }) } @@ -290,36 +291,36 @@ func TestFindMatchedPIPByLoadBalancerIP(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - testPIP := network.PublicIPAddress{ + testPIP := &armnetwork.PublicIPAddress{ Name: ptr.To("pipName"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("1.2.3.4"), }, } testCases := []struct { desc string - pips []network.PublicIPAddress - pipsSecondTime []network.PublicIPAddress + pips []*armnetwork.PublicIPAddress + pipsSecondTime []*armnetwork.PublicIPAddress shouldRefreshCache bool - expectedPIP *network.PublicIPAddress + expectedPIP *armnetwork.PublicIPAddress expectedError bool }{ { desc: "findMatchedPIPByLoadBalancerIP shall return the matched ip", - pips: []network.PublicIPAddress{testPIP}, - expectedPIP: &testPIP, + pips: []*armnetwork.PublicIPAddress{testPIP}, + expectedPIP: testPIP, }, { desc: "findMatchedPIPByLoadBalancerIP shall return error if ip is not found", - pips: []network.PublicIPAddress{}, + pips: []*armnetwork.PublicIPAddress{}, shouldRefreshCache: true, expectedError: true, }, { desc: "findMatchedPIPByLoadBalancerIP should refresh cache if no matched ip is found", - pipsSecondTime: []network.PublicIPAddress{testPIP}, + pipsSecondTime: []*armnetwork.PublicIPAddress{testPIP}, shouldRefreshCache: true, - expectedPIP: &testPIP, + expectedPIP: testPIP, }, } for _, test := range testCases { @@ -327,11 +328,11 @@ func TestFindMatchedPIPByLoadBalancerIP(t *testing.T) { t.Run(test.desc, func(t *testing.T) { az := GetTestCloud(ctrl) - mockPIPsClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) if test.shouldRefreshCache { mockPIPsClient.EXPECT().List(gomock.Any(), "rg").Return(test.pipsSecondTime, nil) } - pip, err := az.findMatchedPIPByLoadBalancerIP(context.TODO(), &test.pips, "1.2.3.4", "rg") + pip, err := az.findMatchedPIPByLoadBalancerIP(context.TODO(), test.pips, "1.2.3.4", "rg") assert.Equal(t, test.expectedPIP, pip) assert.Equal(t, test.expectedError, err != nil) }) diff --git a/pkg/provider/azure_standard.go b/pkg/provider/azure_standard.go index 3dcf89a2dc..c8fbe12dab 100644 --- a/pkg/provider/azure_standard.go +++ b/pkg/provider/azure_standard.go @@ -28,9 +28,11 @@ import ( "sync/atomic" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/samber/lo" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" utilerrors "k8s.io/apimachinery/pkg/util/errors" @@ -166,38 +168,38 @@ func getLastSegment(ID, separator string) (string, error) { // returns the equivalent LoadBalancerRule, SecurityRule and LoadBalancerProbe // protocol types for the given Kubernetes protocol type. -func getProtocolsFromKubernetesProtocol(protocol v1.Protocol) (*network.TransportProtocol, armnetwork.SecurityRuleProtocol, *network.ProbeProtocol, error) { - var transportProto network.TransportProtocol - var securityProto armnetwork.SecurityRuleProtocol - var probeProto network.ProbeProtocol +func getProtocolsFromKubernetesProtocol(protocol v1.Protocol) (*armnetwork.TransportProtocol, *armnetwork.SecurityRuleProtocol, *armnetwork.ProbeProtocol, error) { + var transportProto *armnetwork.TransportProtocol + var securityProto *armnetwork.SecurityRuleProtocol + var probeProto *armnetwork.ProbeProtocol switch protocol { case v1.ProtocolTCP: - transportProto = network.TransportProtocolTCP - securityProto = armnetwork.SecurityRuleProtocolTCP - probeProto = network.ProbeProtocolTCP - return &transportProto, securityProto, &probeProto, nil + transportProto = to.Ptr(armnetwork.TransportProtocolTCP) + securityProto = to.Ptr(armnetwork.SecurityRuleProtocolTCP) + probeProto = to.Ptr(armnetwork.ProbeProtocolTCP) + return transportProto, securityProto, probeProto, nil case v1.ProtocolUDP: - transportProto = network.TransportProtocolUDP - securityProto = armnetwork.SecurityRuleProtocolUDP - return &transportProto, securityProto, nil, nil + transportProto = to.Ptr(armnetwork.TransportProtocolUDP) + securityProto = to.Ptr(armnetwork.SecurityRuleProtocolUDP) + return transportProto, securityProto, nil, nil case v1.ProtocolSCTP: - transportProto = network.TransportProtocolAll - securityProto = armnetwork.SecurityRuleProtocolAsterisk - return &transportProto, securityProto, nil, nil + transportProto = to.Ptr(armnetwork.TransportProtocolAll) + securityProto = to.Ptr(armnetwork.SecurityRuleProtocolAsterisk) + return transportProto, securityProto, nil, nil default: - return &transportProto, securityProto, &probeProto, fmt.Errorf("only TCP, UDP and SCTP are supported for Azure LoadBalancers") + return transportProto, securityProto, probeProto, fmt.Errorf("only TCP, UDP and SCTP are supported for Azure LoadBalancers") } } // This returns the full identifier of the primary NIC for the given VM. -func getPrimaryInterfaceID(machine compute.VirtualMachine) (string, error) { - if len(*machine.NetworkProfile.NetworkInterfaces) == 1 { - return *(*machine.NetworkProfile.NetworkInterfaces)[0].ID, nil +func getPrimaryInterfaceID(machine *armcompute.VirtualMachine) (string, error) { + if len(machine.Properties.NetworkProfile.NetworkInterfaces) == 1 { + return *(machine.Properties.NetworkProfile.NetworkInterfaces)[0].ID, nil } - for _, ref := range *machine.NetworkProfile.NetworkInterfaces { - if ptr.Deref(ref.Primary, false) { + for _, ref := range machine.Properties.NetworkProfile.NetworkInterfaces { + if ptr.Deref(ref.Properties.Primary, false) { return *ref.ID, nil } } @@ -205,19 +207,19 @@ func getPrimaryInterfaceID(machine compute.VirtualMachine) (string, error) { return "", fmt.Errorf("failed to find a primary nic for the vm. vmname=%q", *machine.Name) } -func getPrimaryIPConfig(nic network.Interface) (*network.InterfaceIPConfiguration, error) { - if nic.IPConfigurations == nil { - return nil, fmt.Errorf("nic.IPConfigurations for nic (nicname=%q) is nil", *nic.Name) +func getPrimaryIPConfig(nic *armnetwork.Interface) (*armnetwork.InterfaceIPConfiguration, error) { + if nic.Properties.IPConfigurations == nil { + return nil, fmt.Errorf("nic.Properties.IPConfigurations for nic (nicname=%q) is nil", *nic.Name) } - if len(*nic.IPConfigurations) == 1 { - return &((*nic.IPConfigurations)[0]), nil + if len(nic.Properties.IPConfigurations) == 1 { + return nic.Properties.IPConfigurations[0], nil } - for _, ref := range *nic.IPConfigurations { + for _, ref := range nic.Properties.IPConfigurations { ref := ref - if *ref.Primary { - return &ref, nil + if *ref.Properties.Primary { + return ref, nil } } @@ -225,21 +227,21 @@ func getPrimaryIPConfig(nic network.Interface) (*network.InterfaceIPConfiguratio } // returns first ip configuration on a nic by family -func getIPConfigByIPFamily(nic network.Interface, IPv6 bool) (*network.InterfaceIPConfiguration, error) { - if nic.IPConfigurations == nil { - return nil, fmt.Errorf("nic.IPConfigurations for nic (nicname=%q) is nil", *nic.Name) +func getIPConfigByIPFamily(nic *armnetwork.Interface, IPv6 bool) (*armnetwork.InterfaceIPConfiguration, error) { + if nic.Properties.IPConfigurations == nil { + return nil, fmt.Errorf("nic.Properties.IPConfigurations for nic (nicname=%q) is nil", *nic.Name) } - var ipVersion network.IPVersion + var ipVersion armnetwork.IPVersion if IPv6 { - ipVersion = network.IPv6 + ipVersion = armnetwork.IPVersionIPv6 } else { - ipVersion = network.IPv4 + ipVersion = armnetwork.IPVersionIPv4 } - for _, ref := range *nic.IPConfigurations { + for _, ref := range nic.Properties.IPConfigurations { ref := ref - if ref.PrivateIPAddress != nil && ref.PrivateIPAddressVersion == ipVersion { - return &ref, nil + if ref.Properties.PrivateIPAddress != nil && *ref.Properties.PrivateIPAddressVersion == ipVersion { + return ref, nil } } return nil, fmt.Errorf("failed to determine the ipconfig(IPv6=%v). nicname=%q", IPv6, ptr.Deref(nic.Name, "")) @@ -347,15 +349,15 @@ func (az *Cloud) getPublicIPName(clusterName string, service *v1.Service, isIPv6 return getResourceByIPFamily(pipNameSegment, isDualStack, isIPv6), nil } -func publicIPOwnsFrontendIP(service *v1.Service, fip *network.FrontendIPConfiguration, pip *network.PublicIPAddress) bool { +func publicIPOwnsFrontendIP(service *v1.Service, fip *armnetwork.FrontendIPConfiguration, pip *armnetwork.PublicIPAddress) bool { if pip != nil && pip.ID != nil && - pip.PublicIPAddressPropertiesFormat != nil && - pip.PublicIPAddressPropertiesFormat.IPAddress != nil && + pip.Properties != nil && + pip.Properties.IPAddress != nil && fip != nil && - fip.FrontendIPConfigurationPropertiesFormat != nil && - fip.FrontendIPConfigurationPropertiesFormat.PublicIPAddress != nil { - if strings.EqualFold(ptr.Deref(pip.ID, ""), ptr.Deref(fip.PublicIPAddress.ID, "")) { + fip.Properties != nil && + fip.Properties.PublicIPAddress != nil { + if strings.EqualFold(ptr.Deref(pip.ID, ""), ptr.Deref(fip.Properties.PublicIPAddress.ID, "")) { klog.V(6).Infof("publicIPOwnsFrontendIP:found secondary service %s of the frontend IP config %s", service.Name, *fip.Name) return true } @@ -401,7 +403,7 @@ type availabilitySet struct { } type AvailabilitySetEntry struct { - VMAS *compute.AvailabilitySet + VMAS *armcompute.AvailabilitySet ResourceGroup string } @@ -415,10 +417,10 @@ func (as *availabilitySet) newVMASCache() (azcache.Resource, error) { } for _, resourceGroup := range allResourceGroups.UnsortedList() { - allAvailabilitySets, rerr := as.AvailabilitySetsClient.List(ctx, resourceGroup) + allAvailabilitySets, rerr := as.ComputeClientFactory.GetAvailabilitySetClient().List(ctx, resourceGroup) if rerr != nil { klog.Errorf("AvailabilitySetsClient.List failed: %v", rerr) - return nil, rerr.Error() + return nil, rerr } for i := range allAvailabilitySets { @@ -428,7 +430,7 @@ func (as *availabilitySet) newVMASCache() (azcache.Resource, error) { continue } localCache.Store(ptr.Deref(vmas.Name, ""), &AvailabilitySetEntry{ - VMAS: &vmas, + VMAS: vmas, ResourceGroup: resourceGroup, }) } @@ -472,7 +474,7 @@ func newAvailabilitySet(az *Cloud) (VMSet, error) { // It must return ("", cloudprovider.InstanceNotFound) if the instance does // not exist or is no longer running. func (as *availabilitySet) GetInstanceIDByNodeName(ctx context.Context, name string) (string, error) { - var machine compute.VirtualMachine + var machine *armcompute.VirtualMachine var err error machine, err = as.getVirtualMachine(ctx, types.NodeName(name), azcache.CacheReadTypeUnsafe) @@ -509,11 +511,11 @@ func (as *availabilitySet) GetPowerStatusByNodeName(ctx context.Context, name st return powerState, err } - if vm.InstanceView != nil { - return vmutil.GetVMPowerState(ptr.Deref(vm.Name, ""), vm.InstanceView.Statuses), nil + if vm.Properties.InstanceView != nil { + return vmutil.GetVMPowerState(ptr.Deref(vm.Name, ""), vm.Properties.InstanceView.Statuses), nil } - // vm.InstanceView or vm.InstanceView.Statuses are nil when the VM is under deleting. + // vm.Properties.InstanceView or vm.Properties.InstanceView.Statuses are nil when the VM is under deleting. klog.V(3).Infof("InstanceView for node %q is nil, assuming it's deleting", name) return consts.VMPowerStateUnknown, nil } @@ -525,11 +527,11 @@ func (as *availabilitySet) GetProvisioningStateByNodeName(ctx context.Context, n return provisioningState, err } - if vm.VirtualMachineProperties == nil || vm.VirtualMachineProperties.ProvisioningState == nil { + if vm.Properties == nil || vm.Properties.ProvisioningState == nil { return provisioningState, nil } - return ptr.Deref(vm.VirtualMachineProperties.ProvisioningState, ""), nil + return ptr.Deref(vm.Properties.ProvisioningState, ""), nil } // GetNodeNameByProviderID gets the node name by provider ID. @@ -551,10 +553,10 @@ func (as *availabilitySet) GetInstanceTypeByNodeName(ctx context.Context, name s return "", err } - if machine.HardwareProfile == nil { + if machine.Properties.HardwareProfile == nil { return "", fmt.Errorf("HardwareProfile of node(%s) is nil", name) } - return string(machine.HardwareProfile.VMSize), nil + return string(*machine.Properties.HardwareProfile.VMSize), nil } // GetZoneByNodeName gets availability zone for the specified node. If the node is not running @@ -567,18 +569,18 @@ func (as *availabilitySet) GetZoneByNodeName(ctx context.Context, name string) ( } var failureDomain string - if vm.Zones != nil && len(*vm.Zones) > 0 { + if len(vm.Zones) > 0 { // Get availability zone for the node. - zones := *vm.Zones - zoneID, err := strconv.Atoi(zones[0]) + zones := vm.Zones + zoneID, err := strconv.Atoi(*zones[0]) if err != nil { - return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone %q: %w", zones, err) + return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone %q: %w", lo.FromSlicePtr(zones), err) } failureDomain = as.makeZone(ptr.Deref(vm.Location, ""), zoneID) } else { // Availability zone is not used for the node, falling back to fault domain. - failureDomain = strconv.Itoa(int(ptr.Deref(vm.VirtualMachineProperties.InstanceView.PlatformFaultDomain, 0))) + failureDomain = strconv.Itoa(int(ptr.Deref(vm.Properties.InstanceView.PlatformFaultDomain, 0))) } zone := cloudprovider.Zone{ @@ -607,10 +609,10 @@ func (as *availabilitySet) GetIPByNodeName(ctx context.Context, name string) (st return "", "", err } - privateIP := *ipConfig.PrivateIPAddress + privateIP := *ipConfig.Properties.PrivateIPAddress publicIP := "" - if ipConfig.PublicIPAddress != nil && ipConfig.PublicIPAddress.ID != nil { - pipID := *ipConfig.PublicIPAddress.ID + if ipConfig.Properties.PublicIPAddress != nil && ipConfig.Properties.PublicIPAddress.ID != nil { + pipID := *ipConfig.Properties.PublicIPAddress.ID pipName, err := getLastSegment(pipID, "/") if err != nil { return "", "", fmt.Errorf("failed to publicIP name for node %q with pipID %q", name, pipID) @@ -620,7 +622,7 @@ func (as *availabilitySet) GetIPByNodeName(ctx context.Context, name string) (st return "", "", err } if existsPip { - publicIP = *pip.IPAddress + publicIP = *pip.Properties.IPAddress } } @@ -637,13 +639,13 @@ func (as *availabilitySet) GetPrivateIPsByNodeName(ctx context.Context, name str return ips, err } - if nic.IPConfigurations == nil { - return ips, fmt.Errorf("nic.IPConfigurations for nic (nicname=%q) is nil", *nic.Name) + if nic.Properties.IPConfigurations == nil { + return ips, fmt.Errorf("nic.Properties.IPConfigurations for nic (nicname=%q) is nil", *nic.Name) } - for _, ipConfig := range *(nic.IPConfigurations) { - if ipConfig.PrivateIPAddress != nil { - ips = append(ips, *(ipConfig.PrivateIPAddress)) + for _, ipConfig := range nic.Properties.IPConfigurations { + if ipConfig.Properties.PrivateIPAddress != nil { + ips = append(ips, *(ipConfig.Properties.PrivateIPAddress)) } } @@ -652,15 +654,15 @@ func (as *availabilitySet) GetPrivateIPsByNodeName(ctx context.Context, name str // getAgentPoolAvailabilitySets lists the virtual machines for the resource group and then builds // a list of availability sets that match the nodes available to k8s. -func (as *availabilitySet) getAgentPoolAvailabilitySets(vms []compute.VirtualMachine, nodes []*v1.Node) (agentPoolAvailabilitySets *[]string, err error) { +func (as *availabilitySet) getAgentPoolAvailabilitySets(vms []*armcompute.VirtualMachine, nodes []*v1.Node) (agentPoolAvailabilitySets []*string, err error) { vmNameToAvailabilitySetID := make(map[string]string, len(vms)) for vmx := range vms { vm := vms[vmx] - if vm.AvailabilitySet != nil { - vmNameToAvailabilitySetID[*vm.Name] = *vm.AvailabilitySet.ID + if vm.Properties.AvailabilitySet != nil { + vmNameToAvailabilitySetID[*vm.Name] = *vm.Properties.AvailabilitySet.ID } } - agentPoolAvailabilitySets = &[]string{} + agentPoolAvailabilitySets = []*string{} for nx := range nodes { nodeName := (*nodes[nx]).Name if isControlPlaneNode(nodes[nx]) { @@ -680,7 +682,7 @@ func (as *availabilitySet) getAgentPoolAvailabilitySets(vms []compute.VirtualMac // We want to keep it lower case, before the ID get fixed asName = strings.ToLower(asName) - *agentPoolAvailabilitySets = append(*agentPoolAvailabilitySets, asName) + agentPoolAvailabilitySets = append(agentPoolAvailabilitySets, &asName) } return agentPoolAvailabilitySets, nil @@ -691,12 +693,12 @@ func (as *availabilitySet) getAgentPoolAvailabilitySets(vms []compute.VirtualMac // no loadbalancer mode annotation returns the primary VMSet. If service annotation // for loadbalancer exists then returns the eligible VMSet. The mode selection // annotation would be ignored when using one SLB per cluster. -func (as *availabilitySet) GetVMSetNames(ctx context.Context, service *v1.Service, nodes []*v1.Node) (availabilitySetNames *[]string, err error) { +func (as *availabilitySet) GetVMSetNames(ctx context.Context, service *v1.Service, nodes []*v1.Node) (availabilitySetNames []*string, err error) { hasMode, isAuto, serviceAvailabilitySetName := as.getServiceLoadBalancerMode(service) if !hasMode || as.UseStandardLoadBalancer() { // no mode specified in service annotation or use single SLB mode // default to PrimaryAvailabilitySetName - availabilitySetNames = &[]string{as.Config.PrimaryAvailabilitySetName} + availabilitySetNames = []*string{to.Ptr(as.Config.PrimaryAvailabilitySetName)} return availabilitySetNames, nil } @@ -710,14 +712,14 @@ func (as *availabilitySet) GetVMSetNames(ctx context.Context, service *v1.Servic klog.Errorf("as.GetVMSetNames - getAgentPoolAvailabilitySets failed err=(%v)", err) return nil, err } - if len(*availabilitySetNames) == 0 { + if len(availabilitySetNames) == 0 { klog.Errorf("as.GetVMSetNames - No availability sets found for nodes in the cluster, node count(%d)", len(nodes)) return nil, fmt.Errorf("no availability sets found for nodes, node count(%d)", len(nodes)) } if !isAuto { found := false - for asx := range *availabilitySetNames { - if strings.EqualFold((*availabilitySetNames)[asx], serviceAvailabilitySetName) { + for asx := range availabilitySetNames { + if strings.EqualFold(*availabilitySetNames[asx], serviceAvailabilitySetName) { found = true break } @@ -726,7 +728,7 @@ func (as *availabilitySet) GetVMSetNames(ctx context.Context, service *v1.Servic klog.Errorf("as.GetVMSetNames - Availability set (%s) in service annotation not found", serviceAvailabilitySetName) return nil, fmt.Errorf("availability set (%s) - not found", serviceAvailabilitySetName) } - return &[]string{serviceAvailabilitySetName}, nil + return []*string{to.Ptr(serviceAvailabilitySetName)}, nil } return availabilitySetNames, nil @@ -758,12 +760,12 @@ func (as *availabilitySet) GetNodeVMSetName(ctx context.Context, node *v1.Node) var asName string for _, vm := range vms { if strings.EqualFold(ptr.Deref(vm.Name, ""), hostName) { - if vm.AvailabilitySet != nil && ptr.Deref(vm.AvailabilitySet.ID, "") != "" { + if vm.Properties.AvailabilitySet != nil && ptr.Deref(vm.Properties.AvailabilitySet.ID, "") != "" { klog.V(4).Infof("as.GetNodeVMSetName: found vm %s", hostName) - asName, err = getLastSegment(ptr.Deref(vm.AvailabilitySet.ID, ""), "/") + asName, err = getLastSegment(ptr.Deref(vm.Properties.AvailabilitySet.ID, ""), "/") if err != nil { - klog.Errorf("as.GetNodeVMSetName: failed to get last segment of ID %s: %s", ptr.Deref(vm.AvailabilitySet.ID, ""), err) + klog.Errorf("as.GetNodeVMSetName: failed to get last segment of ID %s: %s", ptr.Deref(vm.Properties.AvailabilitySet.ID, ""), err) return "", err } } @@ -777,7 +779,7 @@ func (as *availabilitySet) GetNodeVMSetName(ctx context.Context, node *v1.Node) } // GetPrimaryInterface gets machine primary network interface by node name. -func (as *availabilitySet) GetPrimaryInterface(ctx context.Context, nodeName string) (network.Interface, error) { +func (as *availabilitySet) GetPrimaryInterface(ctx context.Context, nodeName string) (*armnetwork.Interface, error) { nic, _, err := as.getPrimaryInterfaceWithVMSet(ctx, nodeName, "") return nic, err } @@ -793,26 +795,26 @@ func extractResourceGroupByNicID(nicID string) (string, error) { } // getPrimaryInterfaceWithVMSet gets machine primary network interface by node name and vmSet. -func (as *availabilitySet) getPrimaryInterfaceWithVMSet(ctx context.Context, nodeName, vmSetName string) (network.Interface, string, error) { - var machine compute.VirtualMachine +func (as *availabilitySet) getPrimaryInterfaceWithVMSet(ctx context.Context, nodeName, vmSetName string) (*armnetwork.Interface, string, error) { + var machine *armcompute.VirtualMachine machine, err := as.GetVirtualMachineWithRetry(ctx, types.NodeName(nodeName), azcache.CacheReadTypeDefault) if err != nil { klog.V(2).Infof("GetPrimaryInterface(%s, %s) abort backoff", nodeName, vmSetName) - return network.Interface{}, "", err + return nil, "", err } primaryNicID, err := getPrimaryInterfaceID(machine) if err != nil { - return network.Interface{}, "", err + return nil, "", err } nicName, err := getLastSegment(primaryNicID, "/") if err != nil { - return network.Interface{}, "", err + return nil, "", err } nodeResourceGroup, err := as.GetNodeResourceGroup(nodeName) if err != nil { - return network.Interface{}, "", err + return nil, "", err } // Check availability set name. Note that vmSetName is empty string when getting @@ -830,35 +832,35 @@ func (as *availabilitySet) getPrimaryInterfaceWithVMSet(ctx context.Context, nod } if vmSetName != "" && needCheck { expectedAvailabilitySetID := as.getAvailabilitySetID(nodeResourceGroup, vmSetName) - if machine.AvailabilitySet == nil || !strings.EqualFold(*machine.AvailabilitySet.ID, expectedAvailabilitySetID) { + if machine.Properties.AvailabilitySet == nil || !strings.EqualFold(*machine.Properties.AvailabilitySet.ID, expectedAvailabilitySetID) { klog.V(3).Infof( "GetPrimaryInterface: nic (%s) is not in the availabilitySet(%s)", nicName, vmSetName) - return network.Interface{}, "", errNotInVMSet + return nil, "", errNotInVMSet } } nicResourceGroup, err := extractResourceGroupByNicID(primaryNicID) if err != nil { - return network.Interface{}, "", err + return nil, "", err } ctx, cancel := getContextWithCancel() defer cancel() - nic, rerr := as.InterfacesClient.Get(ctx, nicResourceGroup, nicName, "") + nic, rerr := as.NetworkClientFactory.GetInterfaceClient().Get(ctx, nicResourceGroup, nicName, nil) if rerr != nil { - return network.Interface{}, "", rerr.Error() + return nil, "", rerr } var availabilitySetID string - if machine.VirtualMachineProperties != nil && machine.AvailabilitySet != nil { - availabilitySetID = ptr.Deref(machine.AvailabilitySet.ID, "") + if machine.Properties != nil && machine.Properties.AvailabilitySet != nil { + availabilitySetID = ptr.Deref(machine.Properties.AvailabilitySet.ID, "") } return nic, availabilitySetID, nil } // EnsureHostInPool ensures the given VM's Primary NIC's Primary IP Configuration is // participating in the specified LoadBalancer Backend Pool. -func (as *availabilitySet) EnsureHostInPool(ctx context.Context, service *v1.Service, nodeName types.NodeName, backendPoolID string, vmSetName string) (string, string, string, *compute.VirtualMachineScaleSetVM, error) { +func (as *availabilitySet) EnsureHostInPool(ctx context.Context, service *v1.Service, nodeName types.NodeName, backendPoolID string, vmSetName string) (string, string, string, *armcompute.VirtualMachineScaleSetVM, error) { vmName := mapNodeNameToVMName(nodeName) serviceName := getServiceName(service) nic, _, err := as.getPrimaryInterfaceWithVMSet(ctx, vmName, vmSetName) @@ -872,12 +874,12 @@ func (as *availabilitySet) EnsureHostInPool(ctx context.Context, service *v1.Ser return "", "", "", nil, err } - if nic.ProvisioningState == consts.NicFailedState { + if nic != nil && nic.Properties != nil && nic.Properties.ProvisioningState != nil && *nic.Properties.ProvisioningState == armnetwork.ProvisioningStateFailed { klog.Warningf("EnsureHostInPool skips node %s because its primary nic %s is in Failed state", nodeName, *nic.Name) return "", "", "", nil, nil } - var primaryIPConfig *network.InterfaceIPConfiguration + var primaryIPConfig *armnetwork.InterfaceIPConfiguration ipv6 := isBackendPoolIPv6(backendPoolID) if !as.Cloud.ipv6DualStackEnabled && !ipv6 { primaryIPConfig, err = getPrimaryIPConfig(nic) @@ -892,9 +894,9 @@ func (as *availabilitySet) EnsureHostInPool(ctx context.Context, service *v1.Ser } foundPool := false - newBackendPools := []network.BackendAddressPool{} - if primaryIPConfig.LoadBalancerBackendAddressPools != nil { - newBackendPools = *primaryIPConfig.LoadBalancerBackendAddressPools + newBackendPools := []*armnetwork.BackendAddressPool{} + if primaryIPConfig.Properties.LoadBalancerBackendAddressPools != nil { + newBackendPools = primaryIPConfig.Properties.LoadBalancerBackendAddressPools } for _, existingPool := range newBackendPools { if strings.EqualFold(backendPoolID, *existingPool.ID) { @@ -925,11 +927,11 @@ func (as *availabilitySet) EnsureHostInPool(ctx context.Context, service *v1.Ser } newBackendPools = append(newBackendPools, - network.BackendAddressPool{ + &armnetwork.BackendAddressPool{ ID: ptr.To(backendPoolID), }) - primaryIPConfig.LoadBalancerBackendAddressPools = &newBackendPools + primaryIPConfig.Properties.LoadBalancerBackendAddressPools = newBackendPools nicName := *nic.Name klog.V(3).Infof("nicupdate(%s): nic(%s) - updating", serviceName, nicName) @@ -989,7 +991,7 @@ func (as *availabilitySet) EnsureHostsInPool(ctx context.Context, service *v1.Se // EnsureBackendPoolDeleted ensures the loadBalancer backendAddressPools deleted from the specified nodes. // backendPoolIDs are the IDs of the backendpools to be deleted. -func (as *availabilitySet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Service, backendPoolIDs []string, vmSetName string, backendAddressPools *[]network.BackendAddressPool, _ bool) (bool, error) { +func (as *availabilitySet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Service, backendPoolIDs []string, vmSetName string, backendAddressPools []*armnetwork.BackendAddressPool, _ bool) (bool, error) { // Returns nil if backend address pools already deleted. if backendAddressPools == nil { return false, nil @@ -1002,12 +1004,12 @@ func (as *availabilitySet) EnsureBackendPoolDeleted(ctx context.Context, service }() ipConfigurationIDs := []string{} - for _, backendPool := range *backendAddressPools { + for _, backendPool := range backendAddressPools { for _, backendPoolID := range backendPoolIDs { if strings.EqualFold(ptr.Deref(backendPool.ID, ""), backendPoolID) { - if backendPool.BackendAddressPoolPropertiesFormat != nil && - backendPool.BackendIPConfigurations != nil { - for _, ipConf := range *backendPool.BackendIPConfigurations { + if backendPool.Properties != nil && + backendPool.Properties.BackendIPConfigurations != nil { + for _, ipConf := range backendPool.Properties.BackendIPConfigurations { if ipConf.ID == nil { continue } @@ -1021,7 +1023,7 @@ func (as *availabilitySet) EnsureBackendPoolDeleted(ctx context.Context, service nicUpdaters := make([]func() error, 0) allErrs := make([]error, 0) - ipconfigPrefixToNicMap := map[string]network.Interface{} // ipconfig prefix -> nic + ipconfigPrefixToNicMap := map[string]*armnetwork.Interface{} // ipconfig prefix -> nic for i := range ipConfigurationIDs { ipConfigurationID := ipConfigurationIDs[i] ipConfigIDPrefix := getResourceIDPrefix(ipConfigurationID) @@ -1060,12 +1062,12 @@ func (as *availabilitySet) EnsureBackendPoolDeleted(ctx context.Context, service continue } - if nic.ProvisioningState == consts.NicFailedState { + if *nic.Properties.ProvisioningState == consts.NicFailedState { klog.Warningf("EnsureBackendPoolDeleted skips node %s because its primary nic %s is in Failed state", nodeName, *nic.Name) return false, nil } - if nic.InterfacePropertiesFormat != nil && nic.InterfacePropertiesFormat.IPConfigurations != nil { + if nic.Properties != nil && nic.Properties.IPConfigurations != nil { ipconfigPrefixToNicMap[ipConfigIDPrefix] = nic } } @@ -1074,16 +1076,16 @@ func (as *availabilitySet) EnsureBackendPoolDeleted(ctx context.Context, service var nicUpdated atomic.Bool for k := range ipconfigPrefixToNicMap { nic := ipconfigPrefixToNicMap[k] - newIPConfigs := *nic.IPConfigurations + newIPConfigs := nic.Properties.IPConfigurations for j, ipConf := range newIPConfigs { - if isServiceIPv4 && !ptr.Deref(ipConf.Primary, false) { + if isServiceIPv4 && !ptr.Deref(ipConf.Properties.Primary, false) { continue } // To support IPv6 only and dual-stack clusters, all IP configurations // should be checked regardless of primary or not because IPv6 IP configurations // are not marked as primary. - if ipConf.LoadBalancerBackendAddressPools != nil { - newLBAddressPools := *ipConf.LoadBalancerBackendAddressPools + if ipConf.Properties.LoadBalancerBackendAddressPools != nil { + newLBAddressPools := ipConf.Properties.LoadBalancerBackendAddressPools for k := len(newLBAddressPools) - 1; k >= 0; k-- { pool := newLBAddressPools[k] for _, backendPoolID := range backendPoolIDs { @@ -1093,16 +1095,16 @@ func (as *availabilitySet) EnsureBackendPoolDeleted(ctx context.Context, service } } } - newIPConfigs[j].LoadBalancerBackendAddressPools = &newLBAddressPools + newIPConfigs[j].Properties.LoadBalancerBackendAddressPools = newLBAddressPools } } - nic.IPConfigurations = &newIPConfigs + nic.Properties.IPConfigurations = newIPConfigs nicUpdaters = append(nicUpdaters, func() error { klog.V(2).Infof("EnsureBackendPoolDeleted begins to CreateOrUpdate for NIC(%s, %s) with backendPoolIDs %q", as.ResourceGroup, ptr.Deref(nic.Name, ""), backendPoolIDs) - rerr := as.InterfacesClient.CreateOrUpdate(ctx, as.ResourceGroup, ptr.Deref(nic.Name, ""), nic) + _, rerr := as.NetworkClientFactory.GetInterfaceClient().CreateOrUpdate(ctx, as.ResourceGroup, ptr.Deref(nic.Name, ""), *nic) if rerr != nil { klog.Errorf("EnsureBackendPoolDeleted CreateOrUpdate for NIC(%s, %s) failed with error %v", as.ResourceGroup, ptr.Deref(nic.Name, ""), rerr.Error()) - return rerr.Error() + return rerr } nicUpdated.Store(true) return nil @@ -1147,13 +1149,13 @@ func (as *availabilitySet) GetNodeNameByIPConfigurationID(ctx context.Context, i if nicResourceGroup == "" || nicName == "" { return "", "", fmt.Errorf("invalid ip config ID %s", ipConfigurationID) } - nic, rerr := as.InterfacesClient.Get(ctx, nicResourceGroup, nicName, "") + nic, rerr := as.NetworkClientFactory.GetInterfaceClient().Get(ctx, nicResourceGroup, nicName, nil) if rerr != nil { - return "", "", fmt.Errorf("GetNodeNameByIPConfigurationID(%s): failed to get interface of name %s: %w", ipConfigurationID, nicName, rerr.Error()) + return "", "", fmt.Errorf("GetNodeNameByIPConfigurationID(%s): failed to get interface of name %s: %w", ipConfigurationID, nicName, rerr) } vmID := "" - if nic.InterfacePropertiesFormat != nil && nic.VirtualMachine != nil { - vmID = ptr.Deref(nic.VirtualMachine.ID, "") + if nic.Properties != nil && nic.Properties.VirtualMachine != nil { + vmID = ptr.Deref(nic.Properties.VirtualMachine.ID, "") } if vmID == "" { klog.V(2).Infof("GetNodeNameByIPConfigurationID(%s): empty vmID", ipConfigurationID) @@ -1172,8 +1174,8 @@ func (as *availabilitySet) GetNodeNameByIPConfigurationID(ctx context.Context, i return "", "", err } asID := "" - if vm.VirtualMachineProperties != nil && vm.AvailabilitySet != nil { - asID = ptr.Deref(vm.AvailabilitySet.ID, "") + if vm.Properties != nil && vm.Properties.AvailabilitySet != nil { + asID = ptr.Deref(vm.Properties.AvailabilitySet.ID, "") } if asID == "" { return vmName, "", nil @@ -1186,7 +1188,7 @@ func (as *availabilitySet) GetNodeNameByIPConfigurationID(ctx context.Context, i return vmName, strings.ToLower(asName), nil } -func (as *availabilitySet) getAvailabilitySetByNodeName(ctx context.Context, nodeName string, crt azcache.AzureCacheReadType) (*compute.AvailabilitySet, error) { +func (as *availabilitySet) getAvailabilitySetByNodeName(ctx context.Context, nodeName string, crt azcache.AzureCacheReadType) (*armcompute.AvailabilitySet, error) { cached, err := as.vmasCache.Get(ctx, consts.VMASKey, crt) if err != nil { return nil, err @@ -1198,12 +1200,12 @@ func (as *availabilitySet) getAvailabilitySetByNodeName(ctx context.Context, nod return nil, nil } - var result *compute.AvailabilitySet + var result *armcompute.AvailabilitySet vmasList.Range(func(_, value interface{}) bool { vmasEntry := value.(*AvailabilitySetEntry) vmas := vmasEntry.VMAS - if vmas != nil && vmas.AvailabilitySetProperties != nil && vmas.VirtualMachines != nil { - for _, vmIDRef := range *vmas.VirtualMachines { + if vmas != nil && vmas.Properties != nil && vmas.Properties.VirtualMachines != nil { + for _, vmIDRef := range vmas.Properties.VirtualMachines { if vmIDRef.ID != nil { matches := vmIDRE.FindStringSubmatch(ptr.Deref(vmIDRef.ID, "")) if len(matches) != 2 { @@ -1273,7 +1275,7 @@ func (as *availabilitySet) EnsureBackendPoolDeletedFromVMSets(_ context.Context, } // GetAgentPoolVMSetNames returns all VMAS names according to the nodes -func (as *availabilitySet) GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1.Node) (*[]string, error) { +func (as *availabilitySet) GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1.Node) ([]*string, error) { vms, err := as.ListVirtualMachines(ctx, as.ResourceGroup) if err != nil { klog.Errorf("as.getNodeAvailabilitySet - ListVirtualMachines failed, err=%v", err) diff --git a/pkg/provider/azure_standard_test.go b/pkg/provider/azure_standard_test.go index 2441da2781..f44ff443fe 100644 --- a/pkg/provider/azure_standard_test.go +++ b/pkg/provider/azure_standard_test.go @@ -24,9 +24,11 @@ import ( "strconv" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" v1 "k8s.io/api/core/v1" @@ -35,12 +37,11 @@ import ( cloudprovider "k8s.io/cloud-provider" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmasclient/mockvmasclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/availabilitysetclient/mock_availabilitysetclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/mock_interfaceclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) @@ -189,9 +190,9 @@ func TestMapLoadBalancerNameToVMSet(t *testing.T) { for _, c := range cases { if c.useStandardLB { - az.Config.LoadBalancerSku = consts.LoadBalancerSkuStandard + az.Config.LoadBalancerSKU = consts.LoadBalancerSKUStandard } else { - az.Config.LoadBalancerSku = consts.LoadBalancerSkuBasic + az.Config.LoadBalancerSKU = consts.LoadBalancerSKUBasic } vmset := az.mapLoadBalancerNameToVMSet(c.lbName, c.clusterName) assert.Equal(t, c.expectedVMSet, vmset, c.description) @@ -324,9 +325,9 @@ func TestGetLoadBalancingRuleName(t *testing.T) { for _, c := range cases { t.Run(c.description, func(t *testing.T) { if c.useStandardLB { - az.Config.LoadBalancerSku = consts.LoadBalancerSkuStandard + az.Config.LoadBalancerSKU = consts.LoadBalancerSKUStandard } else { - az.Config.LoadBalancerSku = consts.LoadBalancerSkuBasic + az.Config.LoadBalancerSKU = consts.LoadBalancerSKUBasic } svc.Annotations[consts.ServiceAnnotationLoadBalancerInternalSubnet] = c.subnetName svc.Annotations[consts.ServiceAnnotationLoadBalancerInternal] = strconv.FormatBool(c.isInternal) @@ -551,57 +552,65 @@ func TestGetProtocolsFromKubernetesProtocol(t *testing.T) { testcases := []struct { Name string protocol v1.Protocol - expectedTransportProto network.TransportProtocol - expectedSecurityGroupProto armnetwork.SecurityRuleProtocol - expectedProbeProto network.ProbeProtocol + expectedTransportProto *armnetwork.TransportProtocol + expectedSecurityGroupProto *armnetwork.SecurityRuleProtocol + expectedProbeProto *armnetwork.ProbeProtocol nilProbeProto bool expectedErrMsg error }{ { Name: "getProtocolsFromKubernetesProtocol should get TCP protocol", protocol: v1.ProtocolTCP, - expectedTransportProto: network.TransportProtocolTCP, - expectedSecurityGroupProto: armnetwork.SecurityRuleProtocolTCP, - expectedProbeProto: network.ProbeProtocolTCP, + expectedTransportProto: to.Ptr(armnetwork.TransportProtocolTCP), + expectedSecurityGroupProto: to.Ptr(armnetwork.SecurityRuleProtocolTCP), + expectedProbeProto: to.Ptr(armnetwork.ProbeProtocolTCP), }, { Name: "getProtocolsFromKubernetesProtocol should get UDP protocol", protocol: v1.ProtocolUDP, - expectedTransportProto: network.TransportProtocolUDP, - expectedSecurityGroupProto: armnetwork.SecurityRuleProtocolUDP, + expectedTransportProto: to.Ptr(armnetwork.TransportProtocolUDP), + expectedSecurityGroupProto: to.Ptr(armnetwork.SecurityRuleProtocolUDP), nilProbeProto: true, }, { Name: "getProtocolsFromKubernetesProtocol should get SCTP protocol", protocol: v1.ProtocolSCTP, - expectedTransportProto: network.TransportProtocolAll, - expectedSecurityGroupProto: armnetwork.SecurityRuleProtocolAsterisk, + expectedTransportProto: to.Ptr(armnetwork.TransportProtocolAll), + expectedSecurityGroupProto: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), nilProbeProto: true, }, { Name: "getProtocolsFromKubernetesProtocol should report error", protocol: v1.Protocol("ICMP"), expectedErrMsg: fmt.Errorf("only TCP, UDP and SCTP are supported for Azure LoadBalancers"), + nilProbeProto: true, }, } for _, test := range testcases { - transportProto, securityGroupProto, probeProto, err := getProtocolsFromKubernetesProtocol(test.protocol) - assert.Equal(t, test.expectedTransportProto, *transportProto, test.Name) - assert.Equal(t, test.expectedSecurityGroupProto, securityGroupProto, test.Name) - if test.nilProbeProto { - assert.Nil(t, probeProto, test.Name) - } else { - assert.Equal(t, test.expectedProbeProto, *probeProto, test.Name) - } - assert.Equal(t, test.expectedErrMsg, err, test.Name) + test := test + t.Run(test.Name, func(t *testing.T) { + transportProto, securityGroupProto, probeProto, err := getProtocolsFromKubernetesProtocol(test.protocol) + if test.expectedTransportProto != nil { + assert.Equal(t, *test.expectedTransportProto, *transportProto, test.Name) + } + if test.expectedSecurityGroupProto != nil { + assert.Equal(t, *test.expectedSecurityGroupProto, *securityGroupProto, test.Name) + } + if test.nilProbeProto { + assert.Nil(t, probeProto, test.Name) + } else { + assert.Equal(t, *test.expectedProbeProto, *probeProto, test.Name) + } + assert.Equal(t, test.expectedErrMsg, err, test.Name) + }) } } func TestGetStandardVMPrimaryInterfaceID(t *testing.T) { testcases := []struct { name string - vm compute.VirtualMachine + vm *armcompute.VirtualMachine expectedNicID string expectedErrMsg error }{ @@ -612,19 +621,19 @@ func TestGetStandardVMPrimaryInterfaceID(t *testing.T) { }, { name: "GetPrimaryInterfaceID should get primary NIC ID", - vm: compute.VirtualMachine{ + vm: &armcompute.VirtualMachine{ Name: ptr.To("vm2"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &[]compute.NetworkInterfaceReference{ + Properties: &armcompute.VirtualMachineProperties{ + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: []*armcompute.NetworkInterfaceReference{ { - NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ + Properties: &armcompute.NetworkInterfaceReferenceProperties{ Primary: ptr.To(true), }, ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic1"), }, { - NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ + Properties: &armcompute.NetworkInterfaceReferenceProperties{ Primary: ptr.To(false), }, ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic2"), @@ -637,19 +646,19 @@ func TestGetStandardVMPrimaryInterfaceID(t *testing.T) { }, { name: "GetPrimaryInterfaceID should report error if node don't have primary NIC", - vm: compute.VirtualMachine{ + vm: &armcompute.VirtualMachine{ Name: ptr.To("vm3"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &[]compute.NetworkInterfaceReference{ + Properties: &armcompute.VirtualMachineProperties{ + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: []*armcompute.NetworkInterfaceReference{ { - NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ + Properties: &armcompute.NetworkInterfaceReferenceProperties{ Primary: ptr.To(false), }, ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic1"), }, { - NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ + Properties: &armcompute.NetworkInterfaceReferenceProperties{ Primary: ptr.To(false), }, ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic2"), @@ -672,78 +681,78 @@ func TestGetStandardVMPrimaryInterfaceID(t *testing.T) { func TestGetPrimaryIPConfig(t *testing.T) { testcases := []struct { name string - nic network.Interface - expectedIPConfig *network.InterfaceIPConfiguration + nic *armnetwork.Interface + expectedIPConfig *armnetwork.InterfaceIPConfiguration expectedErrMsg error }{ { name: "GetPrimaryIPConfig should get the only IP configuration", - nic: network.Interface{ + nic: &armnetwork.Interface{ Name: ptr.To("nic"), - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - IPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.InterfacePropertiesFormat{ + IPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { Name: ptr.To("ipconfig1"), }, }, }, }, - expectedIPConfig: &network.InterfaceIPConfiguration{ + expectedIPConfig: &armnetwork.InterfaceIPConfiguration{ Name: ptr.To("ipconfig1"), }, }, { name: "GetPrimaryIPConfig should get the primary IP configuration", - nic: network.Interface{ + nic: &armnetwork.Interface{ Name: ptr.To("nic"), - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - IPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.InterfacePropertiesFormat{ + IPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { Name: ptr.To("ipconfig1"), - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ Primary: ptr.To(true), }, }, { Name: ptr.To("ipconfig2"), - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ Primary: ptr.To(false), }, }, }, }, }, - expectedIPConfig: &network.InterfaceIPConfiguration{ + expectedIPConfig: &armnetwork.InterfaceIPConfiguration{ Name: ptr.To("ipconfig1"), - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ Primary: ptr.To(true), }, }, }, { name: "GetPrimaryIPConfig should report error if nic don't have IP configuration", - nic: network.Interface{ - Name: ptr.To("nic"), - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{}, + nic: &armnetwork.Interface{ + Name: ptr.To("nic"), + Properties: &armnetwork.InterfacePropertiesFormat{}, }, - expectedErrMsg: fmt.Errorf("nic.IPConfigurations for nic (nicname=%q) is nil", "nic"), + expectedErrMsg: fmt.Errorf("nic.Properties.IPConfigurations for nic (nicname=%q) is nil", "nic"), }, { name: "GetPrimaryIPConfig should report error if node has more than one IP configuration and don't have primary IP configuration", - nic: network.Interface{ + nic: &armnetwork.Interface{ Name: ptr.To("nic"), - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - IPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.InterfacePropertiesFormat{ + IPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { Name: ptr.To("ipconfig1"), - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ Primary: ptr.To(false), }, }, { Name: ptr.To("ipconfig2"), - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ Primary: ptr.To(false), }, }, @@ -762,58 +771,58 @@ func TestGetPrimaryIPConfig(t *testing.T) { } func TestGetIPConfigByIPFamily(t *testing.T) { - ipv4IPconfig := network.InterfaceIPConfiguration{ + ipv4IPconfig := &armnetwork.InterfaceIPConfiguration{ Name: ptr.To("ipconfig1"), - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - PrivateIPAddressVersion: network.IPv4, + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ + PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), PrivateIPAddress: ptr.To("10.10.0.12"), }, } - ipv6IPconfig := network.InterfaceIPConfiguration{ + ipv6IPconfig := &armnetwork.InterfaceIPConfiguration{ Name: ptr.To("ipconfig2"), - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - PrivateIPAddressVersion: network.IPv6, + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ + PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), PrivateIPAddress: ptr.To("1111:11111:00:00:1111:1111:000:111"), }, } - testNic := network.Interface{ + testNic := &armnetwork.Interface{ Name: ptr.To("nic"), - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - IPConfigurations: &[]network.InterfaceIPConfiguration{ipv4IPconfig, ipv6IPconfig}, + Properties: &armnetwork.InterfacePropertiesFormat{ + IPConfigurations: []*armnetwork.InterfaceIPConfiguration{ipv4IPconfig, ipv6IPconfig}, }, } testcases := []struct { name string - nic network.Interface - expectedIPConfig *network.InterfaceIPConfiguration + nic *armnetwork.Interface + expectedIPConfig *armnetwork.InterfaceIPConfiguration IPv6 bool expectedErrMsg error }{ { name: "GetIPConfigByIPFamily should get the IPv6 IP configuration if IPv6 is false", nic: testNic, - expectedIPConfig: &ipv4IPconfig, + expectedIPConfig: ipv4IPconfig, }, { name: "GetIPConfigByIPFamily should get the IPv4 IP configuration if IPv6 is true", nic: testNic, IPv6: true, - expectedIPConfig: &ipv6IPconfig, + expectedIPConfig: ipv6IPconfig, }, { name: "GetIPConfigByIPFamily should report error if nic don't have IP configuration", - nic: network.Interface{ - Name: ptr.To("nic"), - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{}, + nic: &armnetwork.Interface{ + Name: ptr.To("nic"), + Properties: &armnetwork.InterfacePropertiesFormat{}, }, - expectedErrMsg: fmt.Errorf("nic.IPConfigurations for nic (nicname=%q) is nil", "nic"), + expectedErrMsg: fmt.Errorf("nic.Properties.IPConfigurations for nic (nicname=%q) is nil", "nic"), }, { name: "GetIPConfigByIPFamily should report error if nic don't have IPv6 configuration when IPv6 is true", - nic: network.Interface{ + nic: &armnetwork.Interface{ Name: ptr.To("nic"), - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - IPConfigurations: &[]network.InterfaceIPConfiguration{ipv4IPconfig}, + Properties: &armnetwork.InterfacePropertiesFormat{ + IPConfigurations: []*armnetwork.InterfaceIPConfiguration{ipv4IPconfig}, }, }, IPv6: true, @@ -821,14 +830,14 @@ func TestGetIPConfigByIPFamily(t *testing.T) { }, { name: "GetIPConfigByIPFamily should report error if nic don't have PrivateIPAddress", - nic: network.Interface{ + nic: &armnetwork.Interface{ Name: ptr.To("nic"), - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - IPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.InterfacePropertiesFormat{ + IPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { Name: ptr.To("ipconfig1"), - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - PrivateIPAddressVersion: network.IPv4, + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ + PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, @@ -918,7 +927,7 @@ func TestGetStandardInstanceIDByNodeName(t *testing.T) { defer ctrl.Finish() cloud := GetTestCloud(ctrl) - expectedVM := compute.VirtualMachine{ + expectedVM := &armcompute.VirtualMachine{ Name: ptr.To("vm1"), ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm1"), } @@ -942,7 +951,7 @@ func TestGetStandardInstanceIDByNodeName(t *testing.T) { { name: "GetInstanceIDByNodeName should report error if Error encountered when invoke mockVMClient.Get", nodeName: "vm3", - expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: VMGet error"), + expectedErrMsg: fmt.Errorf("VMGet error"), }, { name: "GetInstanceIDByNodeName should report error if ResourceID is invalid", @@ -951,21 +960,21 @@ func TestGetStandardInstanceIDByNodeName(t *testing.T) { }, } for _, test := range testcases { - mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm1", gomock.Any()).Return(expectedVM, nil).AnyTimes() - mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm2", gomock.Any()).Return(compute.VirtualMachine{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() - mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm3", gomock.Any()).Return(compute.VirtualMachine{}, &retry.Error{ - HTTPStatusCode: http.StatusInternalServerError, - RawError: fmt.Errorf("VMGet error"), + mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm2", gomock.Any()).Return(&armcompute.VirtualMachine{}, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() + mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm3", gomock.Any()).Return(&armcompute.VirtualMachine{}, &azcore.ResponseError{ + StatusCode: http.StatusInternalServerError, + ErrorCode: "VMGet error", }).AnyTimes() - mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm4", gomock.Any()).Return(compute.VirtualMachine{ + mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm4", gomock.Any()).Return(&armcompute.VirtualMachine{ Name: ptr.To("vm4"), ID: ptr.To(invalidResouceID), }, nil).AnyTimes() instanceID, err := cloud.VMSet.GetInstanceIDByNodeName(context.Background(), test.nodeName) if test.expectedErrMsg != nil { - assert.EqualError(t, test.expectedErrMsg, err.Error(), test.name) + assert.Contains(t, err.Error(), test.expectedErrMsg.Error(), test.name) } assert.Equal(t, test.expectedID, instanceID, test.name) } @@ -979,30 +988,30 @@ func TestGetStandardVMPowerStatusByNodeName(t *testing.T) { testcases := []struct { name string nodeName string - vm compute.VirtualMachine + vm *armcompute.VirtualMachine expectedStatus string - getErr *retry.Error + getErr error expectedErrMsg error }{ { name: "GetPowerStatusByNodeName should report error if node don't exist", nodeName: "vm1", - vm: compute.VirtualMachine{}, - getErr: &retry.Error{ - HTTPStatusCode: http.StatusNotFound, - RawError: cloudprovider.InstanceNotFound, + vm: &armcompute.VirtualMachine{}, + getErr: &azcore.ResponseError{ + StatusCode: http.StatusNotFound, + ErrorCode: cloudprovider.InstanceNotFound.Error(), }, expectedErrMsg: fmt.Errorf("instance not found"), }, { name: "GetPowerStatusByNodeName should get power status as expected", nodeName: "vm2", - vm: compute.VirtualMachine{ + vm: &armcompute.VirtualMachine{ Name: ptr.To("vm2"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ + Properties: &armcompute.VirtualMachineProperties{ ProvisioningState: ptr.To("Succeeded"), - InstanceView: &compute.VirtualMachineInstanceView{ - Statuses: &[]compute.InstanceViewStatus{ + InstanceView: &armcompute.VirtualMachineInstanceView{ + Statuses: []*armcompute.InstanceViewStatus{ { Code: ptr.To("PowerState/Running"), }, @@ -1013,31 +1022,31 @@ func TestGetStandardVMPowerStatusByNodeName(t *testing.T) { expectedStatus: "Running", }, { - name: "GetPowerStatusByNodeName should get vmPowerStateUnknown if vm.InstanceView is nil", + name: "GetPowerStatusByNodeName should get vmPowerStateUnknown if vm.Properties.InstanceView is nil", nodeName: "vm3", - vm: compute.VirtualMachine{ + vm: &armcompute.VirtualMachine{ Name: ptr.To("vm3"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ + Properties: &armcompute.VirtualMachineProperties{ ProvisioningState: ptr.To("Succeeded"), }, }, expectedStatus: consts.VMPowerStateUnknown, }, { - name: "GetPowerStatusByNodeName should get vmPowerStateUnknown if vm.InstanceView.statuses is nil", + name: "GetPowerStatusByNodeName should get vmPowerStateUnknown if vm.Properties.InstanceView.statuses is nil", nodeName: "vm4", - vm: compute.VirtualMachine{ + vm: &armcompute.VirtualMachine{ Name: ptr.To("vm4"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ + Properties: &armcompute.VirtualMachineProperties{ ProvisioningState: ptr.To("Succeeded"), - InstanceView: &compute.VirtualMachineInstanceView{}, + InstanceView: &armcompute.VirtualMachineInstanceView{}, }, }, expectedStatus: consts.VMPowerStateUnknown, }, } for _, test := range testcases { - mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, test.nodeName, gomock.Any()).Return(test.vm, test.getErr).AnyTimes() powerState, err := cloud.VMSet.GetPowerStatusByNodeName(context.TODO(), test.nodeName) @@ -1054,30 +1063,30 @@ func TestGetStandardVMProvisioningStateByNodeName(t *testing.T) { testcases := []struct { name string nodeName string - vm compute.VirtualMachine + vm *armcompute.VirtualMachine expectedProvisioningState string - getErr *retry.Error + getErr error expectedErrMsg error }{ { name: "GetProvisioningStateByNodeName should report error if node don't exist", nodeName: "vm1", - vm: compute.VirtualMachine{}, - getErr: &retry.Error{ - HTTPStatusCode: http.StatusNotFound, - RawError: cloudprovider.InstanceNotFound, + vm: &armcompute.VirtualMachine{}, + getErr: &azcore.ResponseError{ + StatusCode: http.StatusNotFound, + ErrorCode: cloudprovider.InstanceNotFound.Error(), }, expectedErrMsg: fmt.Errorf("instance not found"), }, { name: "GetProvisioningStateByNodeName should return Succeeded for running VM", nodeName: "vm2", - vm: compute.VirtualMachine{ + vm: &armcompute.VirtualMachine{ Name: ptr.To("vm2"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ + Properties: &armcompute.VirtualMachineProperties{ ProvisioningState: ptr.To("Succeeded"), - InstanceView: &compute.VirtualMachineInstanceView{ - Statuses: &[]compute.InstanceViewStatus{ + InstanceView: &armcompute.VirtualMachineInstanceView{ + Statuses: []*armcompute.InstanceViewStatus{ { Code: ptr.To("PowerState/Running"), }, @@ -1090,9 +1099,9 @@ func TestGetStandardVMProvisioningStateByNodeName(t *testing.T) { { name: "GetProvisioningStateByNodeName should return empty string when vm.ProvisioningState is nil", nodeName: "vm3", - vm: compute.VirtualMachine{ + vm: &armcompute.VirtualMachine{ Name: ptr.To("vm3"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ + Properties: &armcompute.VirtualMachineProperties{ ProvisioningState: nil, }, }, @@ -1100,7 +1109,7 @@ func TestGetStandardVMProvisioningStateByNodeName(t *testing.T) { }, } for _, test := range testcases { - mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, test.nodeName, gomock.Any()).Return(test.vm, test.getErr).AnyTimes() provisioningState, err := cloud.VMSet.GetProvisioningStateByNodeName(context.TODO(), test.nodeName) @@ -1118,30 +1127,30 @@ func TestGetStandardVMZoneByNodeName(t *testing.T) { testcases := []struct { name string nodeName string - vm compute.VirtualMachine + vm *armcompute.VirtualMachine expectedZone cloudprovider.Zone - getErr *retry.Error + getErr error expectedErrMsg error }{ { name: "GetZoneByNodeName should report error if node don't exist", nodeName: "vm1", - vm: compute.VirtualMachine{}, - getErr: &retry.Error{ - HTTPStatusCode: http.StatusNotFound, - RawError: cloudprovider.InstanceNotFound, + vm: &armcompute.VirtualMachine{}, + getErr: &azcore.ResponseError{ + StatusCode: http.StatusNotFound, + ErrorCode: cloudprovider.InstanceNotFound.Error(), }, expectedErrMsg: fmt.Errorf("instance not found"), }, { name: "GetZoneByNodeName should get zone as expected", nodeName: "vm2", - vm: compute.VirtualMachine{ + vm: &armcompute.VirtualMachine{ Name: ptr.To("vm2"), Location: ptr.To("EASTUS"), - Zones: &[]string{"2"}, - VirtualMachineProperties: &compute.VirtualMachineProperties{ - InstanceView: &compute.VirtualMachineInstanceView{ + Zones: to.SliceOfPtrs("2"), + Properties: &armcompute.VirtualMachineProperties{ + InstanceView: &armcompute.VirtualMachineInstanceView{ PlatformFaultDomain: &faultDomain, }, }, @@ -1154,11 +1163,11 @@ func TestGetStandardVMZoneByNodeName(t *testing.T) { { name: "GetZoneByNodeName should get FailureDomain as zone if zone is not used for node", nodeName: "vm3", - vm: compute.VirtualMachine{ + vm: &armcompute.VirtualMachine{ Name: ptr.To("vm3"), Location: ptr.To("EASTUS"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ - InstanceView: &compute.VirtualMachineInstanceView{ + Properties: &armcompute.VirtualMachineProperties{ + InstanceView: &armcompute.VirtualMachineInstanceView{ PlatformFaultDomain: &faultDomain, }, }, @@ -1171,12 +1180,12 @@ func TestGetStandardVMZoneByNodeName(t *testing.T) { { name: "GetZoneByNodeName should report error if zones is invalid", nodeName: "vm4", - vm: compute.VirtualMachine{ + vm: &armcompute.VirtualMachine{ Name: ptr.To("vm4"), Location: ptr.To("EASTUS"), - Zones: &[]string{"a"}, - VirtualMachineProperties: &compute.VirtualMachineProperties{ - InstanceView: &compute.VirtualMachineInstanceView{ + Zones: to.SliceOfPtrs("a"), + Properties: &armcompute.VirtualMachineProperties{ + InstanceView: &armcompute.VirtualMachineInstanceView{ PlatformFaultDomain: &faultDomain, }, }, @@ -1185,7 +1194,7 @@ func TestGetStandardVMZoneByNodeName(t *testing.T) { }, } for _, test := range testcases { - mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, test.nodeName, gomock.Any()).Return(test.vm, test.getErr).AnyTimes() zone, err := cloud.VMSet.GetZoneByNodeName(context.TODO(), test.nodeName) @@ -1200,43 +1209,43 @@ func TestGetStandardVMSetNames(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - testVM := compute.VirtualMachine{ + testVM := &armcompute.VirtualMachine{ Name: ptr.To("vm1"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ - AvailabilitySet: &compute.SubResource{ID: ptr.To(asID)}, + Properties: &armcompute.VirtualMachineProperties{ + AvailabilitySet: &armcompute.SubResource{ID: ptr.To(asID)}, }, } - testVMWithoutAS := compute.VirtualMachine{ - Name: ptr.To("vm2"), - VirtualMachineProperties: &compute.VirtualMachineProperties{}, + testVMWithoutAS := &armcompute.VirtualMachine{ + Name: ptr.To("vm2"), + Properties: &armcompute.VirtualMachineProperties{}, } testCases := []struct { name string - vm []compute.VirtualMachine + vm []*armcompute.VirtualMachine service *v1.Service nodes []*v1.Node usingSingleSLBS bool - expectedVMSetNames *[]string + expectedVMSetNames []*string expectedErrMsg error }{ { name: "GetVMSetNames should return the primary vm set name if the service has no mode annotation", - vm: []compute.VirtualMachine{testVM}, + vm: []*armcompute.VirtualMachine{testVM}, service: &v1.Service{}, - expectedVMSetNames: &[]string{"as"}, + expectedVMSetNames: to.SliceOfPtrs("as"), }, { name: "GetVMSetNames should return the primary vm set name when using the single SLB", - vm: []compute.VirtualMachine{testVM}, + vm: []*armcompute.VirtualMachine{testVM}, service: &v1.Service{ ObjectMeta: meta.ObjectMeta{Annotations: map[string]string{consts.ServiceAnnotationLoadBalancerMode: consts.ServiceAnnotationLoadBalancerAutoModeValue}}, }, usingSingleSLBS: true, - expectedVMSetNames: &[]string{"as"}, + expectedVMSetNames: to.SliceOfPtrs("as"), }, { name: "GetVMSetNames should return the correct as names if the service has auto mode annotation", - vm: []compute.VirtualMachine{testVM}, + vm: []*armcompute.VirtualMachine{testVM}, service: &v1.Service{ ObjectMeta: meta.ObjectMeta{Annotations: map[string]string{consts.ServiceAnnotationLoadBalancerMode: consts.ServiceAnnotationLoadBalancerAutoModeValue}}, }, @@ -1247,11 +1256,11 @@ func TestGetStandardVMSetNames(t *testing.T) { }, }, }, - expectedVMSetNames: &[]string{"myavailabilityset"}, + expectedVMSetNames: to.SliceOfPtrs("myavailabilityset"), }, { name: "GetVMSetNames should return the correct as names if node don't have availability set", - vm: []compute.VirtualMachine{testVMWithoutAS}, + vm: []*armcompute.VirtualMachine{testVMWithoutAS}, service: &v1.Service{ ObjectMeta: meta.ObjectMeta{Annotations: map[string]string{consts.ServiceAnnotationLoadBalancerMode: consts.ServiceAnnotationLoadBalancerAutoModeValue}}, }, @@ -1266,7 +1275,7 @@ func TestGetStandardVMSetNames(t *testing.T) { }, { name: "GetVMSetNames should report the error if there's no such availability set", - vm: []compute.VirtualMachine{testVM}, + vm: []*armcompute.VirtualMachine{testVM}, service: &v1.Service{ ObjectMeta: meta.ObjectMeta{Annotations: map[string]string{consts.ServiceAnnotationLoadBalancerMode: "vm2"}}, }, @@ -1281,7 +1290,7 @@ func TestGetStandardVMSetNames(t *testing.T) { }, { name: "GetVMSetNames should return the correct node name", - vm: []compute.VirtualMachine{testVM}, + vm: []*armcompute.VirtualMachine{testVM}, service: &v1.Service{ ObjectMeta: meta.ObjectMeta{Annotations: map[string]string{consts.ServiceAnnotationLoadBalancerMode: "myAvailabilitySet"}}, }, @@ -1292,16 +1301,16 @@ func TestGetStandardVMSetNames(t *testing.T) { }, }, }, - expectedVMSetNames: &[]string{"myAvailabilitySet"}, + expectedVMSetNames: to.SliceOfPtrs("myAvailabilitySet"), }, } for _, test := range testCases { cloud := GetTestCloud(ctrl) if test.usingSingleSLBS { - cloud.LoadBalancerSku = consts.LoadBalancerSkuStandard + cloud.LoadBalancerSKU = consts.LoadBalancerSKUStandard } - mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) mockVMClient.EXPECT().List(gomock.Any(), cloud.ResourceGroup).Return(test.vm, nil).AnyTimes() vmSetNames, err := cloud.VMSet.GetVMSetNames(context.TODO(), test.service, test.nodes) @@ -1337,9 +1346,6 @@ func TestExtractResourceGroupByNicID(t *testing.T) { } func TestStandardEnsureHostInPool(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - cloud := GetTestCloud(ctrl) availabilitySetID := asID backendAddressPoolID := "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb1-internal/backendAddressPools/backendpool-1" @@ -1352,7 +1358,7 @@ func TestStandardEnsureHostInPool(t *testing.T) { nicName string nicID string vmSetName string - nicProvisionState network.ProvisioningState + nicProvisionState *armnetwork.ProvisioningState isStandardLB bool expectedErrMsg error }{ @@ -1379,7 +1385,7 @@ func TestStandardEnsureHostInPool(t *testing.T) { nodeName: "vm3", nicName: "nic3", nicID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic3", - nicProvisionState: consts.NicFailedState, + nicProvisionState: to.Ptr(armnetwork.ProvisioningStateFailed), vmSetName: "myAvailabilitySet", }, { @@ -1417,34 +1423,40 @@ func TestStandardEnsureHostInPool(t *testing.T) { backendPoolID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb2-internal/backendAddressPool/backendpool-3", nodeName: "vm8", nicName: "nic8", - nicID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic7", + nicID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic8", vmSetName: "myAvailabilitySet", expectedErrMsg: fmt.Errorf("new backendPoolID %q is in wrong format", "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb2-internal/backendAddressPool/backendpool-3"), }, } for _, test := range testCases { - if test.isStandardLB { - cloud.Config.LoadBalancerSku = consts.LoadBalancerSkuStandard - } + test := test + t.Run(test.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + cloud := GetTestCloud(ctrl) + if test.isStandardLB { + cloud.Config.LoadBalancerSKU = consts.LoadBalancerSKUStandard + } - testVM := buildDefaultTestVirtualMachine(availabilitySetID, []string{test.nicID}) - testVM.Name = ptr.To(string(test.nodeName)) - testNIC := buildDefaultTestInterface(false, []string{backendAddressPoolID}) - testNIC.Name = ptr.To(test.nicName) - testNIC.ID = ptr.To(test.nicID) - testNIC.ProvisioningState = test.nicProvisionState + testVM := buildDefaultTestVirtualMachine(availabilitySetID, []string{test.nicID}) + testVM.Name = ptr.To(string(test.nodeName)) + testNIC := buildDefaultTestInterface(false, []string{backendAddressPoolID}) + testNIC.Name = ptr.To(test.nicName) + testNIC.ID = ptr.To(test.nicID) + testNIC.Properties.ProvisioningState = test.nicProvisionState - mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, string(test.nodeName), gomock.Any()).Return(testVM, nil).AnyTimes() + mockVMClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, string(test.nodeName), gomock.Any()).Return(testVM, nil).AnyTimes() - mockInterfaceClient := cloud.InterfacesClient.(*mockinterfaceclient.MockInterface) - mockInterfaceClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, test.nicName, gomock.Any()).Return(testNIC, nil).AnyTimes() - mockInterfaceClient.EXPECT().CreateOrUpdate(gomock.Any(), cloud.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + mockInterfaceClient := cloud.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) + mockInterfaceClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, test.nicName, gomock.Any()).Return(testNIC, nil).AnyTimes() + mockInterfaceClient.EXPECT().CreateOrUpdate(gomock.Any(), cloud.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - _, _, _, vm, err := cloud.VMSet.EnsureHostInPool(context.Background(), test.service, test.nodeName, test.backendPoolID, test.vmSetName) - assert.Equal(t, test.expectedErrMsg, err, test.name) - assert.Nil(t, vm, test.name) + _, _, _, vm, err := cloud.VMSet.EnsureHostInPool(context.Background(), test.service, test.nodeName, test.backendPoolID, test.vmSetName) + assert.Equal(t, test.expectedErrMsg, err, test.name) + assert.Nil(t, vm, test.name) + }) } } @@ -1541,7 +1553,7 @@ func TestStandardEnsureHostsInPool(t *testing.T) { for _, test := range testCases { t.Run(test.name, func(t *testing.T) { - cloud.Config.LoadBalancerSku = consts.LoadBalancerSkuStandard + cloud.Config.LoadBalancerSKU = consts.LoadBalancerSKUStandard cloud.Config.ExcludeMasterFromStandardLB = ptr.To(true) cloud.excludeLoadBalancerNodes = utilsets.NewString(test.excludeLBNodes...) @@ -1550,12 +1562,12 @@ func TestStandardEnsureHostsInPool(t *testing.T) { testNIC.Name = ptr.To(test.nicName) testNIC.ID = ptr.To(test.nicID) - mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, test.nodeName, gomock.Any()).Return(testVM, nil).AnyTimes() - mockInterfaceClient := cloud.InterfacesClient.(*mockinterfaceclient.MockInterface) + mockInterfaceClient := cloud.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) mockInterfaceClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, test.nicName, gomock.Any()).Return(testNIC, nil).AnyTimes() - mockInterfaceClient.EXPECT().CreateOrUpdate(gomock.Any(), cloud.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + mockInterfaceClient.EXPECT().CreateOrUpdate(gomock.Any(), cloud.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() err := cloud.VMSet.EnsureHostsInPool(context.Background(), test.service, test.nodes, test.backendPoolID, test.vmSetName) if test.expectedErr { @@ -1577,18 +1589,18 @@ func TestStandardEnsureBackendPoolDeleted(t *testing.T) { tests := []struct { desc string - backendAddressPools *[]network.BackendAddressPool + backendAddressPools []*armnetwork.BackendAddressPool loadBalancerSKU string - existingVM compute.VirtualMachine - existingNIC network.Interface + existingVM *armcompute.VirtualMachine + existingNIC *armnetwork.Interface }{ { desc: "EnsureBackendPoolDeleted should decouple the nic and the load balancer properly", - backendAddressPools: &[]network.BackendAddressPool{ + backendAddressPools: []*armnetwork.BackendAddressPool{ { ID: ptr.To(backendPoolID), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1"), }, @@ -1604,17 +1616,15 @@ func TestStandardEnsureBackendPoolDeleted(t *testing.T) { } for _, test := range tests { - cloud.LoadBalancerSku = test.loadBalancerSKU - mockVMClient := mockvmclient.NewMockInterface(ctrl) + cloud.LoadBalancerSKU = test.loadBalancerSKU + mockVMClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "k8s-agentpool1-00000000-1", gomock.Any()).Return(test.existingVM, nil) - cloud.VirtualMachinesClient = mockVMClient - mockNICClient := mockinterfaceclient.NewMockInterface(ctrl) - test.existingNIC.VirtualMachine = &network.SubResource{ + mockNICClient := cloud.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) + test.existingNIC.Properties.VirtualMachine = &armnetwork.SubResource{ ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/k8s-agentpool1-00000000-1"), } mockNICClient.EXPECT().Get(gomock.Any(), "rg", "k8s-agentpool1-00000000-nic-1", gomock.Any()).Return(test.existingNIC, nil).Times(2) - mockNICClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) - cloud.InterfacesClient = mockNICClient + mockNICClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil) nicUpdated, err := cloud.VMSet.EnsureBackendPoolDeleted(context.TODO(), &service, []string{backendPoolID}, vmSetName, test.backendAddressPools, true) assert.NoError(t, err, test.desc) @@ -1622,45 +1632,45 @@ func TestStandardEnsureBackendPoolDeleted(t *testing.T) { } } -func buildDefaultTestInterface(isPrimary bool, lbBackendpoolIDs []string) network.Interface { - expectedNIC := network.Interface{ - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - ProvisioningState: network.ProvisioningStateSucceeded, - IPConfigurations: &[]network.InterfaceIPConfiguration{ +func buildDefaultTestInterface(isPrimary bool, lbBackendpoolIDs []string) *armnetwork.Interface { + expectedNIC := &armnetwork.Interface{ + Properties: &armnetwork.InterfacePropertiesFormat{ + ProvisioningState: to.Ptr(armnetwork.ProvisioningStateSucceeded), + IPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ Primary: ptr.To(isPrimary), }, }, }, }, } - backendAddressPool := make([]network.BackendAddressPool, 0) + backendAddressPool := make([]*armnetwork.BackendAddressPool, 0) for _, id := range lbBackendpoolIDs { - backendAddressPool = append(backendAddressPool, network.BackendAddressPool{ + backendAddressPool = append(backendAddressPool, &armnetwork.BackendAddressPool{ ID: ptr.To(id), }) } - (*expectedNIC.IPConfigurations)[0].LoadBalancerBackendAddressPools = &backendAddressPool + (expectedNIC.Properties.IPConfigurations)[0].Properties.LoadBalancerBackendAddressPools = backendAddressPool return expectedNIC } -func buildDefaultTestVirtualMachine(asID string, nicIDs []string) compute.VirtualMachine { - expectedVM := compute.VirtualMachine{ - VirtualMachineProperties: &compute.VirtualMachineProperties{ - AvailabilitySet: &compute.SubResource{ +func buildDefaultTestVirtualMachine(asID string, nicIDs []string) *armcompute.VirtualMachine { + expectedVM := &armcompute.VirtualMachine{ + Properties: &armcompute.VirtualMachineProperties{ + AvailabilitySet: &armcompute.SubResource{ ID: ptr.To(asID), }, - NetworkProfile: &compute.NetworkProfile{}, + NetworkProfile: &armcompute.NetworkProfile{}, }, } - networkInterfaces := make([]compute.NetworkInterfaceReference, 0) + networkInterfaces := make([]*armcompute.NetworkInterfaceReference, 0) for _, nicID := range nicIDs { - networkInterfaces = append(networkInterfaces, compute.NetworkInterfaceReference{ + networkInterfaces = append(networkInterfaces, &armcompute.NetworkInterfaceReference{ ID: ptr.To(nicID), }) } - expectedVM.VirtualMachineProperties.NetworkProfile.NetworkInterfaces = &networkInterfaces + expectedVM.Properties.NetworkProfile.NetworkInterfaces = networkInterfaces return expectedVM } @@ -1670,13 +1680,13 @@ func TestStandardGetNodeNameByIPConfigurationID(t *testing.T) { cloud := GetTestCloud(ctrl) expectedVM := buildDefaultTestVirtualMachine("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/availabilitySets/AGENTPOOL1-AVAILABILITYSET-00000000", []string{}) expectedVM.Name = ptr.To("name") - mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMClient := cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), "rg", "k8s-agentpool1-00000000-0", gomock.Any()).Return(expectedVM, nil) expectedNIC := buildDefaultTestInterface(true, []string{}) - expectedNIC.VirtualMachine = &network.SubResource{ + expectedNIC.Properties.VirtualMachine = &armnetwork.SubResource{ ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/k8s-agentpool1-00000000-0"), } - mockNICClient := cloud.InterfacesClient.(*mockinterfaceclient.MockInterface) + mockNICClient := cloud.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) mockNICClient.EXPECT().Get(gomock.Any(), "rg", "k8s-agentpool1-00000000-nic-0", gomock.Any()).Return(expectedNIC, nil) ipConfigurationID := `/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-0/ipConfigurations/ipconfig1` nodeName, asName, err := cloud.VMSet.GetNodeNameByIPConfigurationID(context.TODO(), ipConfigurationID) @@ -1686,14 +1696,12 @@ func TestStandardGetNodeNameByIPConfigurationID(t *testing.T) { } func TestGetAvailabilitySetByNodeName(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string nodeName string vmasVMIDs []string - vmasListError *retry.Error + vmasListError error expectedErr error }{ { @@ -1711,8 +1719,8 @@ func TestGetAvailabilitySetByNodeName(t *testing.T) { description: "getAvailabilitySetByNodeName should report an error if there's something wrong during an api call", nodeName: "vm-1", vmasVMIDs: []string{"/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm-1"}, - vmasListError: &retry.Error{RawError: fmt.Errorf("error during vmas list")}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: error during vmas list"), + vmasListError: &azcore.ResponseError{ErrorCode: "error during vmas list"}, + expectedErr: fmt.Errorf("error during vmas list"), }, { description: "getAvailabilitySetByNodeName should report an error if the vmID on the vmas is invalid", @@ -1723,35 +1731,39 @@ func TestGetAvailabilitySetByNodeName(t *testing.T) { } for _, test := range testCases { - cloud := GetTestCloud(ctrl) - vmSet, err := newAvailabilitySet(cloud) - assert.NoError(t, err) - as := vmSet.(*availabilitySet) + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - mockVMASClient := mockvmasclient.NewMockInterface(ctrl) - cloud.AvailabilitySetsClient = mockVMASClient + cloud := GetTestCloud(ctrl) + vmSet, err := newAvailabilitySet(cloud) + assert.NoError(t, err) + as := vmSet.(*availabilitySet) - subResources := make([]compute.SubResource, 0) - for _, vmID := range test.vmasVMIDs { - subResources = append(subResources, compute.SubResource{ - ID: ptr.To(vmID), - }) - } - expected := compute.AvailabilitySet{ - Name: ptr.To("vmas-1"), - AvailabilitySetProperties: &compute.AvailabilitySetProperties{ - VirtualMachines: &subResources, - }, - } - mockVMASClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.AvailabilitySet{expected}, test.vmasListError).AnyTimes() + mockVMASClient := cloud.ComputeClientFactory.GetAvailabilitySetClient().(*mock_availabilitysetclient.MockInterface) - actual, err := as.getAvailabilitySetByNodeName(context.TODO(), test.nodeName, azcache.CacheReadTypeDefault) - if test.expectedErr != nil { - assert.EqualError(t, test.expectedErr, err.Error(), test.description) - } - if actual != nil { - assert.Equal(t, expected, *actual, test.description) - } + subResources := make([]*armcompute.SubResource, 0) + for _, vmID := range test.vmasVMIDs { + subResources = append(subResources, &armcompute.SubResource{ + ID: ptr.To(vmID), + }) + } + expected := &armcompute.AvailabilitySet{ + Name: ptr.To("vmas-1"), + Properties: &armcompute.AvailabilitySetProperties{ + VirtualMachines: subResources, + }, + } + mockVMASClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.AvailabilitySet{expected}, test.vmasListError).AnyTimes() + + actual, err := as.getAvailabilitySetByNodeName(context.TODO(), test.nodeName, azcache.CacheReadTypeDefault) + if test.expectedErr != nil { + assert.Contains(t, err.Error(), test.expectedErr.Error(), test.description) + } + if actual != nil { + assert.Equal(t, *expected, *actual, test.description) + } + }) } } @@ -1810,19 +1822,18 @@ func TestGetNodeCIDRMasksByProviderIDAvailabilitySet(t *testing.T) { assert.NoError(t, err) as := vmSet.(*availabilitySet) - mockVMASClient := mockvmasclient.NewMockInterface(ctrl) - cloud.AvailabilitySetsClient = mockVMASClient + mockVMASClient := cloud.ComputeClientFactory.GetAvailabilitySetClient().(*mock_availabilitysetclient.MockInterface) - expected := compute.AvailabilitySet{ + expected := &armcompute.AvailabilitySet{ Name: ptr.To("vmas-1"), - AvailabilitySetProperties: &compute.AvailabilitySetProperties{ - VirtualMachines: &[]compute.SubResource{ + Properties: &armcompute.AvailabilitySetProperties{ + VirtualMachines: []*armcompute.SubResource{ {ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm-0")}, }, }, Tags: tc.tags, } - mockVMASClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.AvailabilitySet{expected}, nil).AnyTimes() + mockVMASClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.AvailabilitySet{expected}, nil).AnyTimes() ipv4MaskSize, ipv6MaskSize, err := as.GetNodeCIDRMasksByProviderID(context.TODO(), tc.providerID) assert.Equal(t, tc.expectedErr, err) @@ -1862,8 +1873,8 @@ func TestGetNodeVMSetName(t *testing.T) { description string node *v1.Node listTimes int - expectedVMs []compute.VirtualMachine - listErr *retry.Error + expectedVMs []*armcompute.VirtualMachine + listErr error expectedVMSetName string expectedErr error }{ @@ -1884,8 +1895,8 @@ func TestGetNodeVMSetName(t *testing.T) { }, }, listTimes: 1, - listErr: retry.NewError(false, errors.New("error")), - expectedErr: retry.NewError(false, errors.New("error")).Error(), + listErr: &azcore.ResponseError{ErrorCode: "error"}, + expectedErr: &azcore.ResponseError{ErrorCode: "error"}, }, { description: "GetNodeVMSetName should report an error if the availability set ID of the vm is not legal", @@ -1899,11 +1910,11 @@ func TestGetNodeVMSetName(t *testing.T) { }, }, }, - expectedVMs: []compute.VirtualMachine{ + expectedVMs: []*armcompute.VirtualMachine{ { Name: ptr.To("vm"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ - AvailabilitySet: &compute.SubResource{ + Properties: &armcompute.VirtualMachineProperties{ + AvailabilitySet: &armcompute.SubResource{ ID: ptr.To("/"), }, }, @@ -1924,11 +1935,11 @@ func TestGetNodeVMSetName(t *testing.T) { }, }, }, - expectedVMs: []compute.VirtualMachine{ + expectedVMs: []*armcompute.VirtualMachine{ { Name: ptr.To("vm"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ - AvailabilitySet: &compute.SubResource{ + Properties: &armcompute.VirtualMachineProperties{ + AvailabilitySet: &armcompute.SubResource{ ID: ptr.To("as"), }, }, @@ -1939,16 +1950,17 @@ func TestGetNodeVMSetName(t *testing.T) { }, } { az := GetTestCloud(ctrl) - vmClient := mockvmclient.NewMockInterface(ctrl) + vmClient := az.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) vmClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.expectedVMs, tc.listErr).Times(tc.listTimes) - az.VirtualMachinesClient = vmClient vmSet, err := newAvailabilitySet(az) assert.NoError(t, err) as := vmSet.(*availabilitySet) vmSetName, err := as.GetNodeVMSetName(context.TODO(), tc.node) - assert.Equal(t, tc.expectedErr, err, tc.description) + if tc.expectedErr != nil { + assert.Contains(t, tc.expectedErr.Error(), err.Error(), tc.description) + } assert.Equal(t, tc.expectedVMSetName, vmSetName, tc.description) } } @@ -2025,7 +2037,7 @@ func TestGetPublicIPName(t *testing.T) { testcases := []struct { desc string svc *v1.Service - pips []network.PublicIPAddress + pips []*armnetwork.PublicIPAddress isIPv6 bool expectedPIPName string }{ diff --git a/pkg/provider/azure_subnet_repo.go b/pkg/provider/azure_subnet_repo.go deleted file mode 100644 index 5d3e449cb3..0000000000 --- a/pkg/provider/azure_subnet_repo.go +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright 2023 The Kubernetes Authors. - -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. -*/ - -package provider - -import ( - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - v1 "k8s.io/api/core/v1" - "k8s.io/klog/v2" -) - -// CreateOrUpdateSubnet invokes az.SubnetClient.CreateOrUpdate with exponential backoff retry -func (az *Cloud) CreateOrUpdateSubnet(service *v1.Service, subnet network.Subnet) error { - ctx, cancel := getContextWithCancel() - defer cancel() - - var rg string - if len(az.VnetResourceGroup) > 0 { - rg = az.VnetResourceGroup - } else { - rg = az.ResourceGroup - } - - rerr := az.SubnetsClient.CreateOrUpdate(ctx, rg, az.VnetName, *subnet.Name, subnet) - klog.V(10).Infof("SubnetClient.CreateOrUpdate(%s): end", *subnet.Name) - if rerr != nil { - klog.Errorf("SubnetClient.CreateOrUpdate(%s) failed: %s", *subnet.Name, rerr.Error().Error()) - az.Event(service, v1.EventTypeWarning, "CreateOrUpdateSubnet", rerr.Error().Error()) - return rerr.Error() - } - - return nil -} - -func (az *Cloud) getSubnet(vnetResourceGroup, virtualNetworkName, subnetName string) (network.Subnet, bool, error) { - if vnetResourceGroup == "" { - if len(az.VnetResourceGroup) > 0 { - vnetResourceGroup = az.VnetResourceGroup - } else { - vnetResourceGroup = az.ResourceGroup - } - } - - ctx, cancel := getContextWithCancel() - defer cancel() - subnet, err := az.SubnetsClient.Get(ctx, vnetResourceGroup, virtualNetworkName, subnetName, "") - exists, rerr := checkResourceExistsFromError(err) - if rerr != nil { - return subnet, false, rerr.Error() - } - - if !exists { - klog.V(2).Infof("Subnet %q not found", subnetName) - } - return subnet, exists, nil -} diff --git a/pkg/provider/azure_test.go b/pkg/provider/azure_test.go index 6e6d9c4a8d..de85097339 100644 --- a/pkg/provider/azure_test.go +++ b/pkg/provider/azure_test.go @@ -20,17 +20,17 @@ import ( "context" "errors" "fmt" - "math" "net/http" "os" "strings" "testing" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" v1 "k8s.io/api/core/v1" @@ -45,19 +45,17 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/azclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader" - "sigs.k8s.io/cloud-provider-azure/pkg/azclient/mock_azclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/mock_interfaceclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/loadbalancerclient/mock_loadbalancerclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipaddressclient/mock_publicipaddressclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/securitygroupclient/mock_securitygroupclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient/mockloadbalancerclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/subnetclient/mocksubnetclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" providerconfig "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" "sigs.k8s.io/cloud-provider-azure/pkg/provider/privatelinkservice" + "sigs.k8s.io/cloud-provider-azure/pkg/provider/subnet" "sigs.k8s.io/cloud-provider-azure/pkg/provider/zone" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" "sigs.k8s.io/cloud-provider-azure/pkg/util/taints" ) @@ -98,7 +96,7 @@ func TestAddPort(t *testing.T) { az := GetTestCloud(ctrl) svc := getTestService("service1", v1.ProtocolTCP, nil, false, 80) clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1) - setMockEnv(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnv(az, expectedInterfaces, expectedVirtualMachines, 1) svc.Spec.Ports = append(svc.Spec.Ports, v1.ServicePort{ Name: fmt.Sprintf("port-udp-%d", 1234), @@ -107,108 +105,70 @@ func TestAddPort(t *testing.T) { NodePort: getBackendPort(1234), }) - expectedLBs := make([]network.LoadBalancer, 0) - setMockLBs(az, ctrl, &expectedLBs, "service", 1, 1, false) + expectedLBs := make([]*armnetwork.LoadBalancer, 0) + setMockLBs(az, &expectedLBs, "service", 1, 1, false) mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { return false, false, lb, nil }).AnyTimes() mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + mockPLSRepo := az.plsRepo.(*privatelinkservice.MockRepository) + mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil).AnyTimes() lb, err := az.reconcileLoadBalancer(context.TODO(), testClusterName, &svc, clusterResources.nodes, true /* wantLb */) assert.Nil(t, err) // ensure we got a frontend ip configuration - if len(*lb.FrontendIPConfigurations) != 1 { + if len(lb.Properties.FrontendIPConfigurations) != 1 { t.Error("Expected the loadbalancer to have a frontend ip configuration") } - validateLoadBalancer(t, lb, svc) -} - -func TestLoadBalancerSelection(t *testing.T) { - testcases := []struct { - desc string - isInternal bool - }{ - { - desc: "internal", - isInternal: true, - }, - { - desc: "external", - isInternal: false, - }, - } - - for _, tc := range testcases { - t.Run(tc.desc, func(t *testing.T) { - t.Run("defaultModeSelection", func(t *testing.T) { - testLoadBalancerServiceDefaultModeSelection(t, tc.isInternal) - }) - t.Run("autoModeSelection", func(t *testing.T) { - testLoadBalancerServiceAutoModeSelection(t, tc.isInternal) - }) - t.Run("specifiedSelection", func(t *testing.T) { - testLoadBalancerServicesSpecifiedSelection(t, tc.isInternal) - }) - t.Run("maxRulesServices", func(t *testing.T) { - testLoadBalancerMaxRulesServices(t, tc.isInternal) - }) - t.Run("autoModeDeleteSelection", func(t *testing.T) { - testLoadBalancerServiceAutoModeDeleteSelection(t, tc.isInternal) - }) - }) - } + validateLoadBalancer(t, az, lb, svc) } -func setMockEnvDualStack(az *Cloud, ctrl *gomock.Controller, expectedInterfaces []network.Interface, expectedVirtualMachines []compute.VirtualMachine, serviceCount int, services ...v1.Service) { - mockInterfacesClient := mockinterfaceclient.NewMockInterface(ctrl) - az.InterfacesClient = mockInterfacesClient +func setMockEnvDualStack(az *Cloud, expectedInterfaces []*armnetwork.Interface, expectedVirtualMachines []*armcompute.VirtualMachine, serviceCount int, services ...v1.Service) { + mockInterfacesClient := az.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) for i := range expectedInterfaces { mockInterfacesClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("vm-%d", i), gomock.Any()).Return(expectedInterfaces[i], nil).AnyTimes() - mockInterfacesClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, fmt.Sprintf("vm-%d", i), gomock.Any()).Return(nil).AnyTimes() + mockInterfacesClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, fmt.Sprintf("vm-%d", i), gomock.Any()).Return(nil, nil).AnyTimes() } - mockVirtualMachinesClient := mockvmclient.NewMockInterface(ctrl) - az.VirtualMachinesClient = mockVirtualMachinesClient - mockVirtualMachinesClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(expectedVirtualMachines, nil).AnyTimes() + vmClient := az.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + vmClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(expectedVirtualMachines, nil).AnyTimes() for i := range expectedVirtualMachines { - mockVirtualMachinesClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("vm-%d", i), gomock.Any()).Return(expectedVirtualMachines[i], nil).AnyTimes() + vmClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("vm-%d", i), gomock.Any()).Return(expectedVirtualMachines[i], nil).AnyTimes() } - setMockPublicIPs(az, ctrl, serviceCount, true, true) + setMockPublicIPs(az, serviceCount, true, true) sg := getTestSecurityGroupDualStack(az, services...) setMockSecurityGroup(az, sg) } -func setMockEnv(az *Cloud, ctrl *gomock.Controller, expectedInterfaces []network.Interface, expectedVirtualMachines []compute.VirtualMachine, serviceCount int, services ...v1.Service) { - mockInterfacesClient := mockinterfaceclient.NewMockInterface(ctrl) - az.InterfacesClient = mockInterfacesClient +func setMockEnv(az *Cloud, expectedInterfaces []*armnetwork.Interface, expectedVirtualMachines []*armcompute.VirtualMachine, serviceCount int, services ...v1.Service) { + mockInterfacesClient := az.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) for i := range expectedInterfaces { mockInterfacesClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("vm-%d", i), gomock.Any()).Return(expectedInterfaces[i], nil).AnyTimes() - mockInterfacesClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, fmt.Sprintf("vm-%d", i), gomock.Any()).Return(nil).AnyTimes() + mockInterfacesClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, fmt.Sprintf("vm-%d", i), gomock.Any()).Return(nil, nil).AnyTimes() } - mockVirtualMachinesClient := mockvmclient.NewMockInterface(ctrl) - az.VirtualMachinesClient = mockVirtualMachinesClient - mockVirtualMachinesClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(expectedVirtualMachines, nil).AnyTimes() + vmClient := az.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + vmClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(expectedVirtualMachines, nil).AnyTimes() for i := range expectedVirtualMachines { - mockVirtualMachinesClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("vm-%d", i), gomock.Any()).Return(expectedVirtualMachines[i], nil).AnyTimes() + vmClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("vm-%d", i), gomock.Any()).Return(expectedVirtualMachines[i], nil).AnyTimes() } - setMockPublicIPs(az, ctrl, serviceCount, true, false) + setMockPublicIPs(az, serviceCount, true, false) sg := getTestSecurityGroup(az, services...) setMockSecurityGroup(az, sg) } -func setMockPublicIPs(az *Cloud, ctrl *gomock.Controller, serviceCount int, v4Enabled, v6Enabled bool) { - mockPIPsClient := mockpublicipclient.NewMockInterface(ctrl) +func setMockPublicIPs(az *Cloud, serviceCount int, v4Enabled, v6Enabled bool) { + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) - expectedPIPsTotal := []network.PublicIPAddress{} + expectedPIPsTotal := []*armnetwork.PublicIPAddress{} if v4Enabled { expectedPIPs := setMockPublicIP(az, mockPIPsClient, serviceCount, false) expectedPIPsTotal = append(expectedPIPsTotal, expectedPIPs...) @@ -219,29 +179,28 @@ func setMockPublicIPs(az *Cloud, ctrl *gomock.Controller, serviceCount int, v4En } mockPIPsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(expectedPIPsTotal, nil).AnyTimes() - az.PublicIPAddressesClient = mockPIPsClient - mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() mockPIPsClient.EXPECT().List(gomock.Any(), gomock.Not(az.ResourceGroup)).Return(nil, nil).AnyTimes() - mockPIPsClient.EXPECT().Get(gomock.Any(), gomock.Not(az.ResourceGroup), gomock.Any(), gomock.Any()).Return(network.PublicIPAddress{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockPIPsClient.EXPECT().Get(gomock.Any(), gomock.Not(az.ResourceGroup), gomock.Any(), gomock.Any()).Return(&armnetwork.PublicIPAddress{}, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() } -func setMockPublicIP(az *Cloud, mockPIPsClient *mockpublicipclient.MockInterface, serviceCount int, isIPv6 bool) []network.PublicIPAddress { +func setMockPublicIP(az *Cloud, mockPIPsClient *mock_publicipaddressclient.MockInterface, serviceCount int, isIPv6 bool) []*armnetwork.PublicIPAddress { suffix := "" - ipVer := network.IPv4 + ipVer := to.Ptr(armnetwork.IPVersionIPv4) ipAddr1 := "1.2.3.4" ipAddra := "1.2.3.5" if isIPv6 { suffix = "-" + consts.IPVersionIPv6String - ipVer = network.IPv6 + ipVer = to.Ptr(armnetwork.IPVersionIPv6) ipAddr1 = "fd00::eef0" ipAddra = "fd00::eef1" } - expectedPIP := network.PublicIPAddress{ + expectedPIP := &armnetwork.PublicIPAddress{ Name: ptr.To("testCluster-aservicea"), Location: &az.Location, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAllocationMethod: network.Static, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), PublicIPAddressVersion: ipVer, IPAddress: ptr.To(ipAddr1), }, @@ -249,33 +208,36 @@ func setMockPublicIP(az *Cloud, mockPIPsClient *mockpublicipclient.MockInterface consts.ServiceTagKey: ptr.To("default/servicea"), consts.ClusterNameKey: ptr.To(testClusterName), }, - Sku: &network.PublicIPAddressSku{ - Name: network.PublicIPAddressSkuNameStandard, + SKU: &armnetwork.PublicIPAddressSKU{ + Name: to.Ptr(armnetwork.PublicIPAddressSKUNameStandard), }, ID: ptr.To("testCluster-aservice1"), } a := 'a' - var expectedPIPs []network.PublicIPAddress + var expectedPIPs []*armnetwork.PublicIPAddress for i := 1; i <= serviceCount; i++ { expectedPIP.Name = ptr.To(fmt.Sprintf("testCluster-aservice%d%s", i, suffix)) expectedPIP.ID = ptr.To(fmt.Sprintf("testCluster-aservice%d%s", i, suffix)) - expectedPIP.PublicIPAddressPropertiesFormat = &network.PublicIPAddressPropertiesFormat{ - PublicIPAllocationMethod: network.Static, + expectedPIP.Properties = &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), PublicIPAddressVersion: ipVer, IPAddress: ptr.To(ipAddr1), } + expectedPIP.Tags = make(map[string]*string) expectedPIP.Tags[consts.ServiceTagKey] = ptr.To(fmt.Sprintf("default/service%d", i)) mockPIPsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%d%s", i, suffix), gomock.Any()).Return(expectedPIP, nil).AnyTimes() mockPIPsClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%d%s", i, suffix)).Return(nil).AnyTimes() expectedPIPs = append(expectedPIPs, expectedPIP) + expectedPIP := &armnetwork.PublicIPAddress{} expectedPIP.Name = ptr.To(fmt.Sprintf("testCluster-aservice%c%s", a, suffix)) expectedPIP.ID = ptr.To(fmt.Sprintf("testCluster-aservice%c%s", a, suffix)) - expectedPIP.PublicIPAddressPropertiesFormat = &network.PublicIPAddressPropertiesFormat{ - PublicIPAllocationMethod: network.Static, + expectedPIP.Properties = &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), PublicIPAddressVersion: ipVer, IPAddress: ptr.To(ipAddra), } + expectedPIP.Tags = make(map[string]*string) expectedPIP.Tags[consts.ServiceTagKey] = ptr.To(fmt.Sprintf("default/service%c", a)) mockPIPsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%c%s", a, suffix), gomock.Any()).Return(expectedPIP, nil).AnyTimes() mockPIPsClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%c%s", a, suffix)).Return(nil).AnyTimes() @@ -286,15 +248,14 @@ func setMockPublicIP(az *Cloud, mockPIPsClient *mockpublicipclient.MockInterface } func setMockSecurityGroup(az *Cloud, sgs ...*armnetwork.SecurityGroup) { - clientFactory := az.NetworkClientFactory.(*mock_azclient.MockClientFactory) - mockSGsClient := clientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) + mockSGsClient := az.NetworkClientFactory.GetSecurityGroupClient().(*mock_securitygroupclient.MockInterface) for _, sg := range sgs { mockSGsClient.EXPECT().Get(gomock.Any(), az.SecurityGroupResourceGroup, az.SecurityGroupName).Return(sg, nil).AnyTimes() } mockSGsClient.EXPECT().CreateOrUpdate(gomock.Any(), az.SecurityGroupResourceGroup, az.SecurityGroupName, gomock.Any()).Return(nil, nil).AnyTimes() } -func setMockLBsDualStack(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]network.LoadBalancer, svcName string, lbCount, serviceIndex int, isInternal bool) string { +func setMockLBsDualStack(az *Cloud, expectedLBs *[]*armnetwork.LoadBalancer, svcName string, lbCount, serviceIndex int, isInternal bool) string { lbIndex := (serviceIndex - 1) % lbCount expectedLBName := "" if lbIndex == 0 { @@ -309,10 +270,10 @@ func setMockLBsDualStack(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]netw fullServiceName := strings.Replace(svcName, "-", "", -1) if lbIndex >= len(*expectedLBs) { - lb := network.LoadBalancer{ + lb := &armnetwork.LoadBalancer{ Location: &az.Location, - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("testCluster"), }, @@ -323,7 +284,7 @@ func setMockLBsDualStack(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]netw }, } lb.Name = &expectedLBName - lb.LoadBalancingRules = &[]network.LoadBalancingRule{ + lb.Properties.LoadBalancingRules = []*armnetwork.LoadBalancingRule{ { Name: ptr.To(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), }, @@ -331,35 +292,35 @@ func setMockLBsDualStack(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]netw Name: ptr.To(fmt.Sprintf("a%s%d-TCP-8081-IPv6", fullServiceName, serviceIndex)), }, } - fips := []network.FrontendIPConfiguration{ + fips := []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), ID: ptr.To("fip"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAllocationMethod: "Dynamic", - PrivateIPAddressVersion: network.IPv4, - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, }, }, { Name: ptr.To(fmt.Sprintf("a%s%d-IPv6", fullServiceName, serviceIndex)), ID: ptr.To("fip-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAllocationMethod: "Dynamic", - PrivateIPAddressVersion: network.IPv6, - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d-IPv6", fullServiceName, serviceIndex))}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d-IPv6", fullServiceName, serviceIndex))}, }, }, } if isInternal { - fips[0].Subnet = &network.Subnet{Name: ptr.To("subnet")} - fips[1].Subnet = &network.Subnet{Name: ptr.To("subnet")} + fips[0].Properties.Subnet = &armnetwork.Subnet{Name: ptr.To("subnet")} + fips[1].Properties.Subnet = &armnetwork.Subnet{Name: ptr.To("subnet")} } - lb.FrontendIPConfigurations = &fips + lb.Properties.FrontendIPConfigurations = fips *expectedLBs = append(*expectedLBs, lb) } else { - lbRules := []network.LoadBalancingRule{ + lbRules := []*armnetwork.LoadBalancingRule{ { Name: ptr.To(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), }, @@ -367,50 +328,49 @@ func setMockLBsDualStack(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]netw Name: ptr.To(fmt.Sprintf("a%s%d-TCP-8081-IPv6", fullServiceName, serviceIndex)), }, } - *(*expectedLBs)[lbIndex].LoadBalancingRules = append(*(*expectedLBs)[lbIndex].LoadBalancingRules, lbRules...) - fips := []network.FrontendIPConfiguration{ + (*expectedLBs)[lbIndex].Properties.LoadBalancingRules = append((*expectedLBs)[lbIndex].Properties.LoadBalancingRules, lbRules...) + fips := []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), ID: ptr.To("fip"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAllocationMethod: "Dynamic", - PrivateIPAddressVersion: network.IPv4, - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, }, }, { Name: ptr.To(fmt.Sprintf("a%s%d-IPv6", fullServiceName, serviceIndex)), ID: ptr.To("fip-IPv6"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAllocationMethod: "Dynamic", - PrivateIPAddressVersion: network.IPv6, - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d-IPv6", fullServiceName, serviceIndex))}, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv6), + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d-IPv6", fullServiceName, serviceIndex))}, }, }, } if isInternal { for _, fip := range fips { - fip.Subnet = &network.Subnet{Name: ptr.To("subnet")} + fip.Properties.Subnet = &armnetwork.Subnet{Name: ptr.To("subnet")} } } - *(*expectedLBs)[lbIndex].FrontendIPConfigurations = append(*(*expectedLBs)[lbIndex].FrontendIPConfigurations, fips...) + (*expectedLBs)[lbIndex].Properties.FrontendIPConfigurations = append((*expectedLBs)[lbIndex].Properties.FrontendIPConfigurations, fips...) } - mockLBsClient := mockloadbalancerclient.NewMockInterface(ctrl) - az.LoadBalancerClient = mockLBsClient - mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + mockLBsClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() for _, lb := range *expectedLBs { mockLBsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, *lb.Name, gomock.Any()).Return((*expectedLBs)[lbIndex], nil).MaxTimes(2) } - mockLBsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(*expectedLBs, nil).MaxTimes(4) - mockLBsClient.EXPECT().List(gomock.Any(), gomock.Not(az.ResourceGroup)).Return([]network.LoadBalancer{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() - mockLBsClient.EXPECT().Get(gomock.Any(), gomock.Not(az.ResourceGroup), gomock.Any(), gomock.Any()).Return(network.LoadBalancer{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockLBsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return((*expectedLBs), nil).MaxTimes(4) + mockLBsClient.EXPECT().List(gomock.Any(), gomock.Not(az.ResourceGroup)).Return([]*armnetwork.LoadBalancer{}, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() + mockLBsClient.EXPECT().Get(gomock.Any(), gomock.Not(az.ResourceGroup), gomock.Any(), gomock.Any()).Return(&armnetwork.LoadBalancer{}, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() mockLBsClient.EXPECT().Delete(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).MaxTimes(1) return expectedLBName } -func setMockLBs(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]network.LoadBalancer, svcName string, lbCount, serviceIndex int, isInternal bool) string { +func setMockLBs(az *Cloud, expectedLBs *[]*armnetwork.LoadBalancer, svcName string, lbCount, serviceIndex int, isInternal bool) string { lbIndex := (serviceIndex - 1) % lbCount expectedLBName := "" if lbIndex == 0 { @@ -424,11 +384,11 @@ func setMockLBs(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]network.LoadB fullServiceName := strings.Replace(svcName, "-", "", -1) - if lbIndex >= len(*expectedLBs) { - lb := network.LoadBalancer{ + if lbIndex >= len((*expectedLBs)) { + lb := &armnetwork.LoadBalancer{ Location: &az.Location, - LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ - BackendAddressPools: &[]network.BackendAddressPool{ + Properties: &armnetwork.LoadBalancerPropertiesFormat{ + BackendAddressPools: []*armnetwork.BackendAddressPool{ { Name: ptr.To("testCluster"), }, @@ -436,446 +396,60 @@ func setMockLBs(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]network.LoadB }, } lb.Name = &expectedLBName - lb.LoadBalancingRules = &[]network.LoadBalancingRule{ + lb.Properties.LoadBalancingRules = []*armnetwork.LoadBalancingRule{ { Name: ptr.To(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), }, } - fips := []network.FrontendIPConfiguration{ + fips := []*armnetwork.FrontendIPConfiguration{ { Name: ptr.To(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), ID: ptr.To("fip"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAllocationMethod: "Dynamic", - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, - PrivateIPAddressVersion: network.IPv4, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, + PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, } if isInternal { - fips[0].Subnet = &network.Subnet{Name: ptr.To("subnet")} + fips[0].Properties.Subnet = &armnetwork.Subnet{Name: ptr.To("subnet")} } - lb.FrontendIPConfigurations = &fips + lb.Properties.FrontendIPConfigurations = fips - *expectedLBs = append(*expectedLBs, lb) + (*expectedLBs) = append((*expectedLBs), lb) } else { - *(*expectedLBs)[lbIndex].LoadBalancingRules = append(*(*expectedLBs)[lbIndex].LoadBalancingRules, network.LoadBalancingRule{ + (*expectedLBs)[lbIndex].Properties.LoadBalancingRules = append((*expectedLBs)[lbIndex].Properties.LoadBalancingRules, &armnetwork.LoadBalancingRule{ Name: ptr.To(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), }) - fip := network.FrontendIPConfiguration{ + fip := &armnetwork.FrontendIPConfiguration{ Name: ptr.To(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), ID: ptr.To("fip"), - FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAllocationMethod: "Dynamic", - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, - PrivateIPAddressVersion: network.IPv4, + Properties: &armnetwork.FrontendIPConfigurationPropertiesFormat{ + PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), + PublicIPAddress: &armnetwork.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, + PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, } if isInternal { - fip.Subnet = &network.Subnet{Name: ptr.To("subnet")} + fip.Properties.Subnet = &armnetwork.Subnet{Name: ptr.To("subnet")} } - *(*expectedLBs)[lbIndex].FrontendIPConfigurations = append(*(*expectedLBs)[lbIndex].FrontendIPConfigurations, fip) + (*expectedLBs)[lbIndex].Properties.FrontendIPConfigurations = append((*expectedLBs)[lbIndex].Properties.FrontendIPConfigurations, fip) } - mockLBsClient := mockloadbalancerclient.NewMockInterface(ctrl) - az.LoadBalancerClient = mockLBsClient - mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + mockLBsClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() for _, lb := range *expectedLBs { mockLBsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, *lb.Name, gomock.Any()).Return((*expectedLBs)[lbIndex], nil).MaxTimes(2) } - mockLBsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(*expectedLBs, nil).MaxTimes(4) - mockLBsClient.EXPECT().List(gomock.Any(), gomock.Not(az.ResourceGroup)).Return([]network.LoadBalancer{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() - mockLBsClient.EXPECT().Get(gomock.Any(), gomock.Not(az.ResourceGroup), gomock.Any(), gomock.Any()).Return(network.LoadBalancer{}, &retry.Error{HTTPStatusCode: http.StatusNotFound, RawError: cloudprovider.InstanceNotFound}).AnyTimes() + mockLBsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return((*expectedLBs), nil).MaxTimes(4) + mockLBsClient.EXPECT().List(gomock.Any(), gomock.Not(az.ResourceGroup)).Return([]*armnetwork.LoadBalancer{}, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() + mockLBsClient.EXPECT().Get(gomock.Any(), gomock.Not(az.ResourceGroup), gomock.Any(), gomock.Any()).Return(&armnetwork.LoadBalancer{}, &azcore.ResponseError{StatusCode: http.StatusNotFound, ErrorCode: cloudprovider.InstanceNotFound.Error()}).AnyTimes() mockLBsClient.EXPECT().Delete(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).MaxTimes(1) return expectedLBName } -func testLoadBalancerServiceDefaultModeSelection(t *testing.T, isInternal bool) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - az := GetTestCloud(ctrl) - const vmCount = 8 - const availabilitySetCount = 4 - const serviceCount = 9 - - clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, vmCount, availabilitySetCount) - setMockEnv(az, ctrl, expectedInterfaces, expectedVirtualMachines, serviceCount) - - mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { - return false, false, lb, nil - }).AnyTimes() - mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - mockLBBackendPool.EXPECT().GetBackendPrivateIPs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - - expectedLBs := make([]network.LoadBalancer, 0) - - for index := 1; index <= serviceCount; index++ { - svcName := fmt.Sprintf("service-%d", index) - var svc v1.Service - if isInternal { - svc = getInternalTestService(svcName, int32(index)) - validateTestSubnet(t, az, &svc) - } else { - svc = getTestService(svcName, v1.ProtocolTCP, nil, false, int32(index)) - } - - expectedLBName := setMockLBs(az, ctrl, &expectedLBs, "service", 1, index, isInternal) - - mockPLSRepo := privatelinkservice.NewMockRepository(ctrl) - mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil).AnyTimes() - az.plsRepo = mockPLSRepo - - lbStatus, err := az.EnsureLoadBalancer(context.TODO(), testClusterName, &svc, clusterResources.nodes) - if err != nil { - t.Errorf("Unexpected error: %q", err) - } - if lbStatus == nil { - t.Errorf("Unexpected error: %s", svcName) - } - - ctx, cancel := getContextWithCancel() - defer cancel() - result, _ := az.LoadBalancerClient.List(ctx, az.Config.ResourceGroup) - lb := result[0] - lbCount := len(result) - expectedNumOfLB := 1 - if lbCount != expectedNumOfLB { - t.Errorf("Unexpected number of LB's: Expected (%d) Found (%d)", expectedNumOfLB, lbCount) - } - - if !strings.EqualFold(*lb.Name, expectedLBName) { - t.Errorf("lb name should be the default LB name Extected (%s) Found (%s)", expectedLBName, *lb.Name) - } - - ruleCount := len(*lb.LoadBalancingRules) - if ruleCount != index { - t.Errorf("lb rule count should be equal to number of services deployed, expected (%d) Found (%d)", index, ruleCount) - } - } -} - -// Validate even distribution of external services across load balancers -// based on number of availability sets -func testLoadBalancerServiceAutoModeSelection(t *testing.T, isInternal bool) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - az := GetTestCloud(ctrl) - const vmCount = 8 - const availabilitySetCount = 4 - const serviceCount = 9 - - clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, vmCount, availabilitySetCount) - setMockEnv(az, ctrl, expectedInterfaces, expectedVirtualMachines, serviceCount) - - expectedLBs := make([]network.LoadBalancer, 0) - - mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { - return false, false, lb, nil - }).AnyTimes() - mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - mockLBBackendPool.EXPECT().GetBackendPrivateIPs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - - for index := 1; index <= serviceCount; index++ { - svcName := fmt.Sprintf("service-%d", index) - var svc v1.Service - if isInternal { - svc = getInternalTestService(svcName, int32(index)) - validateTestSubnet(t, az, &svc) - } else { - svc = getTestService(svcName, v1.ProtocolTCP, nil, false, int32(index)) - } - setLoadBalancerAutoModeAnnotation(&svc) - - setMockLBs(az, ctrl, &expectedLBs, "service", availabilitySetCount, index, isInternal) - - mockPLSRepo := privatelinkservice.NewMockRepository(ctrl) - mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil).AnyTimes() - az.plsRepo = mockPLSRepo - - lbStatus, err := az.EnsureLoadBalancer(context.TODO(), testClusterName, &svc, clusterResources.nodes) - assert.Nil(t, err) - assert.NotNil(t, lbStatus, svc.Name) - - // expected is MIN(index, availabilitySetCount) - expectedNumOfLB := int(math.Min(float64(index), float64(availabilitySetCount))) - ctx, cancel := getContextWithCancel() - defer cancel() - lbs, _ := az.LoadBalancerClient.List(ctx, az.Config.ResourceGroup) - lbCount := len(lbs) - assert.Equal(t, expectedNumOfLB, lbCount) - - maxRules := 0 - minRules := serviceCount - for _, lb := range lbs { - ruleCount := len(*lb.LoadBalancingRules) - if ruleCount < minRules { - minRules = ruleCount - } - if ruleCount > maxRules { - maxRules = ruleCount - } - } - - delta := maxRules - minRules - if delta > 1 { - t.Errorf("Unexpected min or max rule in LB's in resource group: Service Index (%d) Min (%d) Max(%d)", index, minRules, maxRules) - } - } -} - -// Validate availability set selection of services across load balancers -// based on provided availability sets through service annotation -// The scenario is that there are 4 availability sets in the agent pool but the -// services will be assigned load balancers that are part of the provided availability sets -// specified in service annotation -func testLoadBalancerServicesSpecifiedSelection(t *testing.T, isInternal bool) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - az := GetTestCloud(ctrl) - const vmCount = 8 - const availabilitySetCount = 4 - const serviceCount = 9 - - clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, vmCount, availabilitySetCount) - setMockEnv(az, ctrl, expectedInterfaces, expectedVirtualMachines, serviceCount) - - selectedAvailabilitySetName1 := getAvailabilitySetName(az, 0, availabilitySetCount) - - expectedLBs := make([]network.LoadBalancer, 0) - - mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { - return false, false, lb, nil - }).AnyTimes() - mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - mockLBBackendPool.EXPECT().GetBackendPrivateIPs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - - for index := 1; index <= serviceCount; index++ { - svcName := fmt.Sprintf("service-%d", index) - var svc v1.Service - if isInternal { - svc = getInternalTestService(svcName, int32(index)) - validateTestSubnet(t, az, &svc) - } else { - svc = getTestService(svcName, v1.ProtocolTCP, nil, false, int32(index)) - } - lbMode := selectedAvailabilitySetName1 - setLoadBalancerModeAnnotation(&svc, lbMode) - - setMockLBs(az, ctrl, &expectedLBs, "service", 1, index, isInternal) - - expectedPLS := make([]*armnetwork.PrivateLinkService, 0) - mockPLSRepo := privatelinkservice.NewMockRepository(ctrl) - mockPLSRepo.EXPECT().List(gomock.Any(), az.Config.ResourceGroup).Return(expectedPLS, nil).MinTimes(1).MaxTimes(1) - az.plsRepo = mockPLSRepo - - lbStatus, err := az.EnsureLoadBalancer(context.TODO(), testClusterName, &svc, clusterResources.nodes) - if err != nil { - t.Errorf("Unexpected error: %q", err) - } - if lbStatus == nil { - t.Errorf("Unexpected error: %s", svcName) - } - - // expected is MIN(index, 2) - expectedNumOfLB := int(math.Min(float64(index), float64(1))) - ctx, cancel := getContextWithCancel() - defer cancel() - result, _ := az.LoadBalancerClient.List(ctx, az.Config.ResourceGroup) - lbCount := len(result) - if lbCount != expectedNumOfLB { - t.Errorf("Unexpected number of LB's: Expected (%d) Found (%d)", expectedNumOfLB, lbCount) - } - } -} - -func testLoadBalancerMaxRulesServices(t *testing.T, isInternal bool) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - az := GetTestCloud(ctrl) - const vmCount = 1 - const availabilitySetCount = 1 - - clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, vmCount, availabilitySetCount) - setMockEnv(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) - - az.Config.MaximumLoadBalancerRuleCount = 1 - - expectedLBs := make([]network.LoadBalancer, 0) - - mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { - return false, false, lb, nil - }).AnyTimes() - mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - mockLBBackendPool.EXPECT().GetBackendPrivateIPs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - - for index := 1; index <= az.Config.MaximumLoadBalancerRuleCount; index++ { - svcName := fmt.Sprintf("service-%d", index) - var svc v1.Service - if isInternal { - svc = getInternalTestService(svcName, int32(index)) - validateTestSubnet(t, az, &svc) - } else { - svc = getTestService(svcName, v1.ProtocolTCP, nil, false, int32(index)) - } - - setMockLBs(az, ctrl, &expectedLBs, "service", az.Config.MaximumLoadBalancerRuleCount, index, isInternal) - - expectedPLS := make([]*armnetwork.PrivateLinkService, 0) - mockPLSRepo := privatelinkservice.NewMockRepository(ctrl) - mockPLSRepo.EXPECT().List(gomock.Any(), az.Config.ResourceGroup).Return(expectedPLS, nil).MinTimes(1).MaxTimes(1) - az.plsRepo = mockPLSRepo - - lbStatus, err := az.EnsureLoadBalancer(context.TODO(), testClusterName, &svc, clusterResources.nodes) - if err != nil { - t.Errorf("Unexpected error: %q", err) - } - if lbStatus == nil { - t.Errorf("Unexpected error: %s", svcName) - } - - // expected is MIN(index, az.Config.MaximumLoadBalancerRuleCount) - expectedNumOfLBRules := int(math.Min(float64(index), float64(az.Config.MaximumLoadBalancerRuleCount))) - ctx, cancel := getContextWithCancel() - defer cancel() - result, _ := az.LoadBalancerClient.List(ctx, az.Config.ResourceGroup) - lbCount := len(result) - if lbCount != expectedNumOfLBRules { - t.Errorf("Unexpected number of LB's: Expected (%d) Found (%d)", expectedNumOfLBRules, lbCount) - } - } - - // validate adding a new service fails since it will exceed the max limit on LB - svcName := fmt.Sprintf("service-%d", az.Config.MaximumLoadBalancerRuleCount+1) - var svc v1.Service - if isInternal { - svc = getInternalTestService(svcName, 8081) - validateTestSubnet(t, az, &svc) - } else { - svc = getTestService(svcName, v1.ProtocolTCP, nil, false, 8081) - } - - mockLBsClient := mockloadbalancerclient.NewMockInterface(ctrl) - az.LoadBalancerClient = mockLBsClient - mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - for _, lb := range expectedLBs { - mockLBsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, *lb.Name, gomock.Any()).Return(expectedLBs[0], nil).MaxTimes(2) - } - mockLBsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(expectedLBs, nil).MaxTimes(2) - - _, err := az.EnsureLoadBalancer(context.TODO(), testClusterName, &svc, clusterResources.nodes) - if err == nil { - t.Errorf("Expect any new service to fail as max limit in lb has reached") - } else { - expectedErrMessageSubString := "all available load balancers have exceeded maximum rule limit" - if !strings.Contains(err.Error(), expectedErrMessageSubString) { - t.Errorf("Error message returned is not expected, expected sub string=%s, actual error message=%v", expectedErrMessageSubString, err) - } - } -} - -// Validate service deletion in lb auto selection mode -func testLoadBalancerServiceAutoModeDeleteSelection(t *testing.T, isInternal bool) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - az := GetTestCloud(ctrl) - const vmCount = 8 - const availabilitySetCount = 4 - const serviceCount = 9 - - clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, vmCount, availabilitySetCount) - setMockEnv(az, ctrl, expectedInterfaces, expectedVirtualMachines, serviceCount) - - expectedLBs := make([]network.LoadBalancer, 0) - - mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { - return false, false, lb, nil - }).AnyTimes() - mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - mockLBBackendPool.EXPECT().GetBackendPrivateIPs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - - for index := 1; index <= serviceCount; index++ { - svcName := fmt.Sprintf("service-%d", index) - var svc v1.Service - if isInternal { - svc = getInternalTestService(svcName, int32(index)) - validateTestSubnet(t, az, &svc) - } else { - svc = getTestService(svcName, v1.ProtocolTCP, nil, false, int32(index)) - } - setLoadBalancerAutoModeAnnotation(&svc) - - setMockLBs(az, ctrl, &expectedLBs, "service", availabilitySetCount, index, isInternal) - - mockPLSRepo := privatelinkservice.NewMockRepository(ctrl) - mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil).AnyTimes() - az.plsRepo = mockPLSRepo - - lbStatus, err := az.EnsureLoadBalancer(context.TODO(), testClusterName, &svc, clusterResources.nodes) - if err != nil { - t.Errorf("Unexpected error: %q", err) - } - if lbStatus == nil { - t.Errorf("Unexpected error: %s", svcName) - } - } - - for index := serviceCount; index >= 1; index-- { - svcName := fmt.Sprintf("service-%d", index) - var svc v1.Service - if isInternal { - svc = getInternalTestService(svcName, int32(index)) - validateTestSubnet(t, az, &svc) - } else { - svc = getTestService(svcName, v1.ProtocolTCP, nil, false, int32(index)) - } - - setLoadBalancerAutoModeAnnotation(&svc) - - mockLBsClient := mockloadbalancerclient.NewMockInterface(ctrl) - az.LoadBalancerClient = mockLBsClient - mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - for _, lb := range expectedLBs { - mockLBsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, *lb.Name, gomock.Any()).Return(expectedLBs[0], nil).MaxTimes(2) - } - mockLBsClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, gomock.Any()).Return(nil).AnyTimes() - mockLBsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(expectedLBs, nil).MaxTimes(4) - - // expected is MIN(index, availabilitySetCount) - expectedNumOfLB := int(math.Min(float64(index), float64(availabilitySetCount))) - ctx, cancel := getContextWithCancel() - defer cancel() - result, _ := az.LoadBalancerClient.List(ctx, az.Config.ResourceGroup) - lbCount := len(result) - if lbCount != expectedNumOfLB { - t.Errorf("Unexpected number of LB's: Expected (%d) Found (%d)", expectedNumOfLB, lbCount) - } - - mockPLSRepo := privatelinkservice.NewMockRepository(ctrl) - mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil).AnyTimes() - az.plsRepo = mockPLSRepo - - err := az.EnsureLoadBalancerDeleted(context.TODO(), testClusterName, &svc) - if err != nil { - t.Errorf("Unexpected error: %q", err) - } - - if index <= availabilitySetCount { - expectedLBs = expectedLBs[:len(expectedLBs)-1] - } - } -} - // Test addition of a new service on an internal LB with a subnet. func TestReconcileLoadBalancerAddServiceOnInternalSubnet(t *testing.T) { ctrl := gomock.NewController(t) @@ -883,16 +457,16 @@ func TestReconcileLoadBalancerAddServiceOnInternalSubnet(t *testing.T) { az := GetTestCloud(ctrl) clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1) - setMockEnvDualStack(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnvDualStack(az, expectedInterfaces, expectedVirtualMachines, 1) svc := getInternalTestServiceDualStack("service1", 80) validateTestSubnet(t, az, &svc) - expectedLBs := make([]network.LoadBalancer, 0) - setMockLBsDualStack(az, ctrl, &expectedLBs, "service", 1, 1, true) + expectedLBs := make([]*armnetwork.LoadBalancer, 0) + setMockLBsDualStack(az, &expectedLBs, "service", 1, 1, true) mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { return false, false, lb, nil }).AnyTimes() mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() @@ -901,8 +475,8 @@ func TestReconcileLoadBalancerAddServiceOnInternalSubnet(t *testing.T) { assert.Nil(t, err) // ensure we got 2 frontend ip configurations - assert.Equal(t, 2, len(*lb.FrontendIPConfigurations)) - validateLoadBalancer(t, lb, svc) + assert.Equal(t, 2, len(lb.Properties.FrontendIPConfigurations)) + validateLoadBalancer(t, az, lb, svc) } // Test addition of services on an internal LB using both default and explicit subnets. @@ -912,16 +486,16 @@ func TestReconcileLoadBalancerAddServicesOnMultipleSubnets(t *testing.T) { az := GetTestCloud(ctrl) clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1) - setMockEnvDualStack(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnvDualStack(az, expectedInterfaces, expectedVirtualMachines, 1) svc1 := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 8081) svc2 := getInternalTestServiceDualStack("service2", 8081) - expectedLBs := make([]network.LoadBalancer, 0) - setMockLBsDualStack(az, ctrl, &expectedLBs, "service", 1, 1, false) + expectedLBs := make([]*armnetwork.LoadBalancer, 0) + setMockLBsDualStack(az, &expectedLBs, "service", 1, 1, false) mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { return false, false, lb, nil }).AnyTimes() mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() @@ -933,15 +507,15 @@ func TestReconcileLoadBalancerAddServicesOnMultipleSubnets(t *testing.T) { } // ensure we got a frontend ip configuration for each service - assert.Equal(t, 2, len(*lb.FrontendIPConfigurations)) + assert.Equal(t, 2, len(lb.Properties.FrontendIPConfigurations)) - validateLoadBalancer(t, lb, svc1) + validateLoadBalancer(t, az, lb, svc1) // Internal and External service cannot reside on the same LB resource validateTestSubnet(t, az, &svc2) - expectedLBs = make([]network.LoadBalancer, 0) - setMockLBsDualStack(az, ctrl, &expectedLBs, "service", 1, 2, true) + expectedLBs = make([]*armnetwork.LoadBalancer, 0) + setMockLBsDualStack(az, &expectedLBs, "service", 1, 2, true) // svc2 is using LB with "-internal" suffix lb, err = az.reconcileLoadBalancer(context.TODO(), testClusterName, &svc2, clusterResources.nodes, true /* wantLb */) @@ -950,9 +524,9 @@ func TestReconcileLoadBalancerAddServicesOnMultipleSubnets(t *testing.T) { } // ensure we got a frontend ip configuration for each service - assert.Equal(t, 2, len(*lb.FrontendIPConfigurations)) + assert.Equal(t, 2, len(lb.Properties.FrontendIPConfigurations)) - validateLoadBalancer(t, lb, svc2) + validateLoadBalancer(t, az, lb, svc2) } // Test moving a service exposure from one subnet to another. @@ -962,16 +536,16 @@ func TestReconcileLoadBalancerEditServiceSubnet(t *testing.T) { az := GetTestCloud(ctrl) clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1) - setMockEnvDualStack(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnvDualStack(az, expectedInterfaces, expectedVirtualMachines, 1) svc := getInternalTestServiceDualStack("service1", 8081) validateTestSubnet(t, az, &svc) - expectedLBs := make([]network.LoadBalancer, 0) - setMockLBsDualStack(az, ctrl, &expectedLBs, "service", 1, 1, true) + expectedLBs := make([]*armnetwork.LoadBalancer, 0) + setMockLBsDualStack(az, &expectedLBs, "service", 1, 1, true) mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { return false, false, lb, nil }).AnyTimes() mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() @@ -985,13 +559,13 @@ func TestReconcileLoadBalancerEditServiceSubnet(t *testing.T) { t.Errorf("Unexpected error reconciling initial svc: %q", err) } - validateLoadBalancer(t, lb, svc) + validateLoadBalancer(t, az, lb, svc) svc.Annotations[consts.ServiceAnnotationLoadBalancerInternalSubnet] = "subnet" validateTestSubnet(t, az, &svc) - expectedLBs = make([]network.LoadBalancer, 0) - setMockLBsDualStack(az, ctrl, &expectedLBs, "service", 1, 1, true) + expectedLBs = make([]*armnetwork.LoadBalancer, 0) + setMockLBsDualStack(az, &expectedLBs, "service", 1, 1, true) lb, err = az.reconcileLoadBalancer(context.TODO(), testClusterName, &svc, clusterResources.nodes, true /* wantLb */) if err != nil { @@ -999,9 +573,9 @@ func TestReconcileLoadBalancerEditServiceSubnet(t *testing.T) { } // ensure we got a frontend ip configuration for the service - assert.Equal(t, 2, len(*lb.FrontendIPConfigurations)) + assert.Equal(t, 2, len(lb.Properties.FrontendIPConfigurations)) - validateLoadBalancer(t, lb, svc) + validateLoadBalancer(t, az, lb, svc) } func TestReconcileLoadBalancerNodeHealth(t *testing.T) { @@ -1010,28 +584,31 @@ func TestReconcileLoadBalancerNodeHealth(t *testing.T) { az := GetTestCloud(ctrl) clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1) - setMockEnvDualStack(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnvDualStack(az, expectedInterfaces, expectedVirtualMachines, 1) svc := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80) svc.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyTypeLocal svc.Spec.HealthCheckNodePort = int32(32456) - expectedLBs := make([]network.LoadBalancer, 0) - setMockLBsDualStack(az, ctrl, &expectedLBs, "service", 1, 1, false) + expectedLBs := make([]*armnetwork.LoadBalancer, 0) + setMockLBsDualStack(az, &expectedLBs, "service", 1, 1, false) mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { return false, false, lb, nil }).AnyTimes() mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + mockPLSRepo := az.plsRepo.(*privatelinkservice.MockRepository) + mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil).AnyTimes() + lb, err := az.reconcileLoadBalancer(context.TODO(), testClusterName, &svc, clusterResources.nodes, true /* wantLb */) assert.Nil(t, err) // ensure we got a frontend ip configuration - assert.Equal(t, 2, len(*lb.FrontendIPConfigurations)) + assert.Equal(t, 2, len(lb.Properties.FrontendIPConfigurations)) - validateLoadBalancer(t, lb, svc) + validateLoadBalancer(t, az, lb, svc) } // Test removing all services results in removing the frontend ip configuration @@ -1041,27 +618,28 @@ func TestReconcileLoadBalancerRemoveService(t *testing.T) { az := GetTestCloud(ctrl) clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1) - setMockEnvDualStack(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnvDualStack(az, expectedInterfaces, expectedVirtualMachines, 1) svc := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80, 443) - expectedLBs := make([]network.LoadBalancer, 0) - setMockLBsDualStack(az, ctrl, &expectedLBs, "service", 1, 1, false) + expectedLBs := make([]*armnetwork.LoadBalancer, 0) + setMockLBsDualStack(az, &expectedLBs, "service", 1, 1, false) mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { return false, false, lb, nil }).AnyTimes() mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + mockPLSRepo := az.plsRepo.(*privatelinkservice.MockRepository) + mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil).AnyTimes() _, err := az.reconcileLoadBalancer(context.TODO(), testClusterName, &svc, clusterResources.nodes, true /* wantLb */) assert.Nil(t, err) - expectedLBs[0].FrontendIPConfigurations = &[]network.FrontendIPConfiguration{} - mockLBsClient := mockloadbalancerclient.NewMockInterface(ctrl) - az.LoadBalancerClient = mockLBsClient - mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - mockLBsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, *expectedLBs[0].Name, gomock.Any()).Return(expectedLBs[0], nil).MaxTimes(2) + expectedLBs[0].Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{} + mockLBsClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + mockLBsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, expectedLBs[0].Name, gomock.Any()).Return(expectedLBs[0], nil).MaxTimes(2) mockLBsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(expectedLBs, nil).MaxTimes(3) mockLBsClient.EXPECT().Delete(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) @@ -1069,9 +647,9 @@ func TestReconcileLoadBalancerRemoveService(t *testing.T) { assert.Nil(t, err) // ensure we abandoned the frontend ip configuration - assert.Zero(t, len(*lb.FrontendIPConfigurations)) + assert.Zero(t, len(lb.Properties.FrontendIPConfigurations)) - validateLoadBalancer(t, lb) + validateLoadBalancer(t, az, lb) } // Test removing all service ports results in removing the frontend ip configuration @@ -1081,30 +659,29 @@ func TestReconcileLoadBalancerRemoveAllPortsRemovesFrontendConfig(t *testing.T) az := GetTestCloud(ctrl) clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1) - setMockEnvDualStack(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnvDualStack(az, expectedInterfaces, expectedVirtualMachines, 1) svc := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80) - expectedLBs := make([]network.LoadBalancer, 0) - setMockLBsDualStack(az, ctrl, &expectedLBs, "service", 1, 1, false) + expectedLBs := make([]*armnetwork.LoadBalancer, 0) + setMockLBsDualStack(az, &expectedLBs, "service", 1, 1, false) mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { return false, false, lb, nil }).AnyTimes() mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() lb, err := az.reconcileLoadBalancer(context.TODO(), testClusterName, &svc, clusterResources.nodes, true /* wantLb */) assert.Nil(t, err) - validateLoadBalancer(t, lb, svc) + validateLoadBalancer(t, az, lb, svc) svcUpdated := getTestServiceDualStack("service1", v1.ProtocolTCP, nil) - expectedLBs[0].FrontendIPConfigurations = &[]network.FrontendIPConfiguration{} - mockLBsClient := mockloadbalancerclient.NewMockInterface(ctrl) - az.LoadBalancerClient = mockLBsClient - mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - mockLBsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, *expectedLBs[0].Name, gomock.Any()).Return(expectedLBs[0], nil).MaxTimes(2) + expectedLBs[0].Properties.FrontendIPConfigurations = []*armnetwork.FrontendIPConfiguration{} + mockLBsClient := az.NetworkClientFactory.GetLoadBalancerClient().(*mock_loadbalancerclient.MockInterface) + mockLBsClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + mockLBsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, expectedLBs[0].Name, gomock.Any()).Return(expectedLBs[0], nil).MaxTimes(2) mockLBsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(expectedLBs, nil).MaxTimes(3) mockLBsClient.EXPECT().Delete(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) @@ -1112,9 +689,9 @@ func TestReconcileLoadBalancerRemoveAllPortsRemovesFrontendConfig(t *testing.T) assert.Nil(t, err) // ensure we abandoned the frontend ip configuration - assert.Zero(t, len(*lb.FrontendIPConfigurations)) + assert.Zero(t, len(lb.Properties.FrontendIPConfigurations)) - validateLoadBalancer(t, lb, svcUpdated) + validateLoadBalancer(t, az, lb, svcUpdated) } // Test removal of a port from an existing service. @@ -1124,27 +701,28 @@ func TestReconcileLoadBalancerRemovesPort(t *testing.T) { az := GetTestCloud(ctrl) clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1) - setMockEnvDualStack(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnvDualStack(az, expectedInterfaces, expectedVirtualMachines, 1) mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { return false, false, lb, nil }).AnyTimes() mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - - expectedLBs := make([]network.LoadBalancer, 0) - setMockLBsDualStack(az, ctrl, &expectedLBs, "service", 1, 1, false) + mockPLSRepo := az.plsRepo.(*privatelinkservice.MockRepository) + mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil).AnyTimes() + expectedLBs := make([]*armnetwork.LoadBalancer, 0) + setMockLBsDualStack(az, &expectedLBs, "service", 1, 1, false) svc := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80, 443) _, err := az.reconcileLoadBalancer(context.TODO(), testClusterName, &svc, clusterResources.nodes, true /* wantLb */) assert.Nil(t, err) - expectedLBs = make([]network.LoadBalancer, 0) - setMockLBsDualStack(az, ctrl, &expectedLBs, "service", 1, 1, false) + expectedLBs = make([]*armnetwork.LoadBalancer, 0) + setMockLBsDualStack(az, &expectedLBs, "service", 1, 1, false) svcUpdated := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80) lb, err := az.reconcileLoadBalancer(context.TODO(), testClusterName, &svcUpdated, clusterResources.nodes, true /* wantLb */) assert.Nil(t, err) - validateLoadBalancer(t, lb, svcUpdated) + validateLoadBalancer(t, az, lb, svcUpdated) } // Test reconciliation of multiple services on same port @@ -1154,43 +732,41 @@ func TestReconcileLoadBalancerMultipleServices(t *testing.T) { az := GetTestCloud(ctrl) clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1) - setMockEnvDualStack(az, ctrl, expectedInterfaces, expectedVirtualMachines, 2) + setMockEnvDualStack(az, expectedInterfaces, expectedVirtualMachines, 2) svc1 := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80, 443) svc2 := getTestServiceDualStack("service2", v1.ProtocolTCP, nil, 81) - expectedLBs := make([]network.LoadBalancer, 0) - setMockLBsDualStack(az, ctrl, &expectedLBs, "service", 1, 1, false) + expectedLBs := make([]*armnetwork.LoadBalancer, 0) + setMockLBsDualStack(az, &expectedLBs, "service", 1, 1, false) mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { return false, false, lb, nil }).AnyTimes() mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - expectedPLS := make([]*armnetwork.PrivateLinkService, 0) - mockPLSRepo := privatelinkservice.NewMockRepository(ctrl) - mockPLSRepo.EXPECT().List(gomock.Any(), az.Config.ResourceGroup).Return(expectedPLS, nil).MinTimes(1).MaxTimes(1) - az.plsRepo = mockPLSRepo + mockPLSRepo := az.plsRepo.(*privatelinkservice.MockRepository) + mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil).AnyTimes() _, err := az.reconcileLoadBalancer(context.TODO(), testClusterName, &svc1, clusterResources.nodes, true /* wantLb */) assert.Nil(t, err) - setMockLBsDualStack(az, ctrl, &expectedLBs, "service", 1, 2, false) + setMockLBsDualStack(az, &expectedLBs, "service", 1, 2, false) updatedLoadBalancer, err := az.reconcileLoadBalancer(context.TODO(), testClusterName, &svc2, clusterResources.nodes, true /* wantLb */) assert.Nil(t, err) - validateLoadBalancer(t, updatedLoadBalancer, svc1, svc2) + validateLoadBalancer(t, az, updatedLoadBalancer, svc1, svc2) } -func findLBRuleForPort(lbRules []network.LoadBalancingRule, port int32) (network.LoadBalancingRule, error) { +func findLBRuleForPort(lbRules []*armnetwork.LoadBalancingRule, port int32) (*armnetwork.LoadBalancingRule, error) { for _, lbRule := range lbRules { - if *lbRule.FrontendPort == port { + if *lbRule.Properties.FrontendPort == port { return lbRule, nil } } - return network.LoadBalancingRule{}, fmt.Errorf("expected LB rule with port %d but none found", port) + return &armnetwork.LoadBalancingRule{}, fmt.Errorf("expected LB rule with port %d but none found", port) } func TestServiceDefaultsToNoSessionPersistence(t *testing.T) { @@ -1200,35 +776,34 @@ func TestServiceDefaultsToNoSessionPersistence(t *testing.T) { az := GetTestCloud(ctrl) svc := getTestService("service-sa-omitted1", v1.ProtocolTCP, nil, false, 8081) clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1) - setMockEnv(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnv(az, expectedInterfaces, expectedVirtualMachines, 1) - expectedLBs := make([]network.LoadBalancer, 0) - setMockLBs(az, ctrl, &expectedLBs, "service-sa-omitted", 1, 1, false) + expectedLBs := make([]*armnetwork.LoadBalancer, 0) + setMockLBs(az, &expectedLBs, "service-sa-omitted", 1, 1, false) - expectedPIP := network.PublicIPAddress{ + expectedPIP := &armnetwork.PublicIPAddress{ Name: ptr.To("testCluster-aservicesaomitted1"), Location: &az.Location, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAllocationMethod: network.Static, - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("aservicesaomitted1"), consts.ClusterNameKey: ptr.To(testClusterName), }, - Sku: &network.PublicIPAddressSku{ - Name: network.PublicIPAddressSkuNameStandard, + SKU: &armnetwork.PublicIPAddressSKU{ + Name: to.Ptr(armnetwork.PublicIPAddressSKUNameStandard), }, ID: ptr.To("testCluster-aservicesaomitted1"), } - mockPIPsClient := mockpublicipclient.NewMockInterface(ctrl) - az.PublicIPAddressesClient = mockPIPsClient - mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - mockPIPsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]network.PublicIPAddress{expectedPIP}, nil).AnyTimes() + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + mockPIPsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]*armnetwork.PublicIPAddress{expectedPIP}, nil).AnyTimes() mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { return false, false, lb, nil }).AnyTimes() mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() @@ -1237,14 +812,14 @@ func TestServiceDefaultsToNoSessionPersistence(t *testing.T) { if err != nil { t.Errorf("Unexpected error reconciling svc1: %q", err) } - validateLoadBalancer(t, lb, svc) - lbRule, err := findLBRuleForPort(*lb.LoadBalancingRules, 8081) + validateLoadBalancer(t, az, lb, svc) + lbRule, err := findLBRuleForPort(lb.Properties.LoadBalancingRules, 8081) if err != nil { t.Error(err) } - if lbRule.LoadDistribution != network.LoadDistributionDefault { - t.Errorf("Expected LB rule to have default load distribution but was %s", lbRule.LoadDistribution) + if *lbRule.Properties.LoadDistribution != armnetwork.LoadDistributionDefault { + t.Errorf("Expected LB rule to have default load distribution but was %s", *lbRule.Properties.LoadDistribution) } } @@ -1256,32 +831,31 @@ func TestServiceRespectsNoSessionAffinity(t *testing.T) { svc := getTestService("service-sa-none", v1.ProtocolTCP, nil, false, 8081) svc.Spec.SessionAffinity = v1.ServiceAffinityNone clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1) - setMockEnv(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnv(az, expectedInterfaces, expectedVirtualMachines, 1) - expectedLBs := make([]network.LoadBalancer, 0) - setMockLBs(az, ctrl, &expectedLBs, "service-sa-none", 1, 1, false) + expectedLBs := make([]*armnetwork.LoadBalancer, 0) + setMockLBs(az, &expectedLBs, "service-sa-none", 1, 1, false) - expectedPIP := network.PublicIPAddress{ + expectedPIP := &armnetwork.PublicIPAddress{ Name: ptr.To("testCluster-aservicesanone"), Location: &az.Location, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAllocationMethod: network.Static, - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("aservicesanone"), consts.ClusterNameKey: ptr.To(testClusterName), }, - Sku: &network.PublicIPAddressSku{ - Name: network.PublicIPAddressSkuNameStandard, + SKU: &armnetwork.PublicIPAddressSKU{ + Name: to.Ptr(armnetwork.PublicIPAddressSKUNameStandard), }, ID: ptr.To("testCluster-aservicesanone"), } - mockPIPsClient := mockpublicipclient.NewMockInterface(ctrl) - az.PublicIPAddressesClient = mockPIPsClient - mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - mockPIPsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]network.PublicIPAddress{expectedPIP}, nil).AnyTimes() + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + mockPIPsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]*armnetwork.PublicIPAddress{expectedPIP}, nil).AnyTimes() mockPIPsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "testCluster-aservicesanone", gomock.Any()).Return(expectedPIP, nil).AnyTimes() mockPLSRepo := privatelinkservice.NewMockRepository(ctrl) @@ -1289,7 +863,7 @@ func TestServiceRespectsNoSessionAffinity(t *testing.T) { az.plsRepo = mockPLSRepo mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { return false, false, lb, nil }).AnyTimes() mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() @@ -1299,15 +873,15 @@ func TestServiceRespectsNoSessionAffinity(t *testing.T) { t.Errorf("Unexpected error reconciling svc1: %q", err) } - validateLoadBalancer(t, lb, svc) + validateLoadBalancer(t, az, lb, svc) - lbRule, err := findLBRuleForPort(*lb.LoadBalancingRules, 8081) + lbRule, err := findLBRuleForPort(lb.Properties.LoadBalancingRules, 8081) if err != nil { t.Error(err) } - if lbRule.LoadDistribution != network.LoadDistributionDefault { - t.Errorf("Expected LB rule to have default load distribution but was %s", lbRule.LoadDistribution) + if *lbRule.Properties.LoadDistribution != armnetwork.LoadDistributionDefault { + t.Errorf("Expected LB rule to have default load distribution but was %s", *lbRule.Properties.LoadDistribution) } } @@ -1319,40 +893,38 @@ func TestServiceRespectsClientIPSessionAffinity(t *testing.T) { svc := getTestService("service-sa-clientip", v1.ProtocolTCP, nil, false, 8081) svc.Spec.SessionAffinity = v1.ServiceAffinityClientIP clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1) - setMockEnv(az, ctrl, expectedInterfaces, expectedVirtualMachines, 1) + setMockEnv(az, expectedInterfaces, expectedVirtualMachines, 1) - expectedLBs := make([]network.LoadBalancer, 0) - setMockLBs(az, ctrl, &expectedLBs, "service-sa-clientip", 1, 1, false) + expectedLBs := make([]*armnetwork.LoadBalancer, 0) + setMockLBs(az, &expectedLBs, "service-sa-clientip", 1, 1, false) - expectedPIP := network.PublicIPAddress{ + expectedPIP := &armnetwork.PublicIPAddress{ Name: ptr.To("testCluster-aservicesaclientip"), Location: &az.Location, - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - PublicIPAllocationMethod: network.Static, - PublicIPAddressVersion: network.IPv4, + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), + PublicIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, Tags: map[string]*string{ consts.ServiceTagKey: ptr.To("aservicesaclientip"), consts.ClusterNameKey: ptr.To(testClusterName), }, - Sku: &network.PublicIPAddressSku{ - Name: network.PublicIPAddressSkuNameStandard, + SKU: &armnetwork.PublicIPAddressSKU{ + Name: to.Ptr(armnetwork.PublicIPAddressSKUNameStandard), }, ID: ptr.To("testCluster-aservicesaclientip"), } - mockPIPsClient := mockpublicipclient.NewMockInterface(ctrl) - az.PublicIPAddressesClient = mockPIPsClient - mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + mockPIPsClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() mockPIPsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "testCluster-aservicesaclientip", gomock.Any()).Return(expectedPIP, nil).AnyTimes() - mockPIPsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]network.PublicIPAddress{expectedPIP}, nil).AnyTimes() + mockPIPsClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]*armnetwork.PublicIPAddress{expectedPIP}, nil).AnyTimes() - mockPLSRepo := privatelinkservice.NewMockRepository(ctrl) + mockPLSRepo := az.plsRepo.(*privatelinkservice.MockRepository) mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil).AnyTimes() - az.plsRepo = mockPLSRepo mockLBBackendPool := az.LoadBalancerBackendPool.(*MockBackendPool) - mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *network.LoadBalancer) (bool, bool, *network.LoadBalancer, error) { + mockLBBackendPool.EXPECT().ReconcileBackendPools(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ *v1.Service, lb *armnetwork.LoadBalancer) (bool, bool, *armnetwork.LoadBalancer, error) { return false, false, lb, nil }).AnyTimes() mockLBBackendPool.EXPECT().EnsureHostsInPool(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() @@ -1362,15 +934,15 @@ func TestServiceRespectsClientIPSessionAffinity(t *testing.T) { t.Errorf("Unexpected error reconciling svc1: %q", err) } - validateLoadBalancer(t, lb, svc) + validateLoadBalancer(t, az, lb, svc) - lbRule, err := findLBRuleForPort(*lb.LoadBalancingRules, 8081) + lbRule, err := findLBRuleForPort(lb.Properties.LoadBalancingRules, 8081) if err != nil { t.Error(err) } - if lbRule.LoadDistribution != network.LoadDistributionSourceIP { - t.Errorf("Expected LB rule to have SourceIP load distribution but was %s", lbRule.LoadDistribution) + if *lbRule.Properties.LoadDistribution != armnetwork.LoadDistributionSourceIP { + t.Errorf("Expected LB rule to have SourceIP load distribution but was %s", *lbRule.Properties.LoadDistribution) } } @@ -1382,7 +954,7 @@ func TestReconcilePublicIPsWithNewService(t *testing.T) { svc := getTestServiceDualStack("servicea", v1.ProtocolTCP, nil, 80, 443) v4Enabled, v6Enabled := getIPFamiliesEnabled(&svc) - setMockPublicIPs(az, ctrl, 1, v4Enabled, v6Enabled) + setMockPublicIPs(az, 1, v4Enabled, v6Enabled) pips, err := az.reconcilePublicIPs(context.TODO(), testClusterName, &svc, "", true /* wantLb*/) assert.Nil(t, err) @@ -1396,11 +968,11 @@ func TestReconcilePublicIPsWithNewService(t *testing.T) { pipsAddrs1, pipsAddrs2 := []string{}, []string{} for _, pip := range pips { pipsNames1 = append(pipsNames1, ptr.Deref(pip.Name, "")) - pipsAddrs1 = append(pipsAddrs1, ptr.Deref(pip.PublicIPAddressPropertiesFormat.IPAddress, "")) + pipsAddrs1 = append(pipsAddrs1, ptr.Deref(pip.Properties.IPAddress, "")) } for _, pip := range pips2 { pipsNames2 = append(pipsNames2, ptr.Deref(pip.Name, "")) - pipsAddrs2 = append(pipsAddrs2, ptr.Deref(pip.PublicIPAddressPropertiesFormat.IPAddress, "")) + pipsAddrs2 = append(pipsAddrs2, ptr.Deref(pip.Properties.IPAddress, "")) } assert.Truef(t, compareStrings(pipsNames1, pipsNames2) && compareStrings(pipsAddrs1, pipsAddrs2), "We should get the exact same public ip resource after a second reconcile") @@ -1414,7 +986,7 @@ func TestReconcilePublicIPsRemoveService(t *testing.T) { svc := getTestServiceDualStack("servicea", v1.ProtocolTCP, nil, 80, 443) v4Enabled, v6Enabled := getIPFamiliesEnabled(&svc) - setMockPublicIPs(az, ctrl, 1, v4Enabled, v6Enabled) + setMockPublicIPs(az, 1, v4Enabled, v6Enabled) pips, err := az.reconcilePublicIPs(context.TODO(), testClusterName, &svc, "", true /* wantLb*/) assert.Nil(t, err) @@ -1435,7 +1007,7 @@ func TestReconcilePublicIPsWithInternalService(t *testing.T) { svc := getInternalTestServiceDualStack("servicea", 80, 443) v4Enabled, v6Enabled := getIPFamiliesEnabled(&svc) - setMockPublicIPs(az, ctrl, 1, v4Enabled, v6Enabled) + setMockPublicIPs(az, 1, v4Enabled, v6Enabled) pips, err := az.reconcilePublicIPs(context.TODO(), testClusterName, &svc, "", true /* wantLb*/) assert.Nil(t, err) @@ -1451,7 +1023,7 @@ func TestReconcilePublicIPsWithExternalAndInternalSwitch(t *testing.T) { svc := getInternalTestServiceDualStack("servicea", 80, 443) v4Enabled, v6Enabled := getIPFamiliesEnabled(&svc) - setMockPublicIPs(az, ctrl, 1, v4Enabled, v6Enabled) + setMockPublicIPs(az, 1, v4Enabled, v6Enabled) pips, err := az.reconcilePublicIPs(context.TODO(), testClusterName, &svc, "", true /* wantLb*/) assert.Nil(t, err) @@ -1521,7 +1093,7 @@ type ClusterResources struct { availabilitySetNames []string } -func getClusterResources(az *Cloud, vmCount int, availabilitySetCount int) (clusterResources *ClusterResources, expectedInterfaces []network.Interface, expectedVirtualMachines []compute.VirtualMachine) { +func getClusterResources(az *Cloud, vmCount int, availabilitySetCount int) (clusterResources *ClusterResources, expectedInterfaces []*armnetwork.Interface, expectedVirtualMachines []*armcompute.VirtualMachine) { if vmCount < availabilitySetCount { return nil, expectedInterfaces, expectedVirtualMachines } @@ -1537,14 +1109,14 @@ func getClusterResources(az *Cloud, vmCount int, availabilitySetCount int) (clus nicID := getNetworkInterfaceID(az.Config.SubscriptionID, az.Config.ResourceGroup, nicName) primaryIPConfigID := getPrimaryIPConfigID(nicID) isPrimary := true - newNIC := network.Interface{ + newNIC := &armnetwork.Interface{ ID: &nicID, Name: &nicName, - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - IPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.InterfacePropertiesFormat{ + IPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { ID: &primaryIPConfigID, - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ PrivateIPAddress: &nicName, Primary: &isPrimary, }, @@ -1556,15 +1128,15 @@ func getClusterResources(az *Cloud, vmCount int, availabilitySetCount int) (clus // create vm asID := az.getAvailabilitySetID(az.Config.ResourceGroup, asName) - newVM := compute.VirtualMachine{ + newVM := &armcompute.VirtualMachine{ Name: &vmName, Location: &az.Config.Location, - VirtualMachineProperties: &compute.VirtualMachineProperties{ - AvailabilitySet: &compute.SubResource{ + Properties: &armcompute.VirtualMachineProperties{ + AvailabilitySet: &armcompute.SubResource{ ID: &asID, }, - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &[]compute.NetworkInterfaceReference{ + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: []*armcompute.NetworkInterfaceReference{ { ID: &nicID, }, @@ -1738,11 +1310,7 @@ func getTestSecurityGroup(az *Cloud, services ...v1.Service) *armnetwork.Securit return getTestSecurityGroupCommon(az, true, false, services...) } -func validateLoadBalancer(t *testing.T, loadBalancer *network.LoadBalancer, services ...v1.Service) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - az := GetTestCloud(ctrl) +func validateLoadBalancer(t *testing.T, az *Cloud, loadBalancer *armnetwork.LoadBalancer, services ...v1.Service) { expectedRuleCount := 0 expectedFrontendIPCount := 0 expectedProbeCount := 0 @@ -1783,16 +1351,18 @@ func validateLoadBalancer(t *testing.T, loadBalancer *network.LoadBalancer, serv wantedRuleName := az.getLoadBalancerRuleName(&services[i], wantedRule.Protocol, wantedRule.Port, isIPv6) wantedRuleNameMap[isIPv6] = wantedRuleName foundRule := false - for _, actualRule := range *loadBalancer.LoadBalancingRules { - if strings.EqualFold(*actualRule.Name, wantedRuleName) && - *actualRule.FrontendPort == wantedRule.Port { + for _, actualRule := range loadBalancer.Properties.LoadBalancingRules { + if actualRule != nil && actualRule.Name != nil && + strings.EqualFold(*actualRule.Name, wantedRuleName) && + actualRule.Properties != nil && actualRule.Properties.FrontendPort != nil && + *actualRule.Properties.FrontendPort == wantedRule.Port { if isInternal { - if (!isIPv6 && *actualRule.BackendPort == wantedRule.Port) || - (isIPv6 && *actualRule.BackendPort == wantedRule.NodePort) { + if (!isIPv6 && *actualRule.Properties.BackendPort == wantedRule.Port) || + (isIPv6 && *actualRule.Properties.BackendPort == wantedRule.NodePort) { foundRule = true break } - } else if *actualRule.BackendPort == wantedRule.Port { + } else if *actualRule.Properties.BackendPort == wantedRule.Port { foundRule = true break } @@ -1815,27 +1385,27 @@ func validateLoadBalancer(t *testing.T, loadBalancer *network.LoadBalancer, serv if servicehelpers.NeedsHealthCheck(&services[i]) { path, port := servicehelpers.GetServiceHealthCheckPathPort(&services[i]) wantedRuleName := az.getLoadBalancerRuleName(&services[i], v1.ProtocolTCP, port, isIPv6) - for _, actualProbe := range *loadBalancer.Probes { + for _, actualProbe := range loadBalancer.Properties.Probes { if strings.EqualFold(*actualProbe.Name, wantedRuleName) && - *actualProbe.Port == port && - *actualProbe.RequestPath == path && - actualProbe.Protocol == network.ProbeProtocolHTTP { + *actualProbe.Properties.Port == port && + *actualProbe.Properties.RequestPath == path && + actualProbe.Properties.Protocol == to.Ptr(armnetwork.ProbeProtocolHTTP) { foundProbe = true break } } } else { - for _, actualProbe := range *loadBalancer.Probes { + for _, actualProbe := range loadBalancer.Properties.Probes { if strings.EqualFold(*actualProbe.Name, wantedRuleNameMap[isIPv6]) && - *actualProbe.Port == wantedRule.NodePort { + *actualProbe.Properties.Port == wantedRule.NodePort { foundProbe = true break } } } if !foundProbe { - for _, actualProbe := range *loadBalancer.Probes { - t.Logf("Probe: %s %d", *actualProbe.Name, *actualProbe.Port) + for _, actualProbe := range loadBalancer.Properties.Probes { + t.Logf("Probe: %s %d", *actualProbe.Name, *actualProbe.Properties.Port) } t.Errorf("Expected loadbalancer probe but didn't find it: %q", wantedRuleNameMap[isIPv6]) } @@ -1843,24 +1413,24 @@ func validateLoadBalancer(t *testing.T, loadBalancer *network.LoadBalancer, serv } } - frontendIPCount := len(*loadBalancer.FrontendIPConfigurations) + frontendIPCount := len(loadBalancer.Properties.FrontendIPConfigurations) if frontendIPCount != expectedFrontendIPCount { - t.Errorf("Expected the loadbalancer to have %d frontend IPs. Found %d.\n%v", expectedFrontendIPCount, frontendIPCount, loadBalancer.FrontendIPConfigurations) + t.Errorf("Expected the loadbalancer to have %d frontend IPs. Found %d.\n%v", expectedFrontendIPCount, frontendIPCount, loadBalancer.Properties.FrontendIPConfigurations) } - frontendIPs := *loadBalancer.FrontendIPConfigurations + frontendIPs := loadBalancer.Properties.FrontendIPConfigurations for _, expectedFrontendIP := range expectedFrontendIPs { if !expectedFrontendIP.existsIn(frontendIPs) { t.Errorf("Expected the loadbalancer to have frontend IP %s/%s. Found %s", expectedFrontendIP.Name, ptr.Deref(expectedFrontendIP.Subnet, ""), describeFIPs(frontendIPs)) } } - lenRules := len(*loadBalancer.LoadBalancingRules) + lenRules := len(loadBalancer.Properties.LoadBalancingRules) if lenRules != expectedRuleCount { - t.Errorf("Expected the loadbalancer to have %d rules. Found %d.\n%v", expectedRuleCount, lenRules, loadBalancer.LoadBalancingRules) + t.Errorf("Expected the loadbalancer to have %d rules. Found %d.\n%v", expectedRuleCount, lenRules, loadBalancer.Properties.LoadBalancingRules) } - lenProbes := len(*loadBalancer.Probes) + lenProbes := len(loadBalancer.Properties.Probes) if lenProbes != expectedProbeCount { t.Errorf("Expected the loadbalancer to have %d probes. Found %d.", expectedRuleCount, lenProbes) } @@ -1871,11 +1441,11 @@ type ExpectedFrontendIPInfo struct { Subnet *string } -func (expected ExpectedFrontendIPInfo) matches(frontendIP network.FrontendIPConfiguration) bool { +func (expected ExpectedFrontendIPInfo) matches(frontendIP *armnetwork.FrontendIPConfiguration) bool { return strings.EqualFold(expected.Name, ptr.Deref(frontendIP.Name, "")) && strings.EqualFold(ptr.Deref(expected.Subnet, ""), ptr.Deref(subnetName(frontendIP), "")) } -func (expected ExpectedFrontendIPInfo) existsIn(frontendIPs []network.FrontendIPConfiguration) bool { +func (expected ExpectedFrontendIPInfo) existsIn(frontendIPs []*armnetwork.FrontendIPConfiguration) bool { for _, fip := range frontendIPs { if expected.matches(fip) { return true @@ -1884,19 +1454,19 @@ func (expected ExpectedFrontendIPInfo) existsIn(frontendIPs []network.FrontendIP return false } -func subnetName(frontendIP network.FrontendIPConfiguration) *string { - if frontendIP.Subnet != nil { - return frontendIP.Subnet.Name +func subnetName(frontendIP *armnetwork.FrontendIPConfiguration) *string { + if frontendIP.Properties.Subnet != nil { + return frontendIP.Properties.Subnet.Name } return nil } -func describeFIPs(frontendIPs []network.FrontendIPConfiguration) string { +func describeFIPs(frontendIPs []*armnetwork.FrontendIPConfiguration) string { description := "" for _, actualFIP := range frontendIPs { actualSubnetName := "" - if actualFIP.Subnet != nil { - actualSubnetName = ptr.Deref(actualFIP.Subnet.Name, "") + if actualFIP.Properties.Subnet != nil { + actualSubnetName = ptr.Deref(actualFIP.Properties.Subnet.Name, "") } actualFIPText := fmt.Sprintf("%s/%s ", ptr.Deref(actualFIP.Name, ""), actualSubnetName) description = description + actualFIPText @@ -1904,13 +1474,13 @@ func describeFIPs(frontendIPs []network.FrontendIPConfiguration) string { return description } -func validatePublicIPs(t *testing.T, pips []*network.PublicIPAddress, service *v1.Service, wantLb bool) { +func validatePublicIPs(t *testing.T, pips []*armnetwork.PublicIPAddress, service *v1.Service, wantLb bool) { for _, pip := range pips { validatePublicIP(t, pip, service, wantLb) } } -func validatePublicIP(t *testing.T, publicIP *network.PublicIPAddress, service *v1.Service, wantLb bool) { +func validatePublicIP(t *testing.T, publicIP *armnetwork.PublicIPAddress, service *v1.Service, wantLb bool) { isInternal := requiresInternalLoadBalancer(service) if isInternal || !wantLb { if publicIP != nil { @@ -1998,13 +1568,13 @@ func TestProtocolTranslationTCP(t *testing.T) { t.Error(err) } - if *transportProto != network.TransportProtocolTCP { + if *transportProto != armnetwork.TransportProtocolTCP { t.Errorf("Expected TCP LoadBalancer Rule Protocol. Got %v", transportProto) } - if securityGroupProto != armnetwork.SecurityRuleProtocolTCP { + if *securityGroupProto != armnetwork.SecurityRuleProtocolTCP { t.Errorf("Expected TCP SecurityGroup Protocol. Got %v", transportProto) } - if *probeProto != network.ProbeProtocolTCP { + if *probeProto != armnetwork.ProbeProtocolTCP { t.Errorf("Expected TCP LoadBalancer Probe Protocol. Got %v", transportProto) } } @@ -2012,10 +1582,10 @@ func TestProtocolTranslationTCP(t *testing.T) { func TestProtocolTranslationUDP(t *testing.T) { proto := v1.ProtocolUDP transportProto, securityGroupProto, probeProto, _ := getProtocolsFromKubernetesProtocol(proto) - if *transportProto != network.TransportProtocolUDP { + if *transportProto != armnetwork.TransportProtocolUDP { t.Errorf("Expected UDP LoadBalancer Rule Protocol. Got %v", transportProto) } - if securityGroupProto != armnetwork.SecurityRuleProtocolUDP { + if *securityGroupProto != armnetwork.SecurityRuleProtocolUDP { t.Errorf("Expected UDP SecurityGroup Protocol. Got %v", transportProto) } if probeProto != nil { @@ -2263,19 +1833,9 @@ func getCloudFromConfig(t *testing.T, configContent string) *Cloud { c, err := config.ParseConfig(configReader) assert.NoError(t, err) - zoneMock := zone.NewMockRepository(ctrl) - az := &Cloud{ - nodeNames: utilsets.NewString(), - nodeZones: map[string]*utilsets.IgnoreCaseSet{}, - nodeResourceGroups: map[string]string{}, - unmanagedNodes: utilsets.NewString(), - excludeLoadBalancerNodes: utilsets.NewString(), - routeCIDRs: map[string]string{}, - zoneRepo: zoneMock, - ComputeClientFactory: mock_azclient.NewMockClientFactory(ctrl), - NetworkClientFactory: mock_azclient.NewMockClientFactory(ctrl), - } - zoneMock.EXPECT().ListZones(gomock.Any()).Return(map[string][]string{"eastus": {"1", "2", "3"}}, nil) + az := GetTestCloud(ctrl) + zoneMock := az.zoneRepo.(*zone.MockRepository) + zoneMock.EXPECT().ListZones(gomock.Any()).Return(map[string][]string{"eastus": {"1", "2", "3"}}, nil).AnyTimes() // Skip AAD client cert path validation since it will read the file from the path aadCertPath := c.AADClientCertPath @@ -2377,9 +1937,9 @@ func validateTestSubnet(t *testing.T, az *Cloud, svc *v1.Service) { az.VnetResourceGroup, az.VnetName, subName) - mockSubnetsClient := az.SubnetsClient.(*mocksubnetclient.MockInterface) - mockSubnetsClient.EXPECT().Get(gomock.Any(), az.VnetResourceGroup, az.VnetName, subName, "").Return( - network.Subnet{ + mockSubnetsClient := az.subnetRepo.(*subnet.MockRepository) + mockSubnetsClient.EXPECT().Get(gomock.Any(), az.VnetResourceGroup, az.VnetName, subName).Return( + &armnetwork.Subnet{ ID: &subnetID, Name: &subName, }, nil).AnyTimes() @@ -2777,48 +2337,81 @@ func TestGetActiveZones(t *testing.T) { } func TestInitializeCloudFromConfig(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - az := GetTestCloud(ctrl) - - zoneMock := zone.NewMockRepository(ctrl) - zoneMock.EXPECT().ListZones(gomock.Any()).Return(map[string][]string{"eastus": {"1", "2", "3"}}, nil).AnyTimes() - az.zoneRepo = zoneMock - err := az.InitializeCloudFromConfig(context.Background(), nil, false, true) - assert.Equal(t, fmt.Errorf("InitializeCloudFromConfig: cannot initialize from nil config"), err) + t.Run("cannot initialize from nil config", func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + az := GetTestCloud(ctrl) + zoneMock := az.zoneRepo.(*zone.MockRepository) + zoneMock.EXPECT().ListZones(gomock.Any()).Return(map[string][]string{"eastus": {"1", "2", "3"}}, nil).AnyTimes() - azureconfig := config.Config{ - DisableAvailabilitySetNodes: true, - VMType: consts.VMTypeStandard, - } - err = az.InitializeCloudFromConfig(context.Background(), &azureconfig, false, true) - expectedErr := fmt.Errorf("disableAvailabilitySetNodes true is only supported when vmType is 'vmss'") - assert.Equal(t, expectedErr, err) + err := az.InitializeCloudFromConfig(context.Background(), nil, false, true) + assert.Equal(t, fmt.Errorf("InitializeCloudFromConfig: cannot initialize from nil config"), err) - azureconfig = config.Config{ - AzureClientConfig: providerconfig.AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - Cloud: "AZUREPUBLICCLOUD", + }) + t.Run("disableAvailabilitySetNodes true is only supported when vmType is 'vmss'", func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + az := GetTestCloud(ctrl) + zoneMock := az.zoneRepo.(*zone.MockRepository) + zoneMock.EXPECT().ListZones(gomock.Any()).Return(map[string][]string{"eastus": {"1", "2", "3"}}, nil).AnyTimes() + + azureconfig := config.Config{ + DisableAvailabilitySetNodes: true, + VMType: consts.VMTypeStandard, + } + err := az.InitializeCloudFromConfig(context.Background(), &azureconfig, false, true) + expectedErr := fmt.Errorf("disableAvailabilitySetNodes true is only supported when vmType is 'vmss'") + assert.Equal(t, expectedErr, err) + }) + t.Run("useInstanceMetadata must be enabled without Azure credentials", func(t *testing.T) { + + ctrl := gomock.NewController(t) + defer ctrl.Finish() + az := GetTestCloud(ctrl) + zoneMock := az.zoneRepo.(*zone.MockRepository) + zoneMock.EXPECT().ListZones(gomock.Any()).Return(map[string][]string{"eastus": {"1", "2", "3"}}, nil).AnyTimes() + + azureconfig := config.Config{ + AzureClientConfig: providerconfig.AzureClientConfig{ + ARMClientConfig: azclient.ARMClientConfig{ + Cloud: "AZUREPUBLICCLOUD", + }, }, - }, - CloudConfigType: configloader.CloudConfigTypeFile, - } - err = az.InitializeCloudFromConfig(context.Background(), &azureconfig, false, true) - expectedErr = fmt.Errorf("useInstanceMetadata must be enabled without Azure credentials") - assert.Equal(t, expectedErr, err) + CloudConfigType: configloader.CloudConfigTypeFile, + } + az.AuthProvider = &azclient.AuthProvider{} + err := az.InitializeCloudFromConfig(context.Background(), &azureconfig, false, true) + expectedErr := fmt.Errorf("useInstanceMetadata must be enabled without Azure credentials") + assert.Equal(t, expectedErr, err) + }) + t.Run("loadBalancerBackendPoolConfigurationType invalid is not supported, supported values are", func(t *testing.T) { - azureconfig = config.Config{ - LoadBalancerBackendPoolConfigurationType: "invalid", - } - err = az.InitializeCloudFromConfig(context.Background(), &azureconfig, false, true) - expectedErr = errors.New("loadBalancerBackendPoolConfigurationType invalid is not supported, supported values are") - assert.Contains(t, err.Error(), expectedErr.Error()) + ctrl := gomock.NewController(t) + defer ctrl.Finish() + az := GetTestCloud(ctrl) + zoneMock := az.zoneRepo.(*zone.MockRepository) + zoneMock.EXPECT().ListZones(gomock.Any()).Return(map[string][]string{"eastus": {"1", "2", "3"}}, nil).AnyTimes() - azureconfig = config.Config{} - err = az.InitializeCloudFromConfig(context.Background(), &azureconfig, false, true) - assert.NoError(t, err) - assert.Equal(t, az.Config.LoadBalancerBackendPoolConfigurationType, consts.LoadBalancerBackendPoolConfigurationTypeNodeIPConfiguration) + azureconfig := config.Config{ + LoadBalancerBackendPoolConfigurationType: "invalid", + } + err := az.InitializeCloudFromConfig(context.Background(), &azureconfig, false, true) + expectedErr := errors.New("loadBalancerBackendPoolConfigurationType invalid is not supported, supported values are") + assert.Contains(t, err.Error(), expectedErr.Error()) + }) + t.Run("loadBalancerBackendPoolConfigurationType is set to NodeIPConfiguration", func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + az := GetTestCloud(ctrl) + zoneMock := az.zoneRepo.(*zone.MockRepository) + zoneMock.EXPECT().ListZones(gomock.Any()).Return(map[string][]string{"eastus": {"1", "2", "3"}}, nil).AnyTimes() + + azureconfig := config.Config{} + err := az.InitializeCloudFromConfig(context.Background(), &azureconfig, false, true) + assert.NoError(t, err) + assert.Equal(t, az.Config.LoadBalancerBackendPoolConfigurationType, consts.LoadBalancerBackendPoolConfigurationTypeNodeIPConfiguration) + }) } func TestSetLBDefaults(t *testing.T) { @@ -2828,7 +2421,7 @@ func TestSetLBDefaults(t *testing.T) { config := &config.Config{} _ = az.setLBDefaults(config) - assert.Equal(t, config.LoadBalancerSku, consts.LoadBalancerSkuStandard) + assert.Equal(t, config.LoadBalancerSKU, consts.LoadBalancerSKUStandard) } func TestCheckEnableMultipleStandardLoadBalancers(t *testing.T) { diff --git a/pkg/provider/azure_utils.go b/pkg/provider/azure_utils.go index 4357aaa051..5d4f456814 100644 --- a/pkg/provider/azure_utils.go +++ b/pkg/provider/azure_utils.go @@ -18,17 +18,12 @@ package provider import ( "context" - "encoding/json" "fmt" "net" "strings" "sync" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" utilnet "k8s.io/utils/net" @@ -391,7 +386,7 @@ func getResourceByIPFamily(resource string, isDualStack, isIPv6 bool) string { // isFIPIPv6 checks if the frontend IP configuration is of IPv6. // NOTICE: isFIPIPv6 assumes the FIP is owned by the Service and it is the primary Service. -func (az *Cloud) isFIPIPv6(service *v1.Service, fip *network.FrontendIPConfiguration) (bool, error) { +func (az *Cloud) isFIPIPv6(service *v1.Service, fip *armnetwork.FrontendIPConfiguration) (bool, error) { isDualStack := isServiceDualStack(service) if !isDualStack { if len(service.Spec.IPFamilies) == 0 { @@ -420,25 +415,25 @@ func getBackendPoolNameFromBackendPoolID(backendPoolID string) (string, error) { return matches[2], nil } -func countNICsOnBackendPool(backendPool network.BackendAddressPool) int { - if backendPool.BackendAddressPoolPropertiesFormat == nil || - backendPool.BackendIPConfigurations == nil { +func countNICsOnBackendPool(backendPool *armnetwork.BackendAddressPool) int { + if backendPool.Properties == nil || + backendPool.Properties.BackendIPConfigurations == nil { return 0 } - return len(*backendPool.BackendIPConfigurations) + return len(backendPool.Properties.BackendIPConfigurations) } -func countIPsOnBackendPool(backendPool network.BackendAddressPool) int { - if backendPool.BackendAddressPoolPropertiesFormat == nil || - backendPool.LoadBalancerBackendAddresses == nil { +func countIPsOnBackendPool(backendPool *armnetwork.BackendAddressPool) int { + if backendPool.Properties == nil || + backendPool.Properties.LoadBalancerBackendAddresses == nil { return 0 } var ipsCount int - for _, loadBalancerBackendAddress := range *backendPool.LoadBalancerBackendAddresses { - if loadBalancerBackendAddress.LoadBalancerBackendAddressPropertiesFormat != nil && - ptr.Deref(loadBalancerBackendAddress.IPAddress, "") != "" { + for _, loadBalancerBackendAddress := range backendPool.Properties.LoadBalancerBackendAddresses { + if loadBalancerBackendAddress.Properties != nil && + ptr.Deref(loadBalancerBackendAddress.Properties.IPAddress, "") != "" { ipsCount++ } } @@ -497,7 +492,7 @@ func getResourceGroupAndNameFromNICID(ipConfigurationID string) (string, string, return nicResourceGroup, nicName, nil } -func isInternalLoadBalancer(lb *network.LoadBalancer) bool { +func isInternalLoadBalancer(lb *armnetwork.LoadBalancer) bool { return strings.HasSuffix(strings.ToLower(*lb.Name), consts.InternalLoadBalancerNameSuffix) } @@ -512,24 +507,3 @@ func trimSuffixIgnoreCase(str, suf string) string { } return str } - -// ToArmcomputeDisk converts compute.DataDisk to armcompute.DataDisk -// This is a workaround during track2 migration. -// TODO: remove this function after compute api is migrated to track2 -func ToArmcomputeDisk(disks []compute.DataDisk) ([]*armcompute.DataDisk, error) { - var result []*armcompute.DataDisk - for _, disk := range disks { - content, err := json.Marshal(disk) - if err != nil { - return nil, err - } - var dataDisk armcompute.DataDisk - err = json.Unmarshal(content, &dataDisk) - if err != nil { - return nil, err - } - result = append(result, &dataDisk) - } - - return result, nil -} diff --git a/pkg/provider/azure_utils_test.go b/pkg/provider/azure_utils_test.go index cf01c643ef..e5111e40eb 100644 --- a/pkg/provider/azure_utils_test.go +++ b/pkg/provider/azure_utils_test.go @@ -18,14 +18,10 @@ package provider import ( "context" - "reflect" "sync" "testing" - "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -764,7 +760,7 @@ func TestIsFIPIPv6(t *testing.T) { testcases := []struct { desc string svc v1.Service - fip *network.FrontendIPConfiguration + fip *armnetwork.FrontendIPConfiguration expectedIsIPv6 bool }{ { @@ -794,7 +790,7 @@ func TestIsFIPIPv6(t *testing.T) { IPFamilies: []v1.IPFamily{v1.IPv4Protocol, v1.IPv6Protocol}, }, }, - fip: &network.FrontendIPConfiguration{ + fip: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("fip"), }, expectedIsIPv6: false, @@ -806,7 +802,7 @@ func TestIsFIPIPv6(t *testing.T) { IPFamilies: []v1.IPFamily{v1.IPv4Protocol, v1.IPv6Protocol}, }, }, - fip: &network.FrontendIPConfiguration{ + fip: &armnetwork.FrontendIPConfiguration{ Name: ptr.To("fip-IPv6"), }, expectedIsIPv6: true, @@ -852,26 +848,26 @@ func TestGetResourceIDPrefix(t *testing.T) { func TestIsInternalLoadBalancer(t *testing.T) { tests := []struct { name string - lb network.LoadBalancer + lb armnetwork.LoadBalancer expected bool }{ { name: "internal load balancer", - lb: network.LoadBalancer{ + lb: armnetwork.LoadBalancer{ Name: ptr.To("test-internal"), }, expected: true, }, { name: "internal load balancer", - lb: network.LoadBalancer{ + lb: armnetwork.LoadBalancer{ Name: ptr.To("TEST-INTERNAL"), }, expected: true, }, { name: "not internal load balancer", - lb: network.LoadBalancer{ + lb: armnetwork.LoadBalancer{ Name: ptr.To("test"), }, expected: false, @@ -886,44 +882,3 @@ func TestIsInternalLoadBalancer(t *testing.T) { }) } } - -func TestToArmcomputeDisk(t *testing.T) { - type args struct { - disks []compute.DataDisk - } - tests := []struct { - name string - args args - want []*armcompute.DataDisk - wantErr bool - }{ - { - name: "normal", - args: args{ - disks: []compute.DataDisk{ - { - Name: ptr.To("disk1"), - }, - }, - }, - want: []*armcompute.DataDisk{ - { - Name: ptr.To("disk1"), - }, - }, - wantErr: false, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := ToArmcomputeDisk(tt.args.disks) - if (err != nil) != tt.wantErr { - t.Errorf("ToArmcomputeDisk() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("ToArmcomputeDisk() = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/pkg/provider/azure_vmsets.go b/pkg/provider/azure_vmsets.go index 5b7c62acd9..4d0dd4ef97 100644 --- a/pkg/provider/azure_vmsets.go +++ b/pkg/provider/azure_vmsets.go @@ -20,8 +20,7 @@ import ( "context" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" @@ -46,7 +45,7 @@ type VMSet interface { // GetIPByNodeName gets machine private IP and public IP by node name. GetIPByNodeName(ctx context.Context, name string) (string, string, error) // GetPrimaryInterface gets machine primary network interface by node name. - GetPrimaryInterface(ctx context.Context, nodeName string) (network.Interface, error) + GetPrimaryInterface(ctx context.Context, nodeName string) (*armnetwork.Interface, error) // GetNodeNameByProviderID gets the node name by provider ID. GetNodeNameByProviderID(ctx context.Context, providerID string) (types.NodeName, error) @@ -60,7 +59,7 @@ type VMSet interface { // (depending vmType configured) for service load balancer, if the service has // no loadbalancer mode annotation returns the primary VMSet. If service annotation // for loadbalancer exists then return the eligible VMSet. - GetVMSetNames(ctx context.Context, service *v1.Service, nodes []*v1.Node) (availabilitySetNames *[]string, err error) + GetVMSetNames(ctx context.Context, service *v1.Service, nodes []*v1.Node) (availabilitySetNames []*string, err error) // GetNodeVMSetName returns the availability set or vmss name by the node name. // It will return empty string when using standalone vms. GetNodeVMSetName(ctx context.Context, node *v1.Node) (string, error) @@ -69,9 +68,9 @@ type VMSet interface { EnsureHostsInPool(ctx context.Context, service *v1.Service, nodes []*v1.Node, backendPoolID string, vmSetName string) error // EnsureHostInPool ensures the given VM's Primary NIC's Primary IP Configuration is // participating in the specified LoadBalancer Backend Pool. - EnsureHostInPool(ctx context.Context, service *v1.Service, nodeName types.NodeName, backendPoolID string, vmSetName string) (string, string, string, *compute.VirtualMachineScaleSetVM, error) + EnsureHostInPool(ctx context.Context, service *v1.Service, nodeName types.NodeName, backendPoolID string, vmSetName string) (string, string, string, *armcompute.VirtualMachineScaleSetVM, error) // EnsureBackendPoolDeleted ensures the loadBalancer backendAddressPools deleted from the specified nodes. - EnsureBackendPoolDeleted(ctx context.Context, service *v1.Service, backendPoolIDs []string, vmSetName string, backendAddressPools *[]network.BackendAddressPool, deleteFromVMSet bool) (bool, error) + EnsureBackendPoolDeleted(ctx context.Context, service *v1.Service, backendPoolIDs []string, vmSetName string, backendAddressPools []*armnetwork.BackendAddressPool, deleteFromVMSet bool) (bool, error) // EnsureBackendPoolDeletedFromVMSets ensures the loadBalancer backendAddressPools deleted from the specified VMSS/VMAS EnsureBackendPoolDeletedFromVMSets(ctx context.Context, vmSetNamesMap map[string]bool, backendPoolIDs []string) error @@ -103,7 +102,7 @@ type VMSet interface { GetNodeCIDRMasksByProviderID(ctx context.Context, providerID string) (int, int, error) // GetAgentPoolVMSetNames returns all vmSet names according to the nodes - GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1.Node) (*[]string, error) + GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1.Node) ([]*string, error) // DeleteCacheForNode removes the node entry from cache. DeleteCacheForNode(ctx context.Context, nodeName string) error @@ -114,7 +113,7 @@ type VMSet interface { // AttachDiskOptions attach disk options type AttachDiskOptions struct { - CachingMode compute.CachingTypes + CachingMode armcompute.CachingTypes DiskName string DiskEncryptionSetID string WriteAcceleratorEnabled bool diff --git a/pkg/provider/azure_vmsets_repo.go b/pkg/provider/azure_vmsets_repo.go index 00c13e6a66..a64fed3baf 100644 --- a/pkg/provider/azure_vmsets_repo.go +++ b/pkg/provider/azure_vmsets_repo.go @@ -22,7 +22,7 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" cloudprovider "k8s.io/cloud-provider" @@ -34,8 +34,8 @@ import ( ) // GetVirtualMachineWithRetry invokes az.getVirtualMachine with exponential backoff retry -func (az *Cloud) GetVirtualMachineWithRetry(ctx context.Context, name types.NodeName, crt azcache.AzureCacheReadType) (compute.VirtualMachine, error) { - var machine compute.VirtualMachine +func (az *Cloud) GetVirtualMachineWithRetry(ctx context.Context, name types.NodeName, crt azcache.AzureCacheReadType) (*armcompute.VirtualMachine, error) { + var machine *armcompute.VirtualMachine var retryErr error err := wait.ExponentialBackoff(az.RequestBackoff(), func() (bool, error) { machine, retryErr = az.getVirtualMachine(ctx, name, crt) @@ -55,14 +55,14 @@ func (az *Cloud) GetVirtualMachineWithRetry(ctx context.Context, name types.Node return machine, err } -// ListVirtualMachines invokes az.VirtualMachinesClient.List with exponential backoff retry -func (az *Cloud) ListVirtualMachines(ctx context.Context, resourceGroup string) ([]compute.VirtualMachine, error) { - allNodes, rerr := az.VirtualMachinesClient.List(ctx, resourceGroup) - if rerr != nil { - klog.Errorf("VirtualMachinesClient.List(%v) failure with err=%v", resourceGroup, rerr) - return nil, rerr.Error() +// ListVirtualMachines invokes az.ComputeClientFactory.GetVirtualMachineScaleSetClient().List with exponential backoff retry +func (az *Cloud) ListVirtualMachines(ctx context.Context, resourceGroup string) ([]*armcompute.VirtualMachine, error) { + allNodes, err := az.ComputeClientFactory.GetVirtualMachineClient().List(ctx, resourceGroup) + if err != nil { + klog.Errorf("ComputeClientFactory.GetVirtualMachineScaleSetClient().List(%v) failure with err=%v", resourceGroup, err) + return nil, err } - klog.V(6).Infof("VirtualMachinesClient.List(%v) success", resourceGroup) + klog.V(6).Infof("ComputeClientFactory.GetVirtualMachineScaleSetClient().List(%v) success", resourceGroup) return allNodes, nil } @@ -125,10 +125,10 @@ func (az *Cloud) newVMCache() (azcache.Resource, error) { return nil, err } - vm, verr := az.VirtualMachinesClient.Get(ctx, resourceGroup, key, compute.InstanceViewTypesInstanceView) + vm, verr := az.ComputeClientFactory.GetVirtualMachineClient().Get(ctx, resourceGroup, key, nil) exists, rerr := checkResourceExistsFromError(verr) if rerr != nil { - return nil, rerr.Error() + return nil, rerr } if !exists { @@ -136,13 +136,13 @@ func (az *Cloud) newVMCache() (azcache.Resource, error) { return nil, nil } - if vm.VirtualMachineProperties != nil && - strings.EqualFold(ptr.Deref(vm.VirtualMachineProperties.ProvisioningState, ""), string(consts.ProvisioningStateDeleting)) { + if vm != nil && vm.Properties != nil && + strings.EqualFold(ptr.Deref(vm.Properties.ProvisioningState, ""), string(consts.ProvisioningStateDeleting)) { klog.V(2).Infof("Virtual machine %q is under deleting", key) return nil, nil } - return &vm, nil + return vm, nil } if az.VMCacheTTLInSeconds == 0 { @@ -151,10 +151,10 @@ func (az *Cloud) newVMCache() (azcache.Resource, error) { return azcache.NewTimedCache(time.Duration(az.VMCacheTTLInSeconds)*time.Second, getter, az.Config.DisableAPICallCache) } -// getVirtualMachine calls 'VirtualMachinesClient.Get' with a timed cache +// getVirtualMachine calls 'ComputeClientFactory.GetVirtualMachineScaleSetClient().Get' with a timed cache // The service side has throttling control that delays responses if there are multiple requests onto certain vm // resource request in short period. -func (az *Cloud) getVirtualMachine(ctx context.Context, nodeName types.NodeName, crt azcache.AzureCacheReadType) (vm compute.VirtualMachine, err error) { +func (az *Cloud) getVirtualMachine(ctx context.Context, nodeName types.NodeName, crt azcache.AzureCacheReadType) (vm *armcompute.VirtualMachine, err error) { vmName := string(nodeName) cachedVM, err := az.vmCache.Get(ctx, vmName, crt) if err != nil { @@ -166,5 +166,5 @@ func (az *Cloud) getVirtualMachine(ctx context.Context, nodeName types.NodeName, return vm, cloudprovider.InstanceNotFound } - return *(cachedVM.(*compute.VirtualMachine)), nil + return (cachedVM.(*armcompute.VirtualMachine)), nil } diff --git a/pkg/provider/azure_vmss.go b/pkg/provider/azure_vmss.go index 335cccf713..8a134e9f14 100644 --- a/pkg/provider/azure_vmss.go +++ b/pkg/provider/azure_vmss.go @@ -26,8 +26,11 @@ import ( "sync" "sync/atomic" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/samber/lo" + "golang.org/x/sync/errgroup" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" @@ -40,6 +43,7 @@ import ( "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/metrics" "sigs.k8s.io/cloud-provider-azure/pkg/provider/virtualmachine" + "sigs.k8s.io/cloud-provider-azure/pkg/util/errutils" "sigs.k8s.io/cloud-provider-azure/pkg/util/lockmap" vmutil "sigs.k8s.io/cloud-provider-azure/pkg/util/vm" ) @@ -165,8 +169,8 @@ func newScaleSet(az *Cloud) (VMSet, error) { return ss, nil } -func (ss *ScaleSet) getVMSS(ctx context.Context, vmssName string, crt azcache.AzureCacheReadType) (*compute.VirtualMachineScaleSet, error) { - getter := func(vmssName string) (*compute.VirtualMachineScaleSet, error) { +func (ss *ScaleSet) getVMSS(ctx context.Context, vmssName string, crt azcache.AzureCacheReadType) (*armcompute.VirtualMachineScaleSet, error) { + getter := func(vmssName string) (*armcompute.VirtualMachineScaleSet, error) { cached, err := ss.vmssCache.Get(ctx, consts.VMSSKey, crt) if err != nil { return nil, err @@ -299,12 +303,12 @@ func (ss *ScaleSet) GetPowerStatusByNodeName(ctx context.Context, name string) ( if vm.IsVirtualMachineScaleSetVM() { v := vm.AsVirtualMachineScaleSetVM() - if v.InstanceView != nil { - return vmutil.GetVMPowerState(ptr.Deref(v.Name, ""), v.InstanceView.Statuses), nil + if v.Properties.InstanceView != nil { + return vmutil.GetVMPowerState(ptr.Deref(v.Name, ""), v.Properties.InstanceView.Statuses), nil } } - // vm.InstanceView or vm.InstanceView.Statuses are nil when the VM is under deleting. + // vm.Properties.InstanceView or vm.Properties.InstanceView.Statuses are nil when the VM is under deleting. klog.V(3).Infof("InstanceView for node %q is nil, assuming it's deleting", name) return consts.VMPowerStateUnknown, nil } @@ -340,8 +344,8 @@ func (ss *ScaleSet) GetProvisioningStateByNodeName(ctx context.Context, name str // getCachedVirtualMachineByInstanceID gets scaleSetVMInfo from cache. // The node must belong to one of scale sets. -func (ss *ScaleSet) getVmssVMByInstanceID(ctx context.Context, resourceGroup, scaleSetName, instanceID string, crt azcache.AzureCacheReadType) (*compute.VirtualMachineScaleSetVM, error) { - getter := func(ctx context.Context, crt azcache.AzureCacheReadType) (vm *compute.VirtualMachineScaleSetVM, found bool, err error) { +func (ss *ScaleSet) getVmssVMByInstanceID(ctx context.Context, resourceGroup, scaleSetName, instanceID string, crt azcache.AzureCacheReadType) (*armcompute.VirtualMachineScaleSetVM, error) { + getter := func(ctx context.Context, crt azcache.AzureCacheReadType) (vm *armcompute.VirtualMachineScaleSetVM, found bool, err error) { virtualMachines, err := ss.getVMSSVMsFromCache(ctx, resourceGroup, scaleSetName, crt) if err != nil { return nil, false, err @@ -486,8 +490,8 @@ func (ss *ScaleSet) GetNodeNameByProviderID(ctx context.Context, providerID stri return "", err } - if vm.OsProfile != nil && vm.OsProfile.ComputerName != nil { - nodeName := strings.ToLower(*vm.OsProfile.ComputerName) + if vm.Properties.OSProfile != nil && vm.Properties.OSProfile.ComputerName != nil { + nodeName := strings.ToLower(*vm.Properties.OSProfile.ComputerName) return types.NodeName(nodeName), nil } @@ -518,8 +522,8 @@ func (ss *ScaleSet) GetInstanceTypeByNodeName(ctx context.Context, name string) if vm.IsVirtualMachineScaleSetVM() { v := vm.AsVirtualMachineScaleSetVM() - if v.Sku != nil && v.Sku.Name != nil { - return *v.Sku.Name, nil + if v.SKU != nil && v.SKU.Name != nil { + return *v.SKU.Name, nil } } @@ -553,17 +557,17 @@ func (ss *ScaleSet) GetZoneByNodeName(ctx context.Context, name string) (cloudpr if len(vm.Zones) > 0 { // Get availability zone for the node. zones := vm.Zones - zoneID, err := strconv.Atoi(zones[0]) + zoneID, err := strconv.Atoi(*zones[0]) if err != nil { - return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone %q: %w", zones, err) + return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone %q: %w", lo.FromSlicePtr(zones), err) } failureDomain = ss.makeZone(vm.Location, zoneID) } else if vm.IsVirtualMachineScaleSetVM() && - vm.AsVirtualMachineScaleSetVM().InstanceView != nil && - vm.AsVirtualMachineScaleSetVM().InstanceView.PlatformFaultDomain != nil { + vm.AsVirtualMachineScaleSetVM().Properties.InstanceView != nil && + vm.AsVirtualMachineScaleSetVM().Properties.InstanceView.PlatformFaultDomain != nil { // Availability zone is not used for the node, falling back to fault domain. - failureDomain = strconv.Itoa(int(*vm.AsVirtualMachineScaleSetVM().InstanceView.PlatformFaultDomain)) + failureDomain = strconv.Itoa(int(*vm.AsVirtualMachineScaleSetVM().Properties.InstanceView.PlatformFaultDomain)) } else { err = fmt.Errorf("failed to get zone info") klog.Errorf("GetZoneByNodeName: got unexpected error %v", err) @@ -612,10 +616,10 @@ func (ss *ScaleSet) GetIPByNodeName(ctx context.Context, nodeName string) (strin return "", "", err } - internalIP := *ipConfig.PrivateIPAddress + internalIP := *ipConfig.Properties.PrivateIPAddress publicIP := "" - if ipConfig.PublicIPAddress != nil && ipConfig.PublicIPAddress.ID != nil { - pipID := *ipConfig.PublicIPAddress.ID + if ipConfig.Properties.PublicIPAddress != nil && ipConfig.Properties.PublicIPAddress.ID != nil { + pipID := *ipConfig.Properties.PublicIPAddress.ID matches := vmssPIPConfigurationRE.FindStringSubmatch(pipID) if len(matches) == 7 { resourceGroupName := matches[1] @@ -629,8 +633,8 @@ func (ss *ScaleSet) GetIPByNodeName(ctx context.Context, nodeName string) (strin klog.Errorf("ss.getVMSSPublicIPAddress() failed with error: %v", err) return "", "", err } - if existsPip && pip.IPAddress != nil { - publicIP = *pip.IPAddress + if existsPip && pip.Properties.IPAddress != nil { + publicIP = *pip.Properties.IPAddress } } else { klog.Warningf("Failed to get VMSS Public IP with ID %s", pipID) @@ -640,22 +644,22 @@ func (ss *ScaleSet) GetIPByNodeName(ctx context.Context, nodeName string) (strin return internalIP, publicIP, nil } -func (ss *ScaleSet) getVMSSPublicIPAddress(resourceGroupName string, virtualMachineScaleSetName string, virtualMachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string) (network.PublicIPAddress, bool, error) { +func (ss *ScaleSet) getVMSSPublicIPAddress(resourceGroupName string, virtualMachineScaleSetName string, virtualMachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string) (*armnetwork.PublicIPAddress, bool, error) { ctx, cancel := getContextWithCancel() defer cancel() - pip, err := ss.PublicIPAddressesClient.GetVirtualMachineScaleSetPublicIPAddress(ctx, resourceGroupName, virtualMachineScaleSetName, virtualMachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, "") + pip, err := ss.NetworkClientFactory.GetPublicIPAddressClient().GetVirtualMachineScaleSetPublicIPAddress(ctx, resourceGroupName, virtualMachineScaleSetName, virtualMachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, nil) exists, rerr := checkResourceExistsFromError(err) if rerr != nil { - return pip, false, rerr.Error() + return nil, false, err } if !exists { klog.V(2).Infof("Public IP %q not found", publicIPAddressName) - return pip, false, nil + return nil, false, nil } - return pip, exists, nil + return &pip.PublicIPAddress, exists, nil } // returns a list of private ips assigned to node @@ -684,13 +688,13 @@ func (ss *ScaleSet) GetPrivateIPsByNodeName(ctx context.Context, nodeName string return ips, err } - if nic.IPConfigurations == nil { - return ips, fmt.Errorf("nic.IPConfigurations for nic (nicname=%q) is nil", *nic.Name) + if nic.Properties.IPConfigurations == nil { + return ips, fmt.Errorf("nic.Properties.IPConfigurations for nic (nicname=%q) is nil", *nic.Name) } - for _, ipConfig := range *(nic.IPConfigurations) { - if ipConfig.PrivateIPAddress != nil { - ips = append(ips, *(ipConfig.PrivateIPAddress)) + for _, ipConfig := range nic.Properties.IPConfigurations { + if ipConfig.Properties.PrivateIPAddress != nil { + ips = append(ips, *(ipConfig.Properties.PrivateIPAddress)) } } @@ -700,16 +704,16 @@ func (ss *ScaleSet) GetPrivateIPsByNodeName(ctx context.Context, nodeName string // This returns the full identifier of the primary NIC for the given VM. func (ss *ScaleSet) getPrimaryInterfaceID(vm *virtualmachine.VirtualMachine) (string, error) { machine := vm.AsVirtualMachineScaleSetVM() - if machine.NetworkProfile == nil || machine.NetworkProfile.NetworkInterfaces == nil { + if machine.Properties.NetworkProfile == nil || machine.Properties.NetworkProfile.NetworkInterfaces == nil { return "", fmt.Errorf("failed to find the network interfaces for vm %s", ptr.Deref(machine.Name, "")) } - if len(*machine.NetworkProfile.NetworkInterfaces) == 1 { - return *(*machine.NetworkProfile.NetworkInterfaces)[0].ID, nil + if len(machine.Properties.NetworkProfile.NetworkInterfaces) == 1 { + return *machine.Properties.NetworkProfile.NetworkInterfaces[0].ID, nil } - for _, ref := range *machine.NetworkProfile.NetworkInterfaces { - if ptr.Deref(ref.Primary, false) { + for _, ref := range machine.Properties.NetworkProfile.NetworkInterfaces { + if ptr.Deref(ref.Properties.Primary, false) { return *ref.ID, nil } } @@ -774,10 +778,10 @@ func (ss *ScaleSet) getNodeIdentityByNodeName(ctx context.Context, nodeName stri } vmssPrefix := *v.VMSS.Name - if v.VMSS.VirtualMachineProfile != nil && - v.VMSS.VirtualMachineProfile.OsProfile != nil && - v.VMSS.VirtualMachineProfile.OsProfile.ComputerNamePrefix != nil { - vmssPrefix = *v.VMSS.VirtualMachineProfile.OsProfile.ComputerNamePrefix + if v.VMSS.Properties.VirtualMachineProfile != nil && + v.VMSS.Properties.VirtualMachineProfile.OSProfile != nil && + v.VMSS.Properties.VirtualMachineProfile.OSProfile.ComputerNamePrefix != nil { + vmssPrefix = *v.VMSS.Properties.VirtualMachineProfile.OSProfile.ComputerNamePrefix } if strings.EqualFold(vmssPrefix, nodeName[:len(nodeName)-6]) { @@ -817,17 +821,17 @@ func (ss *ScaleSet) getNodeIdentityByNodeName(ctx context.Context, nodeName stri } // listScaleSetVMs lists VMs belonging to the specified scale set. -func (ss *ScaleSet) listScaleSetVMs(scaleSetName, resourceGroup string) ([]compute.VirtualMachineScaleSetVM, error) { +func (ss *ScaleSet) listScaleSetVMs(scaleSetName, resourceGroup string) ([]*armcompute.VirtualMachineScaleSetVM, error) { ctx, cancel := getContextWithCancel() defer cancel() - allVMs, rerr := ss.VirtualMachineScaleSetVMsClient.List(ctx, resourceGroup, scaleSetName, string(compute.InstanceViewTypesInstanceView)) + allVMs, rerr := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().ListVMInstanceView(ctx, resourceGroup, scaleSetName) if rerr != nil { - klog.Errorf("VirtualMachineScaleSetVMsClient.List(%s, %s) failed: %v", resourceGroup, scaleSetName, rerr) - if rerr.IsNotFound() { + klog.Errorf("ComputeClientFactory.GetVirtualMachineScaleSetVMClient().List(%s, %s) failed: %v", resourceGroup, scaleSetName, rerr) + if exists, err := errutils.CheckResourceExistsFromAzcoreError(rerr); !exists && err == nil { return nil, cloudprovider.InstanceNotFound } - return nil, rerr.Error() + return nil, rerr } return allVMs, nil @@ -835,8 +839,8 @@ func (ss *ScaleSet) listScaleSetVMs(scaleSetName, resourceGroup string) ([]compu // getAgentPoolScaleSets lists the virtual machines for the resource group and then builds // a list of scale sets that match the nodes available to k8s. -func (ss *ScaleSet) getAgentPoolScaleSets(ctx context.Context, nodes []*v1.Node) (*[]string, error) { - agentPoolScaleSets := &[]string{} +func (ss *ScaleSet) getAgentPoolScaleSets(ctx context.Context, nodes []*v1.Node) ([]string, error) { + agentPoolScaleSets := []string{} for nx := range nodes { if isControlPlaneNode(nodes[nx]) { continue @@ -862,7 +866,7 @@ func (ss *ScaleSet) getAgentPoolScaleSets(ctx context.Context, nodes []*v1.Node) continue } - *agentPoolScaleSets = append(*agentPoolScaleSets, vm.VMSSName) + agentPoolScaleSets = append(agentPoolScaleSets, vm.VMSSName) } return agentPoolScaleSets, nil @@ -871,13 +875,12 @@ func (ss *ScaleSet) getAgentPoolScaleSets(ctx context.Context, nodes []*v1.Node) // GetVMSetNames selects all possible scale sets for service load balancer. If the service has // no loadbalancer mode annotation returns the primary VMSet. If service annotation // for loadbalancer exists then return the eligible VMSet. -func (ss *ScaleSet) GetVMSetNames(ctx context.Context, service *v1.Service, nodes []*v1.Node) (*[]string, error) { +func (ss *ScaleSet) GetVMSetNames(ctx context.Context, service *v1.Service, nodes []*v1.Node) ([]*string, error) { hasMode, isAuto, serviceVMSetName := ss.getServiceLoadBalancerMode(service) if !hasMode || ss.UseStandardLoadBalancer() { // no mode specified in service annotation or use single SLB mode // default to PrimaryScaleSetName - scaleSetNames := &[]string{ss.Config.PrimaryScaleSetName} - return scaleSetNames, nil + return to.SliceOfPtrs(ss.Config.PrimaryScaleSetName), nil } scaleSetNames, err := ss.GetAgentPoolVMSetNames(ctx, nodes) @@ -885,17 +888,17 @@ func (ss *ScaleSet) GetVMSetNames(ctx context.Context, service *v1.Service, node klog.Errorf("ss.GetVMSetNames - GetAgentPoolVMSetNames failed err=(%v)", err) return nil, err } - if len(*scaleSetNames) == 0 { + if len(scaleSetNames) == 0 { klog.Errorf("ss.GetVMSetNames - No scale sets found for nodes in the cluster, node count(%d)", len(nodes)) return nil, fmt.Errorf("no scale sets found for nodes, node count(%d)", len(nodes)) } if !isAuto { found := false - for asx := range *scaleSetNames { - if strings.EqualFold((*scaleSetNames)[asx], serviceVMSetName) { + for asx := range scaleSetNames { + if strings.EqualFold(*(scaleSetNames)[asx], serviceVMSetName) { found = true - serviceVMSetName = (*scaleSetNames)[asx] + serviceVMSetName = *(scaleSetNames)[asx] break } } @@ -903,7 +906,7 @@ func (ss *ScaleSet) GetVMSetNames(ctx context.Context, service *v1.Service, node klog.Errorf("ss.GetVMSetNames - scale set (%s) in service annotation not found", serviceVMSetName) return nil, ErrScaleSetNotFound } - return &[]string{serviceVMSetName}, nil + return to.SliceOfPtrs(serviceVMSetName), nil } return scaleSetNames, nil @@ -920,11 +923,11 @@ func extractResourceGroupByVMSSNicID(nicID string) (string, error) { } // GetPrimaryInterface gets machine primary network interface by node name and vmSet. -func (ss *ScaleSet) GetPrimaryInterface(ctx context.Context, nodeName string) (network.Interface, error) { +func (ss *ScaleSet) GetPrimaryInterface(ctx context.Context, nodeName string) (*armnetwork.Interface, error) { vmManagementType, err := ss.getVMManagementTypeByNodeName(ctx, nodeName, azcache.CacheReadTypeUnsafe) if err != nil { klog.Errorf("Failed to check VM management type: %v", err) - return network.Interface{}, err + return nil, err } if vmManagementType == ManagedByAvSet { @@ -944,39 +947,39 @@ func (ss *ScaleSet) GetPrimaryInterface(ctx context.Context, nodeName string) (n } klog.Errorf("error: ss.GetPrimaryInterface(%s), ss.getVmssVM(ctx,%s), err=%v", nodeName, nodeName, err) - return network.Interface{}, err + return nil, err } primaryInterfaceID, err := ss.getPrimaryInterfaceID(vm) if err != nil { klog.Errorf("error: ss.GetPrimaryInterface(%s), ss.getPrimaryInterfaceID(), err=%v", nodeName, err) - return network.Interface{}, err + return nil, err } nicName, err := getLastSegment(primaryInterfaceID, "/") if err != nil { klog.Errorf("error: ss.GetPrimaryInterface(%s), getLastSegment(%s), err=%v", nodeName, primaryInterfaceID, err) - return network.Interface{}, err + return nil, err } resourceGroup, err := extractResourceGroupByVMSSNicID(primaryInterfaceID) if err != nil { - return network.Interface{}, err + return nil, err } ctx, cancel := getContextWithCancel() defer cancel() - nic, rerr := ss.InterfacesClient.GetVirtualMachineScaleSetNetworkInterface(ctx, resourceGroup, vm.VMSSName, + nic, rerr := ss.NetworkClientFactory.GetInterfaceClient().GetVirtualMachineScaleSetNetworkInterface(ctx, resourceGroup, vm.VMSSName, vm.InstanceID, - nicName, "") + nicName) if rerr != nil { exists, realErr := checkResourceExistsFromError(rerr) if realErr != nil { klog.Errorf("error: ss.GetPrimaryInterface(%s), ss.GetVirtualMachineScaleSetNetworkInterface.Get(%s, %s, %s), err=%v", nodeName, resourceGroup, vm.VMSSName, nicName, realErr) - return network.Interface{}, realErr.Error() + return nil, realErr } if !exists { - return network.Interface{}, cloudprovider.InstanceNotFound + return nil, cloudprovider.InstanceNotFound } } @@ -990,14 +993,14 @@ func (ss *ScaleSet) GetPrimaryInterface(ctx context.Context, nodeName string) (n } // getPrimaryNetworkInterfaceConfiguration gets primary network interface configuration for VMSS VM or VMSS. -func getPrimaryNetworkInterfaceConfiguration(networkConfigurations []compute.VirtualMachineScaleSetNetworkConfiguration, resource string) (*compute.VirtualMachineScaleSetNetworkConfiguration, error) { +func getPrimaryNetworkInterfaceConfiguration(networkConfigurations []*armcompute.VirtualMachineScaleSetNetworkConfiguration, resource string) (*armcompute.VirtualMachineScaleSetNetworkConfiguration, error) { if len(networkConfigurations) == 1 { - return &networkConfigurations[0], nil + return networkConfigurations[0], nil } for idx := range networkConfigurations { - networkConfig := &networkConfigurations[idx] - if networkConfig.Primary != nil && *networkConfig.Primary { + networkConfig := networkConfigurations[idx] + if networkConfig.Properties.Primary != nil && *networkConfig.Properties.Primary { return networkConfig, nil } } @@ -1005,19 +1008,19 @@ func getPrimaryNetworkInterfaceConfiguration(networkConfigurations []compute.Vir return nil, fmt.Errorf("failed to find a primary network configuration for the VMSS VM or VMSS %q", resource) } -func getPrimaryIPConfigFromVMSSNetworkConfig(config *compute.VirtualMachineScaleSetNetworkConfiguration, backendPoolID, resource string) (*compute.VirtualMachineScaleSetIPConfiguration, error) { - ipConfigurations := *config.IPConfigurations +func getPrimaryIPConfigFromVMSSNetworkConfig(config *armcompute.VirtualMachineScaleSetNetworkConfiguration, backendPoolID, resource string) (*armcompute.VirtualMachineScaleSetIPConfiguration, error) { + ipConfigurations := config.Properties.IPConfigurations isIPv6 := isBackendPoolIPv6(backendPoolID) if !isIPv6 { // There should be exactly one primary IP config. // https://learn.microsoft.com/en-us/azure/virtual-network/ip-services/virtual-network-network-interface-addresses?tabs=nic-address-portal#ip-configurations if len(ipConfigurations) == 1 { - return &ipConfigurations[0], nil + return ipConfigurations[0], nil } for idx := range ipConfigurations { - ipConfig := &ipConfigurations[idx] - if ipConfig.Primary != nil && *ipConfig.Primary { + ipConfig := ipConfigurations[idx] + if ipConfig.Properties.Primary != nil && *ipConfig.Properties.Primary { return ipConfig, nil } } @@ -1026,8 +1029,8 @@ func getPrimaryIPConfigFromVMSSNetworkConfig(config *compute.VirtualMachineScale // IPv6 configuration is only supported as non-primary, so we need to fetch the ip configuration where the // privateIPAddressVersion matches the clusterIP family for idx := range ipConfigurations { - ipConfig := &ipConfigurations[idx] - if ipConfig.PrivateIPAddressVersion == compute.IPv6 { + ipConfig := ipConfigurations[idx] + if ipConfig.Properties != nil && ipConfig.Properties.PrivateIPAddressVersion != nil && *ipConfig.Properties.PrivateIPAddressVersion == armcompute.IPVersionIPv6 { return ipConfig, nil } } @@ -1038,7 +1041,7 @@ func getPrimaryIPConfigFromVMSSNetworkConfig(config *compute.VirtualMachineScale // EnsureHostInPool ensures the given VM's Primary NIC's Primary IP Configuration is // participating in the specified LoadBalancer Backend Pool, which returns (resourceGroup, vmasName, instanceID, vmssVM, error). -func (ss *ScaleSet) EnsureHostInPool(ctx context.Context, _ *v1.Service, nodeName types.NodeName, backendPoolID string, vmSetNameOfLB string) (string, string, string, *compute.VirtualMachineScaleSetVM, error) { +func (ss *ScaleSet) EnsureHostInPool(ctx context.Context, _ *v1.Service, nodeName types.NodeName, backendPoolID string, vmSetNameOfLB string) (string, string, string, *armcompute.VirtualMachineScaleSetVM, error) { logger := klog.Background().WithName("EnsureHostInPool"). WithValues("nodeName", nodeName, "backendPoolID", backendPoolID, "vmSetNameOfLB", vmSetNameOfLB) vmName := mapNodeNameToVMName(nodeName) @@ -1086,7 +1089,7 @@ func (ss *ScaleSet) EnsureHostInPool(ctx context.Context, _ *v1.Service, nodeNam return "", "", "", nil, nil } - networkInterfaceConfigurations := *vm.VirtualMachineScaleSetVMProperties.NetworkProfileConfiguration.NetworkInterfaceConfigurations + networkInterfaceConfigurations := vm.VirtualMachineScaleSetVMProperties.NetworkProfileConfiguration.NetworkInterfaceConfigurations primaryNetworkInterfaceConfiguration, err := getPrimaryNetworkInterfaceConfiguration(networkInterfaceConfigurations, vmName) if err != nil { return "", "", "", nil, err @@ -1100,9 +1103,9 @@ func (ss *ScaleSet) EnsureHostInPool(ctx context.Context, _ *v1.Service, nodeNam // Update primary IP configuration's LoadBalancerBackendAddressPools. foundPool := false - newBackendPools := []compute.SubResource{} - if primaryIPConfiguration.LoadBalancerBackendAddressPools != nil { - newBackendPools = *primaryIPConfiguration.LoadBalancerBackendAddressPools + newBackendPools := []*armcompute.SubResource{} + if primaryIPConfiguration.Properties.LoadBalancerBackendAddressPools != nil { + newBackendPools = primaryIPConfiguration.Properties.LoadBalancerBackendAddressPools } for _, existingPool := range newBackendPools { if strings.EqualFold(backendPoolID, *existingPool.ID) { @@ -1139,16 +1142,16 @@ func (ss *ScaleSet) EnsureHostInPool(ctx context.Context, _ *v1.Service, nodeNam // Compose a new vmssVM with added backendPoolID. newBackendPools = append(newBackendPools, - compute.SubResource{ + &armcompute.SubResource{ ID: ptr.To(backendPoolID), }) - primaryIPConfiguration.LoadBalancerBackendAddressPools = &newBackendPools - newVM := &compute.VirtualMachineScaleSetVM{ + primaryIPConfiguration.Properties.LoadBalancerBackendAddressPools = newBackendPools + newVM := &armcompute.VirtualMachineScaleSetVM{ Location: &vm.Location, - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ HardwareProfile: vm.VirtualMachineScaleSetVMProperties.HardwareProfile, - NetworkProfileConfiguration: &compute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ - NetworkInterfaceConfigurations: &networkInterfaceConfigurations, + NetworkProfileConfiguration: &armcompute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ + NetworkInterfaceConfigurations: networkInterfaceConfigurations, }, }, } @@ -1239,12 +1242,12 @@ func (ss *ScaleSet) ensureVMSSInPool(ctx context.Context, _ *v1.Service, nodes [ // When vmss is being deleted, CreateOrUpdate API would report "the vmss is being deleted" error. // Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it. - if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.ProvisionStateDeleting) { + if vmss.Properties.ProvisioningState != nil && strings.EqualFold(*vmss.Properties.ProvisioningState, consts.ProvisionStateDeleting) { klog.V(3).Infof("ensureVMSSInPool: found vmss %s being deleted, skipping", vmssName) continue } - if vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == nil { + if vmss.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == nil { klog.V(4).Infof("EnsureHostInPool: cannot obtain the primary network interface configuration of vmss %s", vmssName) continue } @@ -1256,7 +1259,7 @@ func (ss *ScaleSet) ensureVMSSInPool(ctx context.Context, _ *v1.Service, nodes [ continue } - vmssNIC := *vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations + vmssNIC := vmss.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations primaryNIC, err := getPrimaryNetworkInterfaceConfiguration(vmssNIC, vmssName) if err != nil { return err @@ -1267,9 +1270,9 @@ func (ss *ScaleSet) ensureVMSSInPool(ctx context.Context, _ *v1.Service, nodes [ return err } - loadBalancerBackendAddressPools := []compute.SubResource{} - if primaryIPConfig.LoadBalancerBackendAddressPools != nil { - loadBalancerBackendAddressPools = *primaryIPConfig.LoadBalancerBackendAddressPools + loadBalancerBackendAddressPools := []*armcompute.SubResource{} + if primaryIPConfig.Properties.LoadBalancerBackendAddressPools != nil { + loadBalancerBackendAddressPools = primaryIPConfig.Properties.LoadBalancerBackendAddressPools } var found bool @@ -1306,16 +1309,16 @@ func (ss *ScaleSet) ensureVMSSInPool(ctx context.Context, _ *v1.Service, nodes [ // Compose a new vmss with added backendPoolID. loadBalancerBackendAddressPools = append(loadBalancerBackendAddressPools, - compute.SubResource{ + &armcompute.SubResource{ ID: ptr.To(backendPoolID), }) - primaryIPConfig.LoadBalancerBackendAddressPools = &loadBalancerBackendAddressPools - newVMSS := compute.VirtualMachineScaleSet{ + primaryIPConfig.Properties.LoadBalancerBackendAddressPools = loadBalancerBackendAddressPools + newVMSS := armcompute.VirtualMachineScaleSet{ Location: vmss.Location, - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{ - NetworkProfile: &compute.VirtualMachineScaleSetNetworkProfile{ - NetworkInterfaceConfigurations: &vmssNIC, + Properties: &armcompute.VirtualMachineScaleSetProperties{ + VirtualMachineProfile: &armcompute.VirtualMachineScaleSetVMProfile{ + NetworkProfile: &armcompute.VirtualMachineScaleSetNetworkProfile{ + NetworkInterfaceConfigurations: vmssNIC, }, }, }, @@ -1325,25 +1328,25 @@ func (ss *ScaleSet) ensureVMSSInPool(ctx context.Context, _ *v1.Service, nodes [ rerr := ss.CreateOrUpdateVMSS(ss.ResourceGroup, vmssName, newVMSS) if rerr != nil { klog.Errorf("ensureVMSSInPool CreateOrUpdateVMSS(%s) with new backendPoolID %s, err: %v", vmssName, backendPoolID, err) - return rerr.Error() + return rerr } } return nil } // isWindows2019 checks if the ImageReference on the VMSS matches a Windows Server 2019 image. -func isWindows2019(vmss *compute.VirtualMachineScaleSet) bool { +func isWindows2019(vmss *armcompute.VirtualMachineScaleSet) bool { if vmss == nil { return false } - if vmss.VirtualMachineProfile == nil || vmss.VirtualMachineProfile.StorageProfile == nil { + if vmss.Properties.VirtualMachineProfile == nil || vmss.Properties.VirtualMachineProfile.StorageProfile == nil { return false } - storageProfile := vmss.VirtualMachineProfile.StorageProfile + storageProfile := vmss.Properties.VirtualMachineProfile.StorageProfile - if storageProfile.OsDisk == nil || storageProfile.OsDisk.OsType != compute.OperatingSystemTypesWindows { + if storageProfile.OSDisk == nil || *storageProfile.OSDisk.OSType != armcompute.OperatingSystemTypesWindows { return false } @@ -1386,7 +1389,7 @@ func (ss *ScaleSet) ensureHostsInPool(ctx context.Context, service *v1.Service, } hostUpdates := make([]func() error, 0, len(nodes)) - nodeUpdates := make(map[vmssMetaInfo]map[string]compute.VirtualMachineScaleSetVM) + nodeUpdates := make(map[vmssMetaInfo]map[string]armcompute.VirtualMachineScaleSetVM) errors := make([]error, 0) for _, node := range nodes { localNodeName := node.Name @@ -1422,7 +1425,7 @@ func (ss *ScaleSet) ensureHostsInPool(ctx context.Context, service *v1.Service, if v, ok := nodeUpdates[nodeVMSSMetaInfo]; ok { v[nodeInstanceID] = *nodeVMSSVM } else { - nodeUpdates[nodeVMSSMetaInfo] = map[string]compute.VirtualMachineScaleSetVM{ + nodeUpdates[nodeVMSSMetaInfo] = map[string]armcompute.VirtualMachineScaleSetVM{ nodeInstanceID: *nodeVMSSVM, } } @@ -1456,10 +1459,20 @@ func (ss *ScaleSet) ensureHostsInPool(ctx context.Context, service *v1.Service, } klog.V(2).InfoS("Begin to update VMs for VMSS with new backendPoolID", logFields...) - rerr := ss.VirtualMachineScaleSetVMsClient.UpdateVMs(ctx, meta.resourceGroup, meta.vmssName, update, "network_update", batchSize) + grp, ctx := errgroup.WithContext(ctx) + grp.SetLimit(batchSize) + for instanceID, vm := range update { + instanceID := instanceID + vm := vm + grp.Go(func() error { + _, rerr := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().Update(ctx, meta.resourceGroup, meta.vmssName, instanceID, vm) + return rerr + }) + } + rerr := grp.Wait() if rerr != nil { klog.ErrorS(err, "Failed to update VMs for VMSS", logFields...) - return rerr.Error() + return rerr } return nil @@ -1558,7 +1571,7 @@ func (ss *ScaleSet) EnsureHostsInPool(ctx context.Context, service *v1.Service, // ensureBackendPoolDeletedFromNode ensures the loadBalancer backendAddressPools deleted // from the specified node, which returns (resourceGroup, vmasName, instanceID, vmssVM, error). -func (ss *ScaleSet) ensureBackendPoolDeletedFromNode(ctx context.Context, nodeName string, backendPoolIDs []string) (string, string, string, *compute.VirtualMachineScaleSetVM, error) { +func (ss *ScaleSet) ensureBackendPoolDeletedFromNode(ctx context.Context, nodeName string, backendPoolIDs []string) (string, string, string, *armcompute.VirtualMachineScaleSetVM, error) { logger := klog.Background().WithName("ensureBackendPoolDeletedFromNode").WithValues("nodeName", nodeName, "backendPoolIDs", backendPoolIDs) vm, err := ss.getVmssVM(ctx, nodeName, azcache.CacheReadTypeDefault) if err != nil { @@ -1584,7 +1597,7 @@ func (ss *ScaleSet) ensureBackendPoolDeletedFromNode(ctx context.Context, nodeNa "probably because the vm's being deleted", nodeName) return "", "", "", nil, nil } - networkInterfaceConfigurations := *vm.VirtualMachineScaleSetVMProperties.NetworkProfileConfiguration.NetworkInterfaceConfigurations + networkInterfaceConfigurations := vm.VirtualMachineScaleSetVMProperties.NetworkProfileConfiguration.NetworkInterfaceConfigurations primaryNetworkInterfaceConfiguration, err := getPrimaryNetworkInterfaceConfiguration(networkInterfaceConfigurations, nodeName) if err != nil { return "", "", "", nil, err @@ -1605,12 +1618,12 @@ func (ss *ScaleSet) ensureBackendPoolDeletedFromNode(ctx context.Context, nodeNa } // Compose a new vmssVM with added backendPoolID. - newVM := &compute.VirtualMachineScaleSetVM{ + newVM := &armcompute.VirtualMachineScaleSetVM{ Location: &vm.Location, - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ HardwareProfile: vm.VirtualMachineScaleSetVMProperties.HardwareProfile, - NetworkProfileConfiguration: &compute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ - NetworkInterfaceConfigurations: &networkInterfaceConfigurations, + NetworkProfileConfiguration: &armcompute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ + NetworkInterfaceConfigurations: networkInterfaceConfigurations, }, }, } @@ -1655,8 +1668,8 @@ func (ss *ScaleSet) GetNodeNameByIPConfigurationID(ctx context.Context, ipConfig return "", "", err } - if vm.OsProfile != nil && vm.OsProfile.ComputerName != nil { - return strings.ToLower(*vm.OsProfile.ComputerName), scaleSetName, nil + if vm.Properties.OSProfile != nil && vm.Properties.OSProfile.ComputerName != nil { + return strings.ToLower(*vm.Properties.OSProfile.ComputerName), scaleSetName, nil } return "", "", nil @@ -1705,7 +1718,7 @@ func (ss *ScaleSet) ensureBackendPoolDeletedFromVMSS(ctx context.Context, backen } vmssFlexMap := cachedFlex.(*sync.Map) vmssFlexMap.Range(func(_, value interface{}) bool { - vmssFlex := value.(*compute.VirtualMachineScaleSet) + vmssFlex := value.(*armcompute.VirtualMachineScaleSet) if ptr.Deref(vmssFlex.Name, "") == vmSetName { found = true return false @@ -1733,7 +1746,7 @@ func (ss *ScaleSet) ensureBackendPoolDeletedFromVMSS(ctx context.Context, backen func (ss *ScaleSet) ensureBackendPoolDeletedFromVmssUniform(ctx context.Context, backendPoolIDs []string, vmSetName string) error { vmssNamesMap := make(map[string]bool) - // the standard load balancer supports multiple vmss in its backend while the basic sku doesn't + // the standard load balancer supports multiple vmss in its backend while the basic SKU doesn't if ss.UseStandardLoadBalancer() { cachedUniform, err := ss.vmssCache.Get(ctx, consts.VMSSKey, azcache.CacheReadTypeDefault) if err != nil { @@ -1744,29 +1757,29 @@ func (ss *ScaleSet) ensureBackendPoolDeletedFromVmssUniform(ctx context.Context, vmssUniformMap := cachedUniform.(*sync.Map) var errorList []error walk := func(_, value interface{}) bool { - var vmss *compute.VirtualMachineScaleSet + var vmss *armcompute.VirtualMachineScaleSet if vmssEntry, ok := value.(*VMSSEntry); ok { vmss = vmssEntry.VMSS - } else if v, ok := value.(*compute.VirtualMachineScaleSet); ok { + } else if v, ok := value.(*armcompute.VirtualMachineScaleSet); ok { vmss = v } klog.V(2).Infof("ensureBackendPoolDeletedFromVmssUniform: vmss %q, backendPoolIDs %q", ptr.Deref(vmss.Name, ""), backendPoolIDs) // When vmss is being deleted, CreateOrUpdate API would report "the vmss is being deleted" error. // Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it. - if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.ProvisionStateDeleting) { + if vmss.Properties.ProvisioningState != nil && strings.EqualFold(*vmss.Properties.ProvisioningState, consts.ProvisionStateDeleting) { klog.V(3).Infof("ensureBackendPoolDeletedFromVMSS: found vmss %s being deleted, skipping", ptr.Deref(vmss.Name, "")) return true } - if vmss.VirtualMachineProfile == nil { + if vmss.Properties.VirtualMachineProfile == nil { klog.V(4).Infof("ensureBackendPoolDeletedFromVMSS: vmss %s has no VirtualMachineProfile, skipping", ptr.Deref(vmss.Name, "")) return true } - if vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == nil { + if vmss.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == nil { klog.V(4).Infof("ensureBackendPoolDeletedFromVMSS: cannot obtain the primary network interface configuration, of vmss %s", ptr.Deref(vmss.Name, "")) return true } - vmssNIC := *vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations + vmssNIC := vmss.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations primaryNIC, err := getPrimaryNetworkInterfaceConfiguration(vmssNIC, ptr.Deref(vmss.Name, "")) if err != nil { klog.Errorf("ensureBackendPoolDeletedFromVMSS: failed to get the primary network interface config of the VMSS %s: %v", ptr.Deref(vmss.Name, ""), err) @@ -1781,9 +1794,9 @@ func (ss *ScaleSet) ensureBackendPoolDeletedFromVmssUniform(ctx context.Context, errorList = append(errorList, err) return true } - loadBalancerBackendAddressPools := make([]compute.SubResource, 0) - if primaryIPConfig.LoadBalancerBackendAddressPools != nil { - loadBalancerBackendAddressPools = *primaryIPConfig.LoadBalancerBackendAddressPools + loadBalancerBackendAddressPools := make([]*armcompute.SubResource, 0) + if primaryIPConfig.Properties.LoadBalancerBackendAddressPools != nil { + loadBalancerBackendAddressPools = primaryIPConfig.Properties.LoadBalancerBackendAddressPools } for _, loadBalancerBackendAddressPool := range loadBalancerBackendAddressPools { klog.V(4).Infof("ensureBackendPoolDeletedFromVMSS: loadBalancerBackendAddressPool (%s) on vmss (%s)", ptr.Deref(loadBalancerBackendAddressPool.ID, ""), ptr.Deref(vmss.Name, "")) @@ -1817,7 +1830,7 @@ func (ss *ScaleSet) ensureBackendPoolDeletedFromVmssUniform(ctx context.Context, } // ensureBackendPoolDeleted ensures the loadBalancer backendAddressPools deleted from the specified nodes. -func (ss *ScaleSet) ensureBackendPoolDeleted(ctx context.Context, service *v1.Service, backendPoolIDs []string, vmSetName string, backendAddressPools *[]network.BackendAddressPool) (bool, error) { +func (ss *ScaleSet) ensureBackendPoolDeleted(ctx context.Context, service *v1.Service, backendPoolIDs []string, vmSetName string, backendAddressPools []*armnetwork.BackendAddressPool) (bool, error) { // Returns nil if backend address pools already deleted. if backendAddressPools == nil { return false, nil @@ -1830,10 +1843,10 @@ func (ss *ScaleSet) ensureBackendPoolDeleted(ctx context.Context, service *v1.Se }() ipConfigurationIDs := []string{} - for _, backendPool := range *backendAddressPools { + for _, backendPool := range backendAddressPools { for _, backendPoolID := range backendPoolIDs { - if strings.EqualFold(*backendPool.ID, backendPoolID) && backendPool.BackendIPConfigurations != nil { - for _, ipConf := range *backendPool.BackendIPConfigurations { + if strings.EqualFold(*backendPool.ID, backendPoolID) && backendPool.Properties.BackendIPConfigurations != nil { + for _, ipConf := range backendPool.Properties.BackendIPConfigurations { if ipConf.ID == nil { continue } @@ -1846,7 +1859,7 @@ func (ss *ScaleSet) ensureBackendPoolDeleted(ctx context.Context, service *v1.Se // Ensure the backendPoolID is deleted from the VMSS VMs. hostUpdates := make([]func() error, 0, len(ipConfigurationIDs)) - nodeUpdates := make(map[vmssMetaInfo]map[string]compute.VirtualMachineScaleSetVM) + nodeUpdates := make(map[vmssMetaInfo]map[string]armcompute.VirtualMachineScaleSetVM) allErrs := make([]error, 0) visitedIPConfigIDPrefix := map[string]bool{} for i := range ipConfigurationIDs { @@ -1901,7 +1914,7 @@ func (ss *ScaleSet) ensureBackendPoolDeleted(ctx context.Context, service *v1.Se if v, ok := nodeUpdates[nodeVMSSMetaInfo]; ok { v[nodeInstanceID] = *nodeVMSSVM } else { - nodeUpdates[nodeVMSSMetaInfo] = map[string]compute.VirtualMachineScaleSetVM{ + nodeUpdates[nodeVMSSMetaInfo] = map[string]armcompute.VirtualMachineScaleSetVM{ nodeInstanceID: *nodeVMSSVM, } } @@ -1931,14 +1944,22 @@ func (ss *ScaleSet) ensureBackendPoolDeleted(ctx context.Context, service *v1.Se klog.ErrorS(err, "Failed to get vmss batch size", logFields...) return err } - - klog.V(2).InfoS("Begin to update VMs for VMSS with new backendPoolID", logFields...) - rerr := ss.VirtualMachineScaleSetVMsClient.UpdateVMs(ctx, meta.resourceGroup, meta.vmssName, update, "network_update", batchSize) - if rerr != nil { + grp, ctx := errgroup.WithContext(ctx) + grp.SetLimit(batchSize) + for instanceID, vm := range update { + instanceID := instanceID + vm := vm + grp.Go(func() error { + klog.V(2).InfoS("Begin to update VMs for VMSS with new backendPoolID", logFields...) + _, rerr := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().Update(ctx, meta.resourceGroup, meta.vmssName, instanceID, vm) + return rerr + }) + } + err = grp.Wait() + if err != nil { klog.ErrorS(err, "Failed to update VMs for VMSS", logFields...) - return rerr.Error() + return err } - updatedVM.Store(true) return nil }) @@ -1958,20 +1979,20 @@ func (ss *ScaleSet) ensureBackendPoolDeleted(ctx context.Context, service *v1.Se } // EnsureBackendPoolDeleted ensures the loadBalancer backendAddressPools deleted from the specified nodes. -func (ss *ScaleSet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Service, backendPoolIDs []string, vmSetName string, backendAddressPools *[]network.BackendAddressPool, deleteFromVMSet bool) (bool, error) { +func (ss *ScaleSet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Service, backendPoolIDs []string, vmSetName string, backendAddressPools []*armnetwork.BackendAddressPool, deleteFromVMSet bool) (bool, error) { if backendAddressPools == nil { return false, nil } - vmssUniformBackendIPConfigurationsMap := map[string][]network.InterfaceIPConfiguration{} - vmssFlexBackendIPConfigurationsMap := map[string][]network.InterfaceIPConfiguration{} - avSetBackendIPConfigurationsMap := map[string][]network.InterfaceIPConfiguration{} + vmssUniformBackendIPConfigurationsMap := map[string][]*armnetwork.InterfaceIPConfiguration{} + vmssFlexBackendIPConfigurationsMap := map[string][]*armnetwork.InterfaceIPConfiguration{} + avSetBackendIPConfigurationsMap := map[string][]*armnetwork.InterfaceIPConfiguration{} - for _, backendPool := range *backendAddressPools { + for _, backendPool := range backendAddressPools { for _, backendPoolID := range backendPoolIDs { if strings.EqualFold(*backendPool.ID, backendPoolID) && - backendPool.BackendAddressPoolPropertiesFormat != nil && - backendPool.BackendIPConfigurations != nil { - for _, ipConf := range *backendPool.BackendIPConfigurations { + backendPool.Properties != nil && + backendPool.Properties.BackendIPConfigurations != nil { + for _, ipConf := range backendPool.Properties.BackendIPConfigurations { if ipConf.ID == nil { continue } @@ -2008,18 +2029,18 @@ func (ss *ScaleSet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Se } var updated bool - vmssUniformBackendPools := []network.BackendAddressPool{} + vmssUniformBackendPools := []*armnetwork.BackendAddressPool{} for backendPoolID, vmssUniformBackendIPConfigurations := range vmssUniformBackendIPConfigurationsMap { vmssUniformBackendIPConfigurations := vmssUniformBackendIPConfigurations - vmssUniformBackendPools = append(vmssUniformBackendPools, network.BackendAddressPool{ + vmssUniformBackendPools = append(vmssUniformBackendPools, &armnetwork.BackendAddressPool{ ID: ptr.To(backendPoolID), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &vmssUniformBackendIPConfigurations, + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: vmssUniformBackendIPConfigurations, }, }) } if len(vmssUniformBackendPools) > 0 { - updatedVM, err := ss.ensureBackendPoolDeleted(ctx, service, backendPoolIDs, vmSetName, &vmssUniformBackendPools) + updatedVM, err := ss.ensureBackendPoolDeleted(ctx, service, backendPoolIDs, vmSetName, vmssUniformBackendPools) if err != nil { return false, err } @@ -2028,18 +2049,18 @@ func (ss *ScaleSet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Se } } - vmssFlexBackendPools := []network.BackendAddressPool{} + vmssFlexBackendPools := []*armnetwork.BackendAddressPool{} for backendPoolID, vmssFlexBackendIPConfigurations := range vmssFlexBackendIPConfigurationsMap { vmssFlexBackendIPConfigurations := vmssFlexBackendIPConfigurations - vmssFlexBackendPools = append(vmssFlexBackendPools, network.BackendAddressPool{ + vmssFlexBackendPools = append(vmssFlexBackendPools, &armnetwork.BackendAddressPool{ ID: ptr.To(backendPoolID), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &vmssFlexBackendIPConfigurations, + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: vmssFlexBackendIPConfigurations, }, }) } if len(vmssFlexBackendPools) > 0 { - updatedNIC, err := ss.flexScaleSet.EnsureBackendPoolDeleted(ctx, service, backendPoolIDs, vmSetName, &vmssFlexBackendPools, false) + updatedNIC, err := ss.flexScaleSet.EnsureBackendPoolDeleted(ctx, service, backendPoolIDs, vmSetName, vmssFlexBackendPools, false) if err != nil { return false, err } @@ -2048,18 +2069,18 @@ func (ss *ScaleSet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Se } } - avSetBackendPools := []network.BackendAddressPool{} + avSetBackendPools := []*armnetwork.BackendAddressPool{} for backendPoolID, avSetBackendIPConfigurations := range avSetBackendIPConfigurationsMap { avSetBackendIPConfigurations := avSetBackendIPConfigurations - avSetBackendPools = append(avSetBackendPools, network.BackendAddressPool{ + avSetBackendPools = append(avSetBackendPools, &armnetwork.BackendAddressPool{ ID: ptr.To(backendPoolID), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &avSetBackendIPConfigurations, + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: avSetBackendIPConfigurations, }, }) } if len(avSetBackendPools) > 0 { - updatedNIC, err := ss.availabilitySet.EnsureBackendPoolDeleted(ctx, service, backendPoolIDs, vmSetName, &avSetBackendPools, false) + updatedNIC, err := ss.availabilitySet.EnsureBackendPoolDeleted(ctx, service, backendPoolIDs, vmSetName, avSetBackendPools, false) if err != nil { return false, err } @@ -2116,19 +2137,19 @@ func (ss *ScaleSet) GetNodeCIDRMasksByProviderID(ctx context.Context, providerID } // deleteBackendPoolFromIPConfig deletes the backend pool from the IP config. -func deleteBackendPoolFromIPConfig(msg, backendPoolID, resource string, primaryNIC *compute.VirtualMachineScaleSetNetworkConfiguration) (bool, error) { +func deleteBackendPoolFromIPConfig(msg, backendPoolID, resource string, primaryNIC *armcompute.VirtualMachineScaleSetNetworkConfiguration) (bool, error) { primaryIPConfig, err := getPrimaryIPConfigFromVMSSNetworkConfig(primaryNIC, backendPoolID, resource) if err != nil { klog.Errorf("%s: failed to get the primary IP config from the VMSS %q's network config: %v", msg, resource, err) return false, err } - loadBalancerBackendAddressPools := []compute.SubResource{} - if primaryIPConfig.LoadBalancerBackendAddressPools != nil { - loadBalancerBackendAddressPools = *primaryIPConfig.LoadBalancerBackendAddressPools + loadBalancerBackendAddressPools := []*armcompute.SubResource{} + if primaryIPConfig.Properties.LoadBalancerBackendAddressPools != nil { + loadBalancerBackendAddressPools = primaryIPConfig.Properties.LoadBalancerBackendAddressPools } var found bool - var newBackendPools []compute.SubResource + var newBackendPools []*armcompute.SubResource for i := len(loadBalancerBackendAddressPools) - 1; i >= 0; i-- { curPool := loadBalancerBackendAddressPools[i] if strings.EqualFold(backendPoolID, *curPool.ID) { @@ -2140,7 +2161,7 @@ func deleteBackendPoolFromIPConfig(msg, backendPoolID, resource string, primaryN if !found { return false, nil } - primaryIPConfig.LoadBalancerBackendAddressPools = &newBackendPools + primaryIPConfig.Properties.LoadBalancerBackendAddressPools = newBackendPools return true, nil } @@ -2159,15 +2180,15 @@ func (ss *ScaleSet) EnsureBackendPoolDeletedFromVMSets(ctx context.Context, vmss // When vmss is being deleted, CreateOrUpdate API would report "the vmss is being deleted" error. // Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it. - if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.ProvisionStateDeleting) { + if vmss.Properties.ProvisioningState != nil && strings.EqualFold(*vmss.Properties.ProvisioningState, consts.ProvisionStateDeleting) { klog.V(3).Infof("EnsureBackendPoolDeletedFromVMSets: found vmss %s being deleted, skipping", vmssName) continue } - if vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == nil { + if vmss.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == nil { klog.V(4).Infof("EnsureBackendPoolDeletedFromVMSets: cannot obtain the primary network interface configuration, of vmss %s", vmssName) continue } - vmssNIC := *vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations + vmssNIC := vmss.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations primaryNIC, err := getPrimaryNetworkInterfaceConfiguration(vmssNIC, vmssName) if err != nil { klog.Errorf("EnsureBackendPoolDeletedFromVMSets: failed to get the primary network interface config of the VMSS %s: %v", vmssName, err) @@ -2191,12 +2212,12 @@ func (ss *ScaleSet) EnsureBackendPoolDeletedFromVMSets(ctx context.Context, vmss vmssUpdaters = append(vmssUpdaters, func() error { // Compose a new vmss with added backendPoolID. - newVMSS := compute.VirtualMachineScaleSet{ + newVMSS := armcompute.VirtualMachineScaleSet{ Location: vmss.Location, - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{ - NetworkProfile: &compute.VirtualMachineScaleSetNetworkProfile{ - NetworkInterfaceConfigurations: &vmssNIC, + Properties: &armcompute.VirtualMachineScaleSetProperties{ + VirtualMachineProfile: &armcompute.VirtualMachineScaleSetVMProfile{ + NetworkProfile: &armcompute.VirtualMachineScaleSetNetworkProfile{ + NetworkInterfaceConfigurations: vmssNIC, }, }, }, @@ -2206,7 +2227,7 @@ func (ss *ScaleSet) EnsureBackendPoolDeletedFromVMSets(ctx context.Context, vmss rerr := ss.CreateOrUpdateVMSS(ss.ResourceGroup, vmssName, newVMSS) if rerr != nil { klog.Errorf("EnsureBackendPoolDeletedFromVMSets CreateOrUpdateVMSS(%s) with new backendPoolIDs %q, err: %v", vmssName, backendPoolIDs, rerr) - return rerr.Error() + return rerr } return nil @@ -2228,14 +2249,14 @@ func (ss *ScaleSet) EnsureBackendPoolDeletedFromVMSets(ctx context.Context, vmss // GetAgentPoolVMSetNames returns all VMSS/VMAS names according to the nodes. // We need to include the VMAS here because some of the cluster provisioning tools // like capz allows mixed instance type. -func (ss *ScaleSet) GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1.Node) (*[]string, error) { - vmSetNames := make([]string, 0) +func (ss *ScaleSet) GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1.Node) ([]*string, error) { + vmSetNames := make([]*string, 0) vmssFlexVMNodes := make([]*v1.Node, 0) avSetVMNodes := make([]*v1.Node, 0) for _, node := range nodes { - var names *[]string + var names []string vmManagementType, err := ss.getVMManagementTypeByNodeName(ctx, node.Name, azcache.CacheReadTypeDefault) if err != nil { @@ -2257,7 +2278,7 @@ func (ss *ScaleSet) GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1.Node if err != nil { return nil, fmt.Errorf("GetAgentPoolVMSetNames: failed to execute getAgentPoolScaleSets: %w", err) } - vmSetNames = append(vmSetNames, *names...) + vmSetNames = append(vmSetNames, to.SliceOfPtrs(names...)...) } if len(vmssFlexVMNodes) > 0 { @@ -2265,7 +2286,7 @@ func (ss *ScaleSet) GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1.Node if err != nil { return nil, fmt.Errorf("ss.flexScaleSet.GetAgentPoolVMSetNames: failed to execute : %w", err) } - vmSetNames = append(vmSetNames, *vmssFlexVMnames...) + vmSetNames = append(vmSetNames, vmssFlexVMnames...) } if len(avSetVMNodes) > 0 { @@ -2273,10 +2294,10 @@ func (ss *ScaleSet) GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1.Node if err != nil { return nil, fmt.Errorf("ss.availabilitySet.GetAgentPoolVMSetNames: failed to execute : %w", err) } - vmSetNames = append(vmSetNames, *avSetVMnames...) + vmSetNames = append(vmSetNames, avSetVMnames...) } - return &vmSetNames, nil + return vmSetNames, nil } func (ss *ScaleSet) GetNodeVMSetName(ctx context.Context, node *v1.Node) (string, error) { diff --git a/pkg/provider/azure_vmss_cache.go b/pkg/provider/azure_vmss_cache.go index e011f85e9a..59d27f0e0c 100644 --- a/pkg/provider/azure_vmss_cache.go +++ b/pkg/provider/azure_vmss_cache.go @@ -23,13 +23,13 @@ import ( "sync" "time" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "k8s.io/klog/v2" "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" + "sigs.k8s.io/cloud-provider-azure/pkg/util/errutils" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) @@ -37,12 +37,12 @@ type VMSSVirtualMachineEntry struct { ResourceGroup string VMSSName string InstanceID string - VirtualMachine *compute.VirtualMachineScaleSetVM + VirtualMachine *armcompute.VirtualMachineScaleSetVM LastUpdate time.Time } type VMSSEntry struct { - VMSS *compute.VirtualMachineScaleSet + VMSS *armcompute.VirtualMachineScaleSet ResourceGroup string LastUpdate time.Time } @@ -75,15 +75,15 @@ func (ss *ScaleSet) newVMSSCache() (azcache.Resource, error) { resourceGroupNotFound := false for _, resourceGroup := range allResourceGroups.UnsortedList() { - allScaleSets, rerr := ss.VirtualMachineScaleSetsClient.List(ctx, resourceGroup) + allScaleSets, rerr := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().List(ctx, resourceGroup) if rerr != nil { - if rerr.IsNotFound() { + if exists, err := errutils.CheckResourceExistsFromAzcoreError(rerr); !exists && err == nil { klog.Warningf("Skip caching vmss for resource group %s due to error: %v", resourceGroup, rerr.Error()) resourceGroupNotFound = true continue } - klog.Errorf("VirtualMachineScaleSetsClient.List failed: %v", rerr) - return nil, rerr.Error() + klog.Errorf("ComputeClientFactory.GetVirtualMachineScaleSetClient().List failed: %v", rerr) + return nil, rerr } for i := range allScaleSets { @@ -92,9 +92,9 @@ func (ss *ScaleSet) newVMSSCache() (azcache.Resource, error) { klog.Warning("failed to get the name of VMSS") continue } - if scaleSet.OrchestrationMode == "" || scaleSet.OrchestrationMode == compute.Uniform { + if scaleSet.Properties.OrchestrationMode == nil || *scaleSet.Properties.OrchestrationMode == armcompute.OrchestrationModeUniform { localCache.Store(*scaleSet.Name, &VMSSEntry{ - VMSS: &scaleSet, + VMSS: scaleSet, ResourceGroup: resourceGroup, LastUpdate: time.Now().UTC(), }) @@ -180,13 +180,13 @@ func (ss *ScaleSet) newVMSSVirtualMachinesCache() (azcache.Resource, error) { for i := range vms { vm := vms[i] - if vm.OsProfile == nil || vm.OsProfile.ComputerName == nil { + if vm.Properties.OSProfile == nil || vm.Properties.OSProfile.ComputerName == nil { klog.Warningf("failed to get computerName for vmssVM (%q)", vmssName) continue } - computerName := strings.ToLower(*vm.OsProfile.ComputerName) - if vm.NetworkProfile == nil || vm.NetworkProfile.NetworkInterfaces == nil { + computerName := strings.ToLower(*vm.Properties.OSProfile.ComputerName) + if vm.Properties.NetworkProfile == nil || vm.Properties.NetworkProfile.NetworkInterfaces == nil { klog.Warningf("skip caching vmssVM %s since its network profile hasn't initialized yet (probably still under creating)", computerName) continue } @@ -195,12 +195,12 @@ func (ss *ScaleSet) newVMSSVirtualMachinesCache() (azcache.Resource, error) { ResourceGroup: resourceGroupName, VMSSName: vmssName, InstanceID: ptr.Deref(vm.InstanceID, ""), - VirtualMachine: &vm, + VirtualMachine: vm, LastUpdate: time.Now().UTC(), } // set cache entry to nil when the VM is under deleting. - if vm.VirtualMachineScaleSetVMProperties != nil && - strings.EqualFold(ptr.Deref(vm.VirtualMachineScaleSetVMProperties.ProvisioningState, ""), string(consts.ProvisioningStateDeleting)) { + if vm.Properties != nil && + strings.EqualFold(ptr.Deref(vm.Properties.ProvisioningState, ""), string(consts.ProvisioningStateDeleting)) { klog.V(4).Infof("VMSS virtualMachine %q is under deleting, setting its cache to nil", computerName) vmssVMCacheEntry.VirtualMachine = nil } @@ -287,7 +287,7 @@ func (ss *ScaleSet) DeleteCacheForNode(ctx context.Context, nodeName string) err return nil } -func (ss *ScaleSet) updateCache(ctx context.Context, nodeName, resourceGroupName, vmssName, instanceID string, updatedVM *compute.VirtualMachineScaleSetVM) error { +func (ss *ScaleSet) updateCache(ctx context.Context, nodeName, resourceGroupName, vmssName, instanceID string, updatedVM *armcompute.VirtualMachineScaleSetVM) error { // lock the VMSS entry to ensure a consistent view of the VM map when there are concurrent updates. cacheKey := getVMSSVMCacheKey(resourceGroupName, vmssName) ss.lockMap.LockEntry(cacheKey) @@ -340,14 +340,14 @@ func (ss *ScaleSet) newNonVmssUniformNodesCache() (azcache.Resource, error) { return nil, fmt.Errorf("getter function of nonVmssUniformNodesCache: failed to list vms in the resource group %s: %w", resourceGroup, err) } for _, vm := range vms { - if vm.OsProfile != nil && vm.OsProfile.ComputerName != nil { - if vm.VirtualMachineScaleSet != nil { - vmssFlexVMNodeNames.Insert(strings.ToLower(ptr.Deref(vm.OsProfile.ComputerName, ""))) + if vm.Properties.OSProfile != nil && vm.Properties.OSProfile.ComputerName != nil { + if vm.Properties.VirtualMachineScaleSet != nil { + vmssFlexVMNodeNames.Insert(strings.ToLower(ptr.Deref(vm.Properties.OSProfile.ComputerName, ""))) if vm.ID != nil { vmssFlexVMProviderIDs.Insert(ss.ProviderName() + "://" + ptr.Deref(vm.ID, "")) } } else { - avSetVMNodeNames.Insert(strings.ToLower(ptr.Deref(vm.OsProfile.ComputerName, ""))) + avSetVMNodeNames.Insert(strings.ToLower(ptr.Deref(vm.Properties.OSProfile.ComputerName, ""))) if vm.ID != nil { avSetVMProviderIDs.Insert(ss.ProviderName() + "://" + ptr.Deref(vm.ID, "")) } @@ -524,14 +524,14 @@ func (ss *ScaleSet) getVMManagementTypeByIPConfigurationID(ctx context.Context, } func (az *Cloud) GetVMNameByIPConfigurationName(ctx context.Context, nicResourceGroup, nicName string) (string, error) { - nic, rerr := az.InterfacesClient.Get(ctx, nicResourceGroup, nicName, "") + nic, rerr := az.NetworkClientFactory.GetInterfaceClient().Get(ctx, nicResourceGroup, nicName, nil) if rerr != nil { - return "", fmt.Errorf("failed to get interface of name %s: %w", nicName, rerr.Error()) + return "", fmt.Errorf("failed to get interface of name %s: %w", nicName, rerr) } - if nic.InterfacePropertiesFormat == nil || nic.InterfacePropertiesFormat.VirtualMachine == nil || nic.InterfacePropertiesFormat.VirtualMachine.ID == nil { + if nic.Properties == nil || nic.Properties.VirtualMachine == nil || nic.Properties.VirtualMachine.ID == nil { return "", fmt.Errorf("failed to get vm ID of nic %s", ptr.Deref(nic.Name, "")) } - vmID := ptr.Deref(nic.InterfacePropertiesFormat.VirtualMachine.ID, "") + vmID := ptr.Deref(nic.Properties.VirtualMachine.ID, "") matches := vmIDRE.FindStringSubmatch(vmID) if len(matches) != 2 { return "", fmt.Errorf("invalid virtual machine ID %s", vmID) diff --git a/pkg/provider/azure_vmss_cache_test.go b/pkg/provider/azure_vmss_cache_test.go index 87bb9a6393..d0403c362c 100644 --- a/pkg/provider/azure_vmss_cache_test.go +++ b/pkg/provider/azure_vmss_cache_test.go @@ -23,8 +23,10 @@ import ( "net/http" "testing" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -32,13 +34,12 @@ import ( cloudprovider "k8s.io/cloud-provider" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssvmclient/mockvmssvmclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/mock_interfaceclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/mock_virtualmachinescalesetclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetvmclient/mock_virtualmachinescalesetvmclient" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) func TestVMSSVMCache(t *testing.T) { @@ -52,32 +53,30 @@ func TestVMSSVMCache(t *testing.T) { assert.NoError(t, err) ss := vmSet.(*ScaleSet) - mockVMSSClient := mockvmssclient.NewMockInterface(ctrl) - mockVMSSVMClient := mockvmssvmclient.NewMockInterface(ctrl) - ss.VirtualMachineScaleSetsClient = mockVMSSClient - ss.VirtualMachineScaleSetVMsClient = mockVMSSVMClient + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) expectedScaleSet := buildTestVMSS(testVMSSName, "vmssee6c2") - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() expectedVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, vmList, "", false) - mockVMSSVMClient.EXPECT().List(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() // validate getting VMSS VM via cache. for i := range expectedVMs { vm := expectedVMs[i] - vmName := ptr.Deref(vm.OsProfile.ComputerName, "") + vmName := ptr.Deref(vm.Properties.OSProfile.ComputerName, "") realVM, err := ss.getVmssVM(context.TODO(), vmName, azcache.CacheReadTypeDefault) assert.NoError(t, err) assert.NotNil(t, realVM) assert.Equal(t, "vmss", realVM.VMSSName) assert.Equal(t, ptr.Deref(vm.InstanceID, ""), realVM.InstanceID) - assert.Equal(t, &vm, realVM.AsVirtualMachineScaleSetVM()) + assert.Equal(t, *vm, *realVM.AsVirtualMachineScaleSetVM()) } // validate DeleteCacheForNode(). vm := expectedVMs[0] - vmName := ptr.Deref(vm.OsProfile.ComputerName, "") + vmName := ptr.Deref(vm.Properties.OSProfile.ComputerName, "") err = ss.DeleteCacheForNode(context.TODO(), vmName) assert.NoError(t, err) @@ -86,7 +85,7 @@ func TestVMSSVMCache(t *testing.T) { assert.NoError(t, err) assert.Equal(t, "vmss", realVM.VMSSName) assert.Equal(t, ptr.Deref(vm.InstanceID, ""), realVM.InstanceID) - assert.Equal(t, &vm, realVM.AsVirtualMachineScaleSetVM()) + assert.Equal(t, vm, realVM.AsVirtualMachineScaleSetVM()) } func TestVMSSVMCacheWithDeletingNodes(t *testing.T) { @@ -97,24 +96,22 @@ func TestVMSSVMCacheWithDeletingNodes(t *testing.T) { ss, err := newTestScaleSetWithState(ctrl) assert.NoError(t, err) - mockVMSSClient := mockvmssclient.NewMockInterface(ctrl) - mockVMSSVMClient := mockvmssvmclient.NewMockInterface(ctrl) - ss.VirtualMachineScaleSetsClient = mockVMSSClient - ss.VirtualMachineScaleSetVMsClient = mockVMSSVMClient + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) - expectedScaleSet := compute.VirtualMachineScaleSet{ - Name: ptr.To(testVMSSName), - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{}, + expectedScaleSet := &armcompute.VirtualMachineScaleSet{ + Name: ptr.To(testVMSSName), + Properties: &armcompute.VirtualMachineScaleSetProperties{}, } - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() expectedVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, vmList, string(consts.ProvisioningStateDeleting), false) - mockVMSSVMClient.EXPECT().List(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() + mockVMSSVMClient.EXPECT().List(gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() for i := range expectedVMs { vm := expectedVMs[i] - vmName := ptr.Deref(vm.OsProfile.ComputerName, "") - assert.Equal(t, vm.ProvisioningState, ptr.To(string(consts.ProvisioningStateDeleting))) + vmName := ptr.Deref(vm.Properties.OSProfile.ComputerName, "") + assert.Equal(t, *vm.Properties.ProvisioningState, string(consts.ProvisioningStateDeleting)) realVM, err := ss.getVmssVM(context.TODO(), vmName, azcache.CacheReadTypeDefault) assert.Nil(t, realVM) @@ -129,26 +126,23 @@ func TestVMSSVMCacheClearedWhenRGDeleted(t *testing.T) { vmList := []string{"vmssee6c2000000", "vmssee6c2000001", "vmssee6c2000002"} ss, err := NewTestScaleSet(ctrl) assert.NoError(t, err) - - mockVMSSClient := mockvmssclient.NewMockInterface(ctrl) - mockVMSSVMClient := mockvmssvmclient.NewMockInterface(ctrl) - ss.VirtualMachineScaleSetsClient = mockVMSSClient - ss.VirtualMachineScaleSetVMsClient = mockVMSSVMClient + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) expectedScaleSet := buildTestVMSS(testVMSSName, "vmssee6c2") - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{expectedScaleSet}, nil).Times(1) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachineScaleSet{expectedScaleSet}, nil).Times(1) expectedVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, vmList, "", false) - mockVMSSVMClient.EXPECT().List(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).Times(1) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).Times(1) // validate getting VMSS VM via cache. vm := expectedVMs[0] - vmName := ptr.Deref(vm.OsProfile.ComputerName, "") + vmName := ptr.Deref(vm.Properties.OSProfile.ComputerName, "") realVM, err := ss.getVmssVM(context.TODO(), vmName, azcache.CacheReadTypeDefault) assert.NoError(t, err) assert.Equal(t, "vmss", realVM.VMSSName) assert.Equal(t, ptr.Deref(vm.InstanceID, ""), realVM.InstanceID) - assert.Equal(t, &vm, realVM.AsVirtualMachineScaleSetVM()) + assert.Equal(t, *vm, *realVM.AsVirtualMachineScaleSetVM()) // verify cache has test vmss. cacheKey := getVMSSVMCacheKey("rg", testVMSSName) @@ -156,8 +150,8 @@ func TestVMSSVMCacheClearedWhenRGDeleted(t *testing.T) { assert.Nil(t, err) // refresh the cache with error. - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{}, &retry.Error{HTTPStatusCode: http.StatusNotFound}).Times(2) - mockVMSSVMClient.EXPECT().List(gomock.Any(), "rg", testVMSSName, gomock.Any()).Return([]compute.VirtualMachineScaleSetVM{}, &retry.Error{HTTPStatusCode: http.StatusNotFound}).Times(1) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachineScaleSet{}, &azcore.ResponseError{StatusCode: http.StatusNotFound}).Times(2) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), "rg", testVMSSName).Return([]*armcompute.VirtualMachineScaleSetVM{}, &azcore.ResponseError{StatusCode: http.StatusNotFound}).Times(1) realVM, err = ss.getVmssVM(context.TODO(), vmName, azcache.CacheReadTypeForceRefresh) assert.Nil(t, realVM) assert.Equal(t, cloudprovider.InstanceNotFound, err) @@ -168,14 +162,12 @@ func TestVMSSVMCacheClearedWhenRGDeleted(t *testing.T) { } func TestGetVMManagementTypeByNodeName(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testVM1 := generateVmssFlexTestVMWithoutInstanceView(testVM1Spec) testVM2 := generateVmssFlexTestVMWithoutInstanceView(testVM2Spec) - testVM2.VirtualMachineScaleSet = nil + testVM2.Properties.VirtualMachineScaleSet = nil - testVMList := []compute.VirtualMachine{ + testVMList := []*armcompute.VirtualMachine{ testVM1, testVM2, } @@ -185,7 +177,7 @@ func TestGetVMManagementTypeByNodeName(t *testing.T) { nodeName string DisableAvailabilitySetNodes bool EnableVmssFlexNodes bool - vmListErr *retry.Error + vmListErr error expectedVMManagementType VMManagementType expectedErr error }{ @@ -222,40 +214,42 @@ func TestGetVMManagementTypeByNodeName(t *testing.T) { { description: "getVMManagementTypeByNodeName should return ManagedByUnknownVMSet if error happens", nodeName: "fakeName", - vmListErr: &retry.Error{RawError: fmt.Errorf("failed to list VMs")}, + vmListErr: &azcore.ResponseError{ErrorCode: "failed to list VMs"}, expectedVMManagementType: ManagedByUnknownVMSet, - expectedErr: fmt.Errorf("getter function of nonVmssUniformNodesCache: failed to list vms in the resource group rg: Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: failed to list VMs"), + expectedErr: fmt.Errorf("failed to list VMs"), }, } for _, tc := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, tc.description) - - ss.DisableAvailabilitySetNodes = tc.DisableAvailabilitySetNodes - ss.EnableVmssFlexNodes = tc.EnableVmssFlexNodes - - mockVMClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVMList, tc.vmListErr).AnyTimes() - - vmManagementType, err := ss.getVMManagementTypeByNodeName(context.TODO(), tc.nodeName, azcache.CacheReadTypeDefault) - assert.Equal(t, tc.expectedVMManagementType, vmManagementType, tc.description) - if tc.expectedErr != nil { - assert.EqualError(t, err, tc.expectedErr.Error(), tc.description) - } - + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, tc.description) + + ss.DisableAvailabilitySetNodes = tc.DisableAvailabilitySetNodes + ss.EnableVmssFlexNodes = tc.EnableVmssFlexNodes + + mockVMClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVMList, tc.vmListErr).AnyTimes() + + vmManagementType, err := ss.getVMManagementTypeByNodeName(context.TODO(), tc.nodeName, azcache.CacheReadTypeDefault) + assert.Equal(t, tc.expectedVMManagementType, vmManagementType, tc.description) + if tc.expectedErr != nil { + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) + } + }) } } func TestGetVMManagementTypeByProviderID(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testVM1 := generateVmssFlexTestVMWithoutInstanceView(testVM1Spec) testVM2 := generateVmssFlexTestVMWithoutInstanceView(testVM2Spec) - testVM2.VirtualMachineScaleSet = nil + testVM2.Properties.VirtualMachineScaleSet = nil - testVMList := []compute.VirtualMachine{ + testVMList := []*armcompute.VirtualMachine{ testVM1, testVM2, } @@ -265,7 +259,7 @@ func TestGetVMManagementTypeByProviderID(t *testing.T) { providerID string DisableAvailabilitySetNodes bool EnableVmssFlexNodes bool - vmListErr *retry.Error + vmListErr error expectedVMManagementType VMManagementType expectedErr error }{ @@ -302,36 +296,40 @@ func TestGetVMManagementTypeByProviderID(t *testing.T) { { description: "getVMManagementTypeByProviderID should return ManagedByUnknownVMSet if error happens", providerID: "fakeName", - vmListErr: &retry.Error{RawError: fmt.Errorf("failed to list VMs")}, + vmListErr: &azcore.ResponseError{ErrorCode: "failed to list VMs"}, expectedVMManagementType: ManagedByUnknownVMSet, - expectedErr: fmt.Errorf("getter function of nonVmssUniformNodesCache: failed to list vms in the resource group rg: Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: failed to list VMs"), + expectedErr: fmt.Errorf("failed to list VMs"), }, } for _, tc := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, tc.description) - - ss.DisableAvailabilitySetNodes = tc.DisableAvailabilitySetNodes - ss.EnableVmssFlexNodes = tc.EnableVmssFlexNodes - - mockVMClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVMList, tc.vmListErr).AnyTimes() - - vmManagementType, err := ss.getVMManagementTypeByProviderID(context.TODO(), tc.providerID, azcache.CacheReadTypeDefault) - assert.Equal(t, tc.expectedVMManagementType, vmManagementType, tc.description) - if tc.expectedErr != nil { - assert.EqualError(t, err, tc.expectedErr.Error(), tc.description) - } - + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, tc.description) + + ss.DisableAvailabilitySetNodes = tc.DisableAvailabilitySetNodes + ss.EnableVmssFlexNodes = tc.EnableVmssFlexNodes + + mockVMClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVMList, tc.vmListErr).AnyTimes() + + vmManagementType, err := ss.getVMManagementTypeByProviderID(context.TODO(), tc.providerID, azcache.CacheReadTypeDefault) + assert.Equal(t, tc.expectedVMManagementType, vmManagementType, tc.description) + if tc.expectedErr != nil { + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) + } + }) } } -func buildTestNICWithVMName(vmName string) network.Interface { - return network.Interface{ +func buildTestNICWithVMName(vmName string) *armnetwork.Interface { + return &armnetwork.Interface{ Name: &vmName, - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - VirtualMachine: &network.SubResource{ + Properties: &armnetwork.InterfacePropertiesFormat{ + VirtualMachine: &armnetwork.SubResource{ ID: ptr.To(fmt.Sprintf("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/%s", vmName)), }, }, @@ -339,15 +337,13 @@ func buildTestNICWithVMName(vmName string) network.Interface { } func TestGetVMManagementTypeByIPConfigurationID(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testVM1 := generateVmssFlexTestVMWithoutInstanceView(testVM1Spec) testVM2 := generateVmssFlexTestVMWithoutInstanceView(testVM2Spec) - testVM2.VirtualMachineScaleSet = nil - testVM2.VirtualMachineProperties.OsProfile.ComputerName = ptr.To("testvm2") + testVM2.Properties.VirtualMachineScaleSet = nil + testVM2.Properties.OSProfile.ComputerName = ptr.To("testvm2") - testVMList := []compute.VirtualMachine{ + testVMList := []*armcompute.VirtualMachine{ testVM1, testVM2, } @@ -355,15 +351,15 @@ func TestGetVMManagementTypeByIPConfigurationID(t *testing.T) { testVM1NIC := buildTestNICWithVMName("testvm1") testVM2NIC := buildTestNICWithVMName("testvm2") testVM3NIC := buildTestNICWithVMName("testvm3") - testVM3NIC.VirtualMachine = nil + testVM3NIC.Properties.VirtualMachine = nil testCases := []struct { description string ipConfigurationID string DisableAvailabilitySetNodes bool EnableVmssFlexNodes bool - vmListErr *retry.Error - nicGetErr *retry.Error + vmListErr error + nicGetErr error expectedNIC string expectedVMManagementType VMManagementType expectedErr error @@ -396,9 +392,9 @@ func TestGetVMManagementTypeByIPConfigurationID(t *testing.T) { description: "getVMManagementTypeByIPConfigurationID should return an error if failed to get nic", ipConfigurationID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/testvm1-nic/ipConfigurations/pipConfig", expectedNIC: "testvm1", - nicGetErr: &retry.Error{RawError: fmt.Errorf("failed to get nic")}, + nicGetErr: &azcore.ResponseError{ErrorCode: "failed to get nic"}, expectedVMManagementType: ManagedByUnknownVMSet, - expectedErr: fmt.Errorf("failed to get vm name by ip config ID /subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/testvm1-nic/ipConfigurations/pipConfig: %w", errors.New("failed to get interface of name testvm1-nic: Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: failed to get nic")), + expectedErr: fmt.Errorf("failed to get nic"), }, { description: "getVMManagementTypeByIPConfigurationID should return ManagedByVmssUniform for vmss uniform node", @@ -419,43 +415,48 @@ func TestGetVMManagementTypeByIPConfigurationID(t *testing.T) { { description: "getVMManagementTypeByIPConfigurationID should return ManagedByUnknownVMSet if error happens", ipConfigurationID: "fakeID", - vmListErr: &retry.Error{RawError: fmt.Errorf("failed to list VMs")}, + vmListErr: &azcore.ResponseError{ErrorCode: "failed to list VMs"}, expectedVMManagementType: ManagedByUnknownVMSet, - expectedErr: fmt.Errorf("getter function of nonVmssUniformNodesCache: failed to list vms in the resource group rg: Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: failed to list VMs"), + expectedErr: fmt.Errorf("failed to list VMs"), }, } for _, tc := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, tc.description) - - ss.DisableAvailabilitySetNodes = tc.DisableAvailabilitySetNodes - ss.EnableVmssFlexNodes = tc.EnableVmssFlexNodes - - mockVMClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVMList, tc.vmListErr).AnyTimes() - - if tc.expectedNIC != "" { - mockNICClient := ss.InterfacesClient.(*mockinterfaceclient.MockInterface) - mockNICClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ string, _ string) (network.Interface, *retry.Error) { - switch tc.expectedNIC { - case "testvm1": - return testVM1NIC, tc.nicGetErr - case "testvm2": - return testVM2NIC, tc.nicGetErr - case "testvm3": - return testVM3NIC, tc.nicGetErr - default: - return network.Interface{}, retry.NewError(false, errors.New("failed to get nic")) - } - }) - } - - vmManagementType, err := ss.getVMManagementTypeByIPConfigurationID(context.TODO(), tc.ipConfigurationID, azcache.CacheReadTypeDefault) - assert.Equal(t, tc.expectedVMManagementType, vmManagementType, tc.description) - if tc.expectedErr != nil { - assert.EqualError(t, err, tc.expectedErr.Error(), tc.description) - } - + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, tc.description) + + ss.DisableAvailabilitySetNodes = tc.DisableAvailabilitySetNodes + ss.EnableVmssFlexNodes = tc.EnableVmssFlexNodes + + mockVMClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVMList, tc.vmListErr).AnyTimes() + + if tc.expectedNIC != "" { + mockNICClient := ss.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) + mockNICClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, _ string, _ *string) (*armnetwork.Interface, error) { + switch tc.expectedNIC { + case "testvm1": + return testVM1NIC, tc.nicGetErr + case "testvm2": + return testVM2NIC, tc.nicGetErr + case "testvm3": + return testVM3NIC, tc.nicGetErr + default: + return &armnetwork.Interface{}, &azcore.ResponseError{ErrorCode: "failed to get nic"} + } + }) + } + + vmManagementType, err := ss.getVMManagementTypeByIPConfigurationID(context.TODO(), tc.ipConfigurationID, azcache.CacheReadTypeDefault) + assert.Equal(t, tc.expectedVMManagementType, vmManagementType, tc.description) + if tc.expectedErr != nil { + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) + } + }) } } diff --git a/pkg/provider/azure_vmss_repo.go b/pkg/provider/azure_vmss_repo.go index 89b5a900f2..ef551c9ceb 100644 --- a/pkg/provider/azure_vmss_repo.go +++ b/pkg/provider/azure_vmss_repo.go @@ -19,36 +19,35 @@ package provider import ( "strings" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "k8s.io/klog/v2" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) -// CreateOrUpdateVMSS invokes az.VirtualMachineScaleSetsClient.Update(). -func (az *Cloud) CreateOrUpdateVMSS(resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) *retry.Error { +// CreateOrUpdateVMSS invokes az.ComputeClientFactory.GetVirtualMachineScaleSetClient().Update(). +func (az *Cloud) CreateOrUpdateVMSS(resourceGroupName string, VMScaleSetName string, parameters armcompute.VirtualMachineScaleSet) error { ctx, cancel := getContextWithCancel() defer cancel() // When vmss is being deleted, CreateOrUpdate API would report "the vmss is being deleted" error. // Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it. klog.V(3).Infof("CreateOrUpdateVMSS: verify the status of the vmss being created or updated") - vmss, rerr := az.VirtualMachineScaleSetsClient.Get(ctx, resourceGroupName, VMScaleSetName) - if rerr != nil { - klog.Errorf("CreateOrUpdateVMSS: error getting vmss(%s): %v", VMScaleSetName, rerr) - return rerr + vmss, err := az.ComputeClientFactory.GetVirtualMachineScaleSetClient().Get(ctx, resourceGroupName, VMScaleSetName, nil) + if err != nil { + klog.Errorf("CreateOrUpdateVMSS: error getting vmss(%s): %v", VMScaleSetName, err) + return err } - if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.ProvisionStateDeleting) { + if vmss.Properties.ProvisioningState != nil && strings.EqualFold(*vmss.Properties.ProvisioningState, consts.ProvisionStateDeleting) { klog.V(3).Infof("CreateOrUpdateVMSS: found vmss %s being deleted, skipping", VMScaleSetName) return nil } - rerr = az.VirtualMachineScaleSetsClient.CreateOrUpdate(ctx, resourceGroupName, VMScaleSetName, parameters) - klog.V(10).Infof("UpdateVmssVMWithRetry: VirtualMachineScaleSetsClient.CreateOrUpdate(%s): end", VMScaleSetName) - if rerr != nil { - klog.Errorf("CreateOrUpdateVMSS: error CreateOrUpdate vmss(%s): %v", VMScaleSetName, rerr) - return rerr + _, err = az.ComputeClientFactory.GetVirtualMachineScaleSetClient().CreateOrUpdate(ctx, resourceGroupName, VMScaleSetName, parameters) + klog.V(10).Infof("UpdateVmssVMWithRetry: ComputeClientFactory.GetVirtualMachineScaleSetClient().CreateOrUpdate(%s): end", VMScaleSetName) + if err != nil { + klog.Errorf("CreateOrUpdateVMSS: error CreateOrUpdate vmss(%s): %v", VMScaleSetName, err) + return err } return nil diff --git a/pkg/provider/azure_vmss_repo_test.go b/pkg/provider/azure_vmss_repo_test.go index 4528990c08..6cbb762ddf 100644 --- a/pkg/provider/azure_vmss_repo_test.go +++ b/pkg/provider/azure_vmss_repo_test.go @@ -22,8 +22,10 @@ import ( "net/http" "testing" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -32,39 +34,36 @@ import ( cloudprovider "k8s.io/cloud-provider" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/mock_interfaceclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipaddressclient/mock_publicipaddressclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/mock_virtualmachinescalesetclient" "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) func TestCreateOrUpdateVMSS(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() tests := []struct { - vmss compute.VirtualMachineScaleSet - clientErr *retry.Error - expectedErr *retry.Error + vmss *armcompute.VirtualMachineScaleSet + clientErr error + expectedErr error }{ { - clientErr: &retry.Error{HTTPStatusCode: http.StatusInternalServerError}, - expectedErr: &retry.Error{HTTPStatusCode: http.StatusInternalServerError}, + clientErr: &azcore.ResponseError{StatusCode: http.StatusInternalServerError}, + expectedErr: &azcore.ResponseError{StatusCode: http.StatusInternalServerError}, }, { - clientErr: &retry.Error{HTTPStatusCode: http.StatusTooManyRequests}, - expectedErr: &retry.Error{HTTPStatusCode: http.StatusTooManyRequests}, + clientErr: &azcore.ResponseError{StatusCode: http.StatusTooManyRequests}, + expectedErr: &azcore.ResponseError{StatusCode: http.StatusTooManyRequests}, }, { - clientErr: &retry.Error{RawError: fmt.Errorf("azure cloud provider rate limited(write) for operation CreateOrUpdate")}, - expectedErr: &retry.Error{RawError: fmt.Errorf("azure cloud provider rate limited(write) for operation CreateOrUpdate")}, + clientErr: &azcore.ResponseError{ErrorCode: "azure cloud provider rate limited(write) for operation CreateOrUpdate"}, + expectedErr: &azcore.ResponseError{ErrorCode: "azure cloud provider rate limited(write) for operation CreateOrUpdate"}, }, { - vmss: compute.VirtualMachineScaleSet{ - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ + vmss: &armcompute.VirtualMachineScaleSet{ + Properties: &armcompute.VirtualMachineScaleSetProperties{ ProvisioningState: ptr.To(consts.ProvisionStateDeleting), }, }, @@ -72,44 +71,58 @@ func TestCreateOrUpdateVMSS(t *testing.T) { } for _, test := range tests { - az := GetTestCloud(ctrl) - - mockVMSSClient := az.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, testVMSSName).Return(test.vmss, test.clientErr) - - err := az.CreateOrUpdateVMSS(az.ResourceGroup, testVMSSName, compute.VirtualMachineScaleSet{}) - assert.Equal(t, test.expectedErr, err) + test := test + t.Run(fmt.Sprintf("TestCreateOrUpdateVMSS-%v", test.expectedErr), func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + az := GetTestCloud(ctrl) + + mockVMSSClient := az.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, testVMSSName, nil).Return(test.vmss, test.clientErr) + + err := az.CreateOrUpdateVMSS(az.ResourceGroup, testVMSSName, armcompute.VirtualMachineScaleSet{}) + if test.expectedErr != nil { + assert.Contains(t, err.Error(), test.expectedErr.Error()) + } else { + assert.Nil(t, err) + } + }) } } func TestGetVirtualMachineWithRetry(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() tests := []struct { - vmClientErr *retry.Error + vmClientErr error expectedErr error }{ { - vmClientErr: &retry.Error{HTTPStatusCode: http.StatusNotFound}, + vmClientErr: &azcore.ResponseError{StatusCode: http.StatusNotFound}, expectedErr: cloudprovider.InstanceNotFound, }, { - vmClientErr: &retry.Error{HTTPStatusCode: http.StatusInternalServerError}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil)), + vmClientErr: &azcore.ResponseError{StatusCode: http.StatusInternalServerError}, + expectedErr: fmt.Errorf("UNAVAILABLE"), }, } for _, test := range tests { - az := GetTestCloud(ctrl) - mockVMClient := az.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "vm", gomock.Any()).Return(compute.VirtualMachine{}, test.vmClientErr) - - vm, err := az.GetVirtualMachineWithRetry(context.TODO(), "vm", cache.CacheReadTypeDefault) - assert.Empty(t, vm) - if err != nil { - assert.EqualError(t, test.expectedErr, err.Error()) - } + test := test + t.Run(fmt.Sprintf("TestGetVirtualMachineWithRetry-%v", test.expectedErr), func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + az := GetTestCloud(ctrl) + mockVMClient := az.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "vm", gomock.Any()).Return(&armcompute.VirtualMachine{}, test.vmClientErr) + + vm, err := az.GetVirtualMachineWithRetry(context.TODO(), "vm", cache.CacheReadTypeDefault) + assert.Empty(t, vm) + if err != nil { + assert.Contains(t, err.Error(), test.expectedErr.Error()) + } + }) } } @@ -118,7 +131,7 @@ func TestGetPrivateIPsForMachine(t *testing.T) { defer ctrl.Finish() tests := []struct { - vmClientErr *retry.Error + vmClientErr error expectedPrivateIPs []string expectedErr error }{ @@ -126,24 +139,24 @@ func TestGetPrivateIPsForMachine(t *testing.T) { expectedPrivateIPs: []string{"1.2.3.4"}, }, { - vmClientErr: &retry.Error{HTTPStatusCode: http.StatusNotFound}, + vmClientErr: &azcore.ResponseError{StatusCode: http.StatusNotFound}, expectedErr: cloudprovider.InstanceNotFound, expectedPrivateIPs: []string{}, }, { - vmClientErr: &retry.Error{HTTPStatusCode: http.StatusInternalServerError}, + vmClientErr: &azcore.ResponseError{StatusCode: http.StatusInternalServerError}, expectedErr: wait.ErrWaitTimeout, expectedPrivateIPs: []string{}, }, } - expectedVM := compute.VirtualMachine{ - VirtualMachineProperties: &compute.VirtualMachineProperties{ - AvailabilitySet: &compute.SubResource{ID: ptr.To("availability-set")}, - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &[]compute.NetworkInterfaceReference{ + expectedVM := &armcompute.VirtualMachine{ + Properties: &armcompute.VirtualMachineProperties{ + AvailabilitySet: &armcompute.SubResource{ID: ptr.To("availability-set")}, + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: []*armcompute.NetworkInterfaceReference{ { - NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ + Properties: &armcompute.NetworkInterfaceReferenceProperties{ Primary: ptr.To(true), }, ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"), @@ -153,11 +166,11 @@ func TestGetPrivateIPsForMachine(t *testing.T) { }, } - expectedInterface := network.Interface{ - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - IPConfigurations: &[]network.InterfaceIPConfiguration{ + expectedInterface := &armnetwork.Interface{ + Properties: &armnetwork.InterfacePropertiesFormat{ + IPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ PrivateIPAddress: ptr.To("1.2.3.4"), }, }, @@ -167,10 +180,10 @@ func TestGetPrivateIPsForMachine(t *testing.T) { for _, test := range tests { az := GetTestCloud(ctrl) - mockVMClient := az.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMClient := az.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "vm", gomock.Any()).Return(expectedVM, test.vmClientErr) - mockInterfaceClient := az.InterfacesClient.(*mockinterfaceclient.MockInterface) + mockInterfaceClient := az.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) mockInterfaceClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(expectedInterface, nil).MaxTimes(1) privateIPs, err := az.getPrivateIPsForMachine(context.Background(), "vm") @@ -184,7 +197,7 @@ func TestGetIPForMachineWithRetry(t *testing.T) { defer ctrl.Finish() tests := []struct { - clientErr *retry.Error + clientErr error expectedPrivateIP string expectedPublicIP string expectedErr error @@ -194,18 +207,18 @@ func TestGetIPForMachineWithRetry(t *testing.T) { expectedPublicIP: "5.6.7.8", }, { - clientErr: &retry.Error{HTTPStatusCode: http.StatusNotFound}, + clientErr: &azcore.ResponseError{StatusCode: http.StatusNotFound}, expectedErr: wait.ErrWaitTimeout, }, } - expectedVM := compute.VirtualMachine{ - VirtualMachineProperties: &compute.VirtualMachineProperties{ - AvailabilitySet: &compute.SubResource{ID: ptr.To("availability-set")}, - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &[]compute.NetworkInterfaceReference{ + expectedVM := &armcompute.VirtualMachine{ + Properties: &armcompute.VirtualMachineProperties{ + AvailabilitySet: &armcompute.SubResource{ID: ptr.To("availability-set")}, + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: []*armcompute.NetworkInterfaceReference{ { - NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ + Properties: &armcompute.NetworkInterfaceReferenceProperties{ Primary: ptr.To(true), }, ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"), @@ -215,13 +228,13 @@ func TestGetIPForMachineWithRetry(t *testing.T) { }, } - expectedInterface := network.Interface{ - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - IPConfigurations: &[]network.InterfaceIPConfiguration{ + expectedInterface := &armnetwork.Interface{ + Properties: &armnetwork.InterfacePropertiesFormat{ + IPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ PrivateIPAddress: ptr.To("1.2.3.4"), - PublicIPAddress: &network.PublicIPAddress{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To("test/pip"), }, }, @@ -230,23 +243,23 @@ func TestGetIPForMachineWithRetry(t *testing.T) { }, } - expectedPIP := network.PublicIPAddress{ + expectedPIP := &armnetwork.PublicIPAddress{ Name: ptr.To("pip"), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To("5.6.7.8"), }, } for _, test := range tests { az := GetTestCloud(ctrl) - mockVMClient := az.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMClient := az.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "vm", gomock.Any()).Return(expectedVM, test.clientErr) - mockInterfaceClient := az.InterfacesClient.(*mockinterfaceclient.MockInterface) + mockInterfaceClient := az.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) mockInterfaceClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(expectedInterface, nil).MaxTimes(1) - mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) - mockPIPClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]network.PublicIPAddress{expectedPIP}, nil).MaxTimes(1) + mockPIPClient := az.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + mockPIPClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]*armnetwork.PublicIPAddress{expectedPIP}, nil).MaxTimes(1) privateIP, publicIP, err := az.GetIPForMachineWithRetry(context.Background(), "vm") assert.Equal(t, test.expectedErr, err) diff --git a/pkg/provider/azure_vmss_test.go b/pkg/provider/azure_vmss_test.go index e0d6aad139..36afff79d8 100644 --- a/pkg/provider/azure_vmss_test.go +++ b/pkg/provider/azure_vmss_test.go @@ -23,8 +23,11 @@ import ( "strings" "testing" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -35,15 +38,14 @@ import ( cloudprovider "k8s.io/cloud-provider" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssvmclient/mockvmssvmclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/mock_interfaceclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipaddressclient/mock_publicipaddressclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/mock_virtualmachinescalesetclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetvmclient/mock_virtualmachinescalesetvmclient" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/provider/virtualmachine" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) @@ -71,24 +73,24 @@ const ( ubuntu ) -func buildTestOSSpecificVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []string, os osVersion, ipv6 bool) compute.VirtualMachineScaleSet { +func buildTestOSSpecificVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []string, os osVersion, ipv6 bool) *armcompute.VirtualMachineScaleSet { vmss := buildTestVMSSWithLB(name, namePrefix, lbBackendpoolIDs, ipv6) switch os { case windows2019: - vmss.VirtualMachineScaleSetProperties.VirtualMachineProfile.StorageProfile = &compute.VirtualMachineScaleSetStorageProfile{ - OsDisk: &compute.VirtualMachineScaleSetOSDisk{ - OsType: compute.OperatingSystemTypesWindows, + vmss.Properties.VirtualMachineProfile.StorageProfile = &armcompute.VirtualMachineScaleSetStorageProfile{ + OSDisk: &armcompute.VirtualMachineScaleSetOSDisk{ + OSType: to.Ptr(armcompute.OperatingSystemTypesWindows), }, - ImageReference: &compute.ImageReference{ + ImageReference: &armcompute.ImageReference{ ID: ptr.To("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/AKS-Windows/providers/Microsoft.Compute/galleries/AKSWindows/images/windows-2019-containerd/versions/17763.5820.240516"), }, } case windows2022: - vmss.VirtualMachineScaleSetProperties.VirtualMachineProfile.StorageProfile = &compute.VirtualMachineScaleSetStorageProfile{ - OsDisk: &compute.VirtualMachineScaleSetOSDisk{ - OsType: compute.OperatingSystemTypesWindows, + vmss.Properties.VirtualMachineProfile.StorageProfile = &armcompute.VirtualMachineScaleSetStorageProfile{ + OSDisk: &armcompute.VirtualMachineScaleSetOSDisk{ + OSType: to.Ptr(armcompute.OperatingSystemTypesWindows), }, - ImageReference: &compute.ImageReference{ + ImageReference: &armcompute.ImageReference{ ID: ptr.To("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/AKS-Windows/providers/Microsoft.Compute/galleries/AKSWindows/images/windows-2022-containerd/versions/20348.5820.240516"), }, } @@ -96,43 +98,43 @@ func buildTestOSSpecificVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []s return vmss } -func buildTestVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []string, ipv6 bool) compute.VirtualMachineScaleSet { - lbBackendpoolsV4, lbBackendpoolsV6 := make([]compute.SubResource, 0), make([]compute.SubResource, 0) +func buildTestVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []string, ipv6 bool) *armcompute.VirtualMachineScaleSet { + lbBackendpoolsV4, lbBackendpoolsV6 := make([]*armcompute.SubResource, 0), make([]*armcompute.SubResource, 0) for _, id := range lbBackendpoolIDs { - lbBackendpoolsV4 = append(lbBackendpoolsV4, compute.SubResource{ID: ptr.To(id)}) - lbBackendpoolsV6 = append(lbBackendpoolsV6, compute.SubResource{ID: ptr.To(id + "-" + consts.IPVersionIPv6String)}) + lbBackendpoolsV4 = append(lbBackendpoolsV4, &armcompute.SubResource{ID: ptr.To(id)}) + lbBackendpoolsV6 = append(lbBackendpoolsV6, &armcompute.SubResource{ID: ptr.To(id + "-" + consts.IPVersionIPv6String)}) } - ipConfig := []compute.VirtualMachineScaleSetIPConfiguration{ + ipConfig := []*armcompute.VirtualMachineScaleSetIPConfiguration{ { - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - LoadBalancerBackendAddressPools: &lbBackendpoolsV4, + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ + LoadBalancerBackendAddressPools: lbBackendpoolsV4, }, }, } if ipv6 { - ipConfig = append(ipConfig, compute.VirtualMachineScaleSetIPConfiguration{ - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - LoadBalancerBackendAddressPools: &lbBackendpoolsV6, - PrivateIPAddressVersion: compute.IPv6, + ipConfig = append(ipConfig, &armcompute.VirtualMachineScaleSetIPConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ + LoadBalancerBackendAddressPools: lbBackendpoolsV6, + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv6), }, }) } - expectedVMSS := compute.VirtualMachineScaleSet{ + expectedVMSS := &armcompute.VirtualMachineScaleSet{ Name: &name, - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - OrchestrationMode: compute.Uniform, + Properties: &armcompute.VirtualMachineScaleSetProperties{ + OrchestrationMode: to.Ptr(armcompute.OrchestrationModeUniform), ProvisioningState: ptr.To("Running"), - VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{ - OsProfile: &compute.VirtualMachineScaleSetOSProfile{ + VirtualMachineProfile: &armcompute.VirtualMachineScaleSetVMProfile{ + OSProfile: &armcompute.VirtualMachineScaleSetOSProfile{ ComputerNamePrefix: &namePrefix, }, - NetworkProfile: &compute.VirtualMachineScaleSetNetworkProfile{ - NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{ + NetworkProfile: &armcompute.VirtualMachineScaleSetNetworkProfile{ + NetworkInterfaceConfigurations: []*armcompute.VirtualMachineScaleSetNetworkConfiguration{ { - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ Primary: ptr.To(true), - IPConfigurations: &ipConfig, + IPConfigurations: ipConfig, }, }, }, @@ -144,13 +146,13 @@ func buildTestVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []string, ipv return expectedVMSS } -func buildTestVMSS(name, computerNamePrefix string) compute.VirtualMachineScaleSet { - return compute.VirtualMachineScaleSet{ +func buildTestVMSS(name, computerNamePrefix string) *armcompute.VirtualMachineScaleSet { + return &armcompute.VirtualMachineScaleSet{ Name: &name, - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - OrchestrationMode: compute.Uniform, - VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{ - OsProfile: &compute.VirtualMachineScaleSetOSProfile{ + Properties: &armcompute.VirtualMachineScaleSetProperties{ + OrchestrationMode: to.Ptr(armcompute.OrchestrationModeUniform), + VirtualMachineProfile: &armcompute.VirtualMachineScaleSetVMProfile{ + OSProfile: &armcompute.VirtualMachineScaleSetOSProfile{ ComputerNamePrefix: &computerNamePrefix, }, }, @@ -158,10 +160,10 @@ func buildTestVMSS(name, computerNamePrefix string) compute.VirtualMachineScaleS } } -func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomain int32, vmList []string, state string, isIPv6 bool) ([]compute.VirtualMachineScaleSetVM, network.Interface, network.PublicIPAddress) { - expectedVMSSVMs := make([]compute.VirtualMachineScaleSetVM, 0) - expectedInterface := network.Interface{} - expectedPIP := network.PublicIPAddress{} +func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomain int32, vmList []string, state string, isIPv6 bool) ([]*armcompute.VirtualMachineScaleSetVM, *armnetwork.Interface, *armnetwork.PublicIPAddress) { + expectedVMSSVMs := make([]*armcompute.VirtualMachineScaleSetVM, 0) + expectedInterface := &armnetwork.Interface{} + expectedPIP := &armnetwork.PublicIPAddress{} for i := range vmList { nodeName := vmList[i] @@ -172,60 +174,59 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai publicAddressID := fmt.Sprintf("/subscriptions/script/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/%s/virtualMachines/%d/networkInterfaces/%s/ipConfigurations/ipconfig1/publicIPAddresses/%s", scaleSetName, i, nodeName, nodeName) // set vmss virtual machine. - networkInterfaces := []compute.NetworkInterfaceReference{ + networkInterfaces := []*armcompute.NetworkInterfaceReference{ { ID: &interfaceID, - NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ + Properties: &armcompute.NetworkInterfaceReferenceProperties{ Primary: ptr.To(true), }, }, } - ipConfigurations := []compute.VirtualMachineScaleSetIPConfiguration{ + ipConfigurations := []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("ipconfig1"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(true), - LoadBalancerBackendAddressPools: &[]compute.SubResource{{ID: ptr.To(testLBBackendpoolID0)}}, - PrivateIPAddressVersion: compute.IPv4, + LoadBalancerBackendAddressPools: []*armcompute.SubResource{{ID: ptr.To(testLBBackendpoolID0)}}, + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv4), }, }, } if isIPv6 { - ipConfigurations = append(ipConfigurations, compute.VirtualMachineScaleSetIPConfiguration{ + ipConfigurations = append(ipConfigurations, &armcompute.VirtualMachineScaleSetIPConfiguration{ Name: ptr.To("ipconfigv6"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(false), - LoadBalancerBackendAddressPools: &[]compute.SubResource{{ID: ptr.To(testLBBackendpoolID0v6)}}, - PrivateIPAddressVersion: compute.IPv6, + LoadBalancerBackendAddressPools: []*armcompute.SubResource{{ID: ptr.To(testLBBackendpoolID0v6)}}, + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv6), }, }) } - networkConfigurations := []compute.VirtualMachineScaleSetNetworkConfiguration{ + networkConfigurations := []*armcompute.VirtualMachineScaleSetNetworkConfiguration{ { Name: ptr.To("vmss-nic"), - ID: ptr.To("fakeNetworkConfiguration"), - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &ipConfigurations, + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: ipConfigurations, Primary: ptr.To(true), }, }, } - vmssVM := compute.VirtualMachineScaleSetVM{ - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ + vmssVM := &armcompute.VirtualMachineScaleSetVM{ + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ ProvisioningState: ptr.To(state), - OsProfile: &compute.OSProfile{ + OSProfile: &armcompute.OSProfile{ ComputerName: &nodeName, }, - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &networkInterfaces, + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: networkInterfaces, }, - NetworkProfileConfiguration: &compute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ - NetworkInterfaceConfigurations: &networkConfigurations, + NetworkProfileConfiguration: &armcompute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ + NetworkInterfaceConfigurations: networkConfigurations, }, - InstanceView: &compute.VirtualMachineScaleSetVMInstanceView{ + InstanceView: &armcompute.VirtualMachineScaleSetVMInstanceView{ PlatformFaultDomain: &faultDomain, - Statuses: &[]compute.InstanceViewStatus{ + Statuses: []*armcompute.InstanceViewStatus{ {Code: ptr.To(testVMPowerState)}, }, }, @@ -234,24 +235,24 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai InstanceID: &instanceID, Name: &vmName, Location: &ss.Location, - Sku: &compute.Sku{Name: ptr.To("sku")}, + SKU: &armcompute.SKU{Name: ptr.To("SKU")}, } if zone != "" { - zones := []string{zone} - vmssVM.Zones = &zones + zones := []*string{&zone} + vmssVM.Zones = zones } // set interfaces. - expectedInterface = network.Interface{ + expectedInterface = &armnetwork.Interface{ Name: ptr.To("nic"), ID: &interfaceID, - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - IPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.InterfacePropertiesFormat{ + IPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ Primary: ptr.To(true), PrivateIPAddress: ptr.To(fakePrivateIP), - PublicIPAddress: &network.PublicIPAddress{ + PublicIPAddress: &armnetwork.PublicIPAddress{ ID: ptr.To(publicAddressID), }, }, @@ -261,9 +262,9 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai } // set public IPs. - expectedPIP = network.PublicIPAddress{ + expectedPIP = &armnetwork.PublicIPAddress{ ID: ptr.To(publicAddressID), - PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ IPAddress: ptr.To(fakePublicIP), }, } @@ -354,19 +355,17 @@ func TestGetNodeIdentityByNodeName(t *testing.T) { ss, err := NewTestScaleSet(ctrl) assert.NoError(t, err, test.description) - mockVMSSClient := mockvmssclient.NewMockInterface(ctrl) - mockVMSSVMClient := mockvmssvmclient.NewMockInterface(ctrl) - ss.VirtualMachineScaleSetsClient = mockVMSSClient - ss.VirtualMachineScaleSetVMsClient = mockVMSSVMClient + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) expectedScaleSet := buildTestVMSS(test.scaleSet, test.computerName) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() expectedVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, test.scaleSet, "", 0, test.vmList, "", false) - mockVMSSVMClient.EXPECT().List(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() + mockVMSSVMClient.EXPECT().List(gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() - mockVMsClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachine{}, nil).AnyTimes() + mockVMsClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() nodeID, err := ss.getNodeIdentityByNodeName(context.TODO(), test.nodeName, azcache.CacheReadTypeDefault) if test.expectError { @@ -380,8 +379,6 @@ func TestGetNodeIdentityByNodeName(t *testing.T) { } func TestGetInstanceIDByNodeName(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string @@ -415,38 +412,37 @@ func TestGetInstanceIDByNodeName(t *testing.T) { } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, test.description) + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, test.description) - mockVMSSClient := mockvmssclient.NewMockInterface(ctrl) - mockVMSSVMClient := mockvmssvmclient.NewMockInterface(ctrl) - ss.VirtualMachineScaleSetsClient = mockVMSSClient - ss.VirtualMachineScaleSetVMsClient = mockVMSSVMClient + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) - expectedScaleSet := buildTestVMSS(test.scaleSet, "vmssee6c2") - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() + expectedScaleSet := buildTestVMSS(test.scaleSet, "vmssee6c2") + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() - expectedVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, test.scaleSet, "", 0, test.vmList, "", false) - mockVMSSVMClient.EXPECT().List(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() + expectedVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, test.scaleSet, "", 0, test.vmList, "", false) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() - mockVMsClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachine{}, nil).AnyTimes() + mockVMsClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() - realValue, err := ss.GetInstanceIDByNodeName(context.Background(), test.nodeName) - if test.expectError { - assert.Error(t, err, test.description) - continue - } - - assert.NoError(t, err, test.description) - assert.Equal(t, test.expected, realValue, test.description) + realValue, err := ss.GetInstanceIDByNodeName(context.Background(), test.nodeName) + if test.expectError { + assert.Error(t, err, test.description) + } else { + assert.NoError(t, err, test.description) + assert.Equal(t, test.expected, realValue, test.description) + } + }) } } func TestGetZoneByNodeName(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - testCases := []struct { description string scaleSet string @@ -496,6 +492,7 @@ func TestGetZoneByNodeName(t *testing.T) { } for _, test := range testCases { + ctrl := gomock.NewController(t) cloud := GetTestCloud(ctrl) if test.location != "" { cloud.Location = test.location @@ -503,19 +500,15 @@ func TestGetZoneByNodeName(t *testing.T) { ss, err := NewTestScaleSet(ctrl) assert.NoError(t, err, test.description) - mockVMSSClient := mockvmssclient.NewMockInterface(ctrl) - mockVMSSVMClient := mockvmssvmclient.NewMockInterface(ctrl) - ss.VirtualMachineScaleSetsClient = mockVMSSClient - ss.VirtualMachineScaleSetVMsClient = mockVMSSVMClient - + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMsClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) expectedScaleSet := buildTestVMSS(test.scaleSet, "vmssee6c2") - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() expectedVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, test.scaleSet, test.zone, test.faultDomain, test.vmList, "", false) - mockVMSSVMClient.EXPECT().List(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() - - mockVMsClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachine{}, nil).AnyTimes() + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() + mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() realValue, err := ss.GetZoneByNodeName(context.TODO(), test.nodeName) if test.expectError { @@ -526,13 +519,11 @@ func TestGetZoneByNodeName(t *testing.T) { assert.NoError(t, err, test.description) assert.Equal(t, test.expected, realValue.FailureDomain, test.description) assert.Equal(t, strings.ToLower(cloud.Location), realValue.Region, test.description) + ctrl.Finish() } } func TestGetIPByNodeName(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - testCases := []struct { description string scaleSet string @@ -558,43 +549,42 @@ func TestGetIPByNodeName(t *testing.T) { } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, test.description) - - mockVMSSClient := mockvmssclient.NewMockInterface(ctrl) - mockVMSSVMClient := mockvmssvmclient.NewMockInterface(ctrl) - mockInterfaceClient := mockinterfaceclient.NewMockInterface(ctrl) - mockPIPClient := mockpublicipclient.NewMockInterface(ctrl) - ss.VirtualMachineScaleSetsClient = mockVMSSClient - ss.VirtualMachineScaleSetVMsClient = mockVMSSVMClient - ss.InterfacesClient = mockInterfaceClient - ss.PublicIPAddressesClient = mockPIPClient - - expectedScaleSet := buildTestVMSS(test.scaleSet, "vmssee6c2") - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() - - expectedVMs, expectedInterface, expectedPIP := buildTestVirtualMachineEnv(ss.Cloud, test.scaleSet, "", 0, test.vmList, "", false) - mockVMSSVMClient.EXPECT().List(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() - mockInterfaceClient.EXPECT().GetVirtualMachineScaleSetNetworkInterface(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedInterface, nil).AnyTimes() - mockPIPClient.EXPECT().GetVirtualMachineScaleSetPublicIPAddress(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedPIP, nil).AnyTimes() - - mockVMsClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachine{}, nil).AnyTimes() + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, test.description) - privateIP, publicIP, err := ss.GetIPByNodeName(context.Background(), test.nodeName) - if test.expectError { - assert.Error(t, err, test.description) - continue - } + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMsClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockInterfaceClient := ss.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) + mockPIPClient := ss.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + + expectedScaleSet := buildTestVMSS(test.scaleSet, "vmssee6c2") + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() + + expectedVMs, expectedInterface, expectedPIP := buildTestVirtualMachineEnv(ss.Cloud, test.scaleSet, "", 0, test.vmList, "", false) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() + mockInterfaceClient.EXPECT().GetVirtualMachineScaleSetNetworkInterface(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedInterface, nil).AnyTimes() + mockPIPClient.EXPECT().GetVirtualMachineScaleSetPublicIPAddress(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return( + armnetwork.PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressResponse{PublicIPAddress: *expectedPIP}, nil).AnyTimes() + mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() + + privateIP, publicIP, err := ss.GetIPByNodeName(context.Background(), test.nodeName) + if test.expectError { + assert.Error(t, err, test.description) + return + } - assert.NoError(t, err, test.description) - assert.Equal(t, test.expected, []string{privateIP, publicIP}, test.description) + assert.NoError(t, err, test.description) + assert.Equal(t, test.expected, []string{privateIP, publicIP}, test.description) + }) } } func TestGetNodeNameByIPConfigurationID(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() ipConfigurationIDTemplate := "/subscriptions/script/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/%s/virtualMachines/%s/networkInterfaces/%s/ipConfigurations/ipconfig1" @@ -632,32 +622,34 @@ func TestGetNodeNameByIPConfigurationID(t *testing.T) { } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, test.description) + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, test.description) - mockVMSSClient := mockvmssclient.NewMockInterface(ctrl) - mockVMSSVMClient := mockvmssvmclient.NewMockInterface(ctrl) - ss.VirtualMachineScaleSetsClient = mockVMSSClient - ss.VirtualMachineScaleSetVMsClient = mockVMSSVMClient + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMsClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + expectedScaleSet := buildTestVMSS(test.scaleSet, "vmssee6c2") + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() - expectedScaleSet := buildTestVMSS(test.scaleSet, "vmssee6c2") - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() + expectedVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, test.scaleSet, "", 0, test.vmList, "", false) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() - expectedVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, test.scaleSet, "", 0, test.vmList, "", false) - mockVMSSVMClient.EXPECT().List(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(expectedVMs, nil).AnyTimes() - - mockVMsClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachine{}, nil).AnyTimes() + mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() - nodeName, scalesetName, err := ss.GetNodeNameByIPConfigurationID(context.TODO(), test.ipConfigurationID) - if test.expectError { - assert.Error(t, err, test.description) - continue - } + nodeName, scalesetName, err := ss.GetNodeNameByIPConfigurationID(context.TODO(), test.ipConfigurationID) + if test.expectError { + assert.Error(t, err, test.description) + return + } - assert.NoError(t, err, test.description) - assert.Equal(t, test.expectedNodeName, nodeName, test.description) - assert.Equal(t, test.expectedScaleSetName, scalesetName, test.description) + assert.NoError(t, err, test.description) + assert.Equal(t, test.expectedNodeName, nodeName, test.description) + assert.Equal(t, test.expectedScaleSetName, scalesetName, test.description) + }) } } @@ -707,7 +699,7 @@ func TestGetVMSS(t *testing.T) { description string existedVMSSName string vmssName string - vmssListError *retry.Error + vmssListError error expectedErr error }{ { @@ -725,8 +717,8 @@ func TestGetVMSS(t *testing.T) { description: "getVMSS should report an error if there's something wrong during an api call", existedVMSSName: "vmss-1", vmssName: "vmss-1", - vmssListError: &retry.Error{RawError: fmt.Errorf("error during vmss list")}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: error during vmss list"), + vmssListError: &azcore.ResponseError{ErrorCode: "error during vmss list"}, + expectedErr: fmt.Errorf("error during vmss list"), }, } @@ -734,30 +726,27 @@ func TestGetVMSS(t *testing.T) { ss, err := NewTestScaleSet(ctrl) assert.NoError(t, err, test.description) - mockVMSSClient := mockvmssclient.NewMockInterface(ctrl) - ss.VirtualMachineScaleSetsClient = mockVMSSClient + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) - expected := compute.VirtualMachineScaleSet{ + expected := &armcompute.VirtualMachineScaleSet{ Name: ptr.To(test.existedVMSSName), - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{}, + Properties: &armcompute.VirtualMachineScaleSetProperties{ + VirtualMachineProfile: &armcompute.VirtualMachineScaleSetVMProfile{}, }, } - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{expected}, test.vmssListError).AnyTimes() + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachineScaleSet{expected}, test.vmssListError).AnyTimes() actual, err := ss.getVMSS(context.TODO(), test.vmssName, azcache.CacheReadTypeDefault) if test.expectedErr != nil { - assert.EqualError(t, test.expectedErr, err.Error(), test.description) + assert.Contains(t, err.Error(), test.expectedErr.Error(), test.description) } if actual != nil { - assert.Equal(t, expected, *actual, test.description) + assert.Equal(t, *expected, *actual, test.description) } } } func TestGetVmssVM(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string @@ -782,35 +771,37 @@ func TestGetVmssVM(t *testing.T) { } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, test.description) + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, test.description) - expectedVMSS := buildTestVMSS(test.existedVMSSName, "vmss-vm-") - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + expectedVMSS := buildTestVMSS(test.existedVMSSName, "vmss-vm-") + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, test.existedVMSSName, "", 0, test.existedNodeNames, "", false) - var expectedVMSSVM compute.VirtualMachineScaleSetVM - for _, expected := range expectedVMSSVMs { - if strings.EqualFold(*expected.OsProfile.ComputerName, test.nodeName) { - expectedVMSSVM = expected + expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, test.existedVMSSName, "", 0, test.existedNodeNames, "", false) + var expectedVMSSVM armcompute.VirtualMachineScaleSetVM + for _, expected := range expectedVMSSVMs { + if strings.EqualFold(*expected.Properties.OSProfile.ComputerName, test.nodeName) { + expectedVMSSVM = *expected + } } - } - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, test.existedVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, test.existedVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() - vmssVM, err := ss.getVmssVM(context.TODO(), test.nodeName, azcache.CacheReadTypeDefault) - if vmssVM != nil { - assert.Equal(t, expectedVMSSVM, *vmssVM.AsVirtualMachineScaleSetVM(), test.description) - } - assert.Equal(t, test.expectedError, err, test.description) + vmssVM, err := ss.getVmssVM(context.TODO(), test.nodeName, azcache.CacheReadTypeDefault) + if vmssVM != nil { + assert.Equal(t, expectedVMSSVM, *vmssVM.AsVirtualMachineScaleSetVM(), test.description) + } + assert.Equal(t, test.expectedError, err, test.description) + }) } } func TestGetPowerStatusByNodeName(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string @@ -825,7 +816,7 @@ func TestGetPowerStatusByNodeName(t *testing.T) { expectedPowerState: "Running", }, { - description: "GetPowerStatusByNodeName should return vmPowerStateUnknown when the vm.InstanceView.Statuses is nil", + description: "GetPowerStatusByNodeName should return vmPowerStateUnknown when the vm.Properties.InstanceView.Statuses is nil", vmList: []string{"vmss-vm-000001"}, nilStatus: true, expectedPowerState: consts.VMPowerStateUnknown, @@ -833,26 +824,32 @@ func TestGetPowerStatusByNodeName(t *testing.T) { } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test VMSS") + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test VMSS") - expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - if test.nilStatus { - expectedVMSSVMs[0].InstanceView.Statuses = nil - } - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - mockVMsClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachine{}, nil).AnyTimes() + expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + if test.nilStatus { + expectedVMSSVMs[0].Properties.InstanceView.Statuses = nil + } + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() - powerState, err := ss.GetPowerStatusByNodeName(context.TODO(), "vmss-vm-000001") - assert.Equal(t, test.expectedErr, err, test.description+errMsgSuffix) - assert.Equal(t, test.expectedPowerState, powerState, test.description) + mockVMsClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() + + powerState, err := ss.GetPowerStatusByNodeName(context.TODO(), "vmss-vm-000001") + assert.Equal(t, test.expectedErr, err, test.description+errMsgSuffix) + assert.Equal(t, test.expectedPowerState, powerState, test.description) + }) } } @@ -886,20 +883,20 @@ func TestGetProvisioningStateByNodeName(t *testing.T) { assert.NoError(t, err, "unexpected error when creating test VMSS") expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) if test.provisioningState != "" { - expectedVMSSVMs[0].ProvisioningState = ptr.To(test.provisioningState) + expectedVMSSVMs[0].Properties.ProvisioningState = ptr.To(test.provisioningState) } else { - expectedVMSSVMs[0].ProvisioningState = nil + expectedVMSSVMs[0].Properties.ProvisioningState = nil } - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() - mockVMsClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachine{}, nil).AnyTimes() + mockVMsClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() provisioningState, err := ss.GetProvisioningStateByNodeName(context.TODO(), "vmss-vm-000001") assert.Equal(t, test.expectedErr, err, test.description+errMsgSuffix) @@ -908,8 +905,6 @@ func TestGetProvisioningStateByNodeName(t *testing.T) { } func TestGetVmssVMByInstanceID(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string @@ -925,31 +920,34 @@ func TestGetVmssVMByInstanceID(t *testing.T) { } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test VMSS") + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test VMSS") - expectedVMSS := compute.VirtualMachineScaleSet{ - Name: ptr.To(testVMSSName), - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{}, - }, - } - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + expectedVMSS := &armcompute.VirtualMachineScaleSet{ + Name: ptr.To(testVMSSName), + Properties: &armcompute.VirtualMachineScaleSetProperties{ + VirtualMachineProfile: &armcompute.VirtualMachineScaleSetVMProfile{}, + }, + } + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() - vm, err := ss.getVmssVMByInstanceID(context.TODO(), ss.ResourceGroup, testVMSSName, test.instanceID, azcache.CacheReadTypeDefault) - assert.Equal(t, test.expectedErr, err, test.description+errMsgSuffix) - assert.Equal(t, expectedVMSSVMs[0], *vm, test.description) + vm, err := ss.getVmssVMByInstanceID(context.TODO(), ss.ResourceGroup, testVMSSName, test.instanceID, azcache.CacheReadTypeDefault) + assert.Equal(t, test.expectedErr, err, test.description+errMsgSuffix) + assert.Equal(t, *expectedVMSSVMs[0], *vm, test.description) + }) } } func TestGetVmssVMByNodeIdentity(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string @@ -973,22 +971,25 @@ func TestGetVmssVMByNodeIdentity(t *testing.T) { } for _, test := range testCases { + test := test t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() ss, err := NewTestScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test VMSS") - expectedVMSS := compute.VirtualMachineScaleSet{ + expectedVMSS := &armcompute.VirtualMachineScaleSet{ Name: ptr.To(testVMSSName), - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{}, + Properties: &armcompute.VirtualMachineScaleSetProperties{ + VirtualMachineProfile: &armcompute.VirtualMachineScaleSetVMProfile{}, }, } - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() cacheKey := getVMSSVMCacheKey(ss.ResourceGroup, testVMSSName) virtualMachines, err := ss.getVMSSVMsFromCache(context.TODO(), ss.ResourceGroup, testVMSSName, azcache.CacheReadTypeDefault) @@ -1006,7 +1007,7 @@ func TestGetVmssVMByNodeIdentity(t *testing.T) { node := nodeIdentity{ss.ResourceGroup, testVMSSName, test.vmList[i]} vm, err := ss.getVmssVMByNodeIdentity(context.TODO(), &node, azcache.CacheReadTypeDefault) assert.Equal(t, test.expectedErr, err) - assert.Equal(t, *virtualmachine.FromVirtualMachineScaleSetVM(&expectedVMSSVMs[i], virtualmachine.ByVMSS(testVMSSName)), *vm) + assert.Equal(t, *virtualmachine.FromVirtualMachineScaleSetVM(expectedVMSSVMs[i], virtualmachine.ByVMSS(testVMSSName)), *vm) } for i := 0; i < len(test.goneVMList); i++ { node := nodeIdentity{ss.ResourceGroup, testVMSSName, test.goneVMList[i]} @@ -1026,50 +1027,53 @@ func TestGetVmssVMByNodeIdentity(t *testing.T) { } func TestGetInstanceTypeByNodeName(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string vmList []string - vmClientErr *retry.Error + vmClientErr error expectedType string expectedErr error }{ { description: "GetInstanceTypeByNodeName should return the correct instance type", vmList: []string{"vmss-vm-000000"}, - expectedType: "sku", + expectedType: "SKU", }, { description: "GetInstanceTypeByNodeName should report the error that occurs", vmList: []string{"vmss-vm-000000"}, - vmClientErr: &retry.Error{RawError: fmt.Errorf("error")}, + vmClientErr: &azcore.ResponseError{ErrorCode: "error"}, expectedType: "", - expectedErr: fmt.Errorf("getter function of nonVmssUniformNodesCache: failed to list vms in the resource group rg: Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: error"), + expectedErr: fmt.Errorf("error"), }, } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test VMSS") + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test VMSS") - expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() - mockVMClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, test.vmClientErr).AnyTimes() + mockVMClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, test.vmClientErr).AnyTimes() - sku, err := ss.GetInstanceTypeByNodeName(context.Background(), "vmss-vm-000000") - if test.expectedErr != nil { - assert.EqualError(t, err, test.expectedErr.Error(), test.description) - } - assert.Equal(t, test.expectedType, sku, test.description) + SKU, err := ss.GetInstanceTypeByNodeName(context.Background(), "vmss-vm-000000") + if test.expectedErr != nil { + assert.Contains(t, err.Error(), test.expectedErr.Error(), test.description) + } + assert.Equal(t, test.expectedType, SKU, test.description) + }) } } @@ -1079,16 +1083,16 @@ func TestGetPrimaryInterfaceID(t *testing.T) { testCases := []struct { description string - existedInterfaces []compute.NetworkInterfaceReference + existedInterfaces []*armcompute.NetworkInterfaceReference expectedID string expectedErr error }{ { description: "GetPrimaryInterfaceID should return the ID of the primary NIC on the VMSS VM", - existedInterfaces: []compute.NetworkInterfaceReference{ + existedInterfaces: []*armcompute.NetworkInterfaceReference{ { ID: ptr.To("1"), - NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ + Properties: &armcompute.NetworkInterfaceReferenceProperties{ Primary: ptr.To(true), }, }, @@ -1098,16 +1102,16 @@ func TestGetPrimaryInterfaceID(t *testing.T) { }, { description: "GetPrimaryInterfaceID should report an error if there's no primary NIC on the VMSS VM", - existedInterfaces: []compute.NetworkInterfaceReference{ + existedInterfaces: []*armcompute.NetworkInterfaceReference{ { ID: ptr.To("1"), - NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ + Properties: &armcompute.NetworkInterfaceReferenceProperties{ Primary: ptr.To(false), }, }, { ID: ptr.To("2"), - NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ + Properties: &armcompute.NetworkInterfaceReferenceProperties{ Primary: ptr.To(false), }, }, @@ -1116,7 +1120,7 @@ func TestGetPrimaryInterfaceID(t *testing.T) { }, { description: "GetPrimaryInterfaceID should report an error if there's no network interface on the VMSS VM", - existedInterfaces: []compute.NetworkInterfaceReference{}, + existedInterfaces: []*armcompute.NetworkInterfaceReference{}, expectedErr: fmt.Errorf("failed to find the network interfaces for vm vm"), }, } @@ -1126,16 +1130,16 @@ func TestGetPrimaryInterfaceID(t *testing.T) { assert.NoError(t, err, "unexpected error when creating test VMSS") existedInterfaces := test.existedInterfaces - vm := compute.VirtualMachineScaleSetVM{ + vm := armcompute.VirtualMachineScaleSetVM{ Name: ptr.To("vm"), - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &existedInterfaces, + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: existedInterfaces, }, }, } if len(test.existedInterfaces) == 0 { - vm.VirtualMachineScaleSetVMProperties.NetworkProfile = nil + vm.Properties.NetworkProfile = nil } id, err := ss.getPrimaryInterfaceID(virtualmachine.FromVirtualMachineScaleSetVM(&vm, virtualmachine.ByVMSS("vmss"))) @@ -1145,16 +1149,14 @@ func TestGetPrimaryInterfaceID(t *testing.T) { } func TestGetPrimaryInterface(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string nodeName string vmList []string - vmClientErr *retry.Error - vmssClientErr *retry.Error - nicClientErr *retry.Error + vmClientErr error + vmssClientErr error + nicClientErr error hasPrimaryInterface bool isInvalidNICID bool expectedErr error @@ -1170,16 +1172,16 @@ func TestGetPrimaryInterface(t *testing.T) { nodeName: "vmss-vm-000000", vmList: []string{"vmss-vm-000000"}, hasPrimaryInterface: true, - vmClientErr: &retry.Error{RawError: fmt.Errorf("error")}, - expectedErr: fmt.Errorf("getter function of nonVmssUniformNodesCache: failed to list vms in the resource group rg: Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: error"), + vmClientErr: &azcore.ResponseError{ErrorCode: "error"}, + expectedErr: fmt.Errorf("error"), }, { description: "GetPrimaryInterface should report the error if vmss client returns retry error", nodeName: "vmss-vm-000000", vmList: []string{"vmss-vm-000000"}, hasPrimaryInterface: true, - vmssClientErr: &retry.Error{RawError: fmt.Errorf("error")}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: error"), + vmssClientErr: &azcore.ResponseError{ErrorCode: "error"}, + expectedErr: fmt.Errorf("error"), }, { description: "GetPrimaryInterface should report the error if there is no primary interface", @@ -1201,60 +1203,66 @@ func TestGetPrimaryInterface(t *testing.T) { nodeName: "vmss-vm-000000", vmList: []string{"vmss-vm-000000"}, hasPrimaryInterface: true, - nicClientErr: &retry.Error{RawError: fmt.Errorf("error")}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: error"), + nicClientErr: &azcore.ResponseError{ErrorCode: "error"}, + expectedErr: fmt.Errorf("error"), }, { description: "GetPrimaryInterface should report the error if the NIC instance is not found", nodeName: "vmss-vm-000000", vmList: []string{"vmss-vm-000000"}, hasPrimaryInterface: true, - nicClientErr: &retry.Error{HTTPStatusCode: 404, RawError: fmt.Errorf("not found")}, + nicClientErr: &azcore.ResponseError{StatusCode: 404, ErrorCode: "not found"}, expectedErr: cloudprovider.InstanceNotFound, }, } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test VMSS") + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test VMSS") - expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, test.vmssClientErr).AnyTimes() - - expectedVMSSVMs, expectedInterface, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) - if !test.hasPrimaryInterface { - networkInterfaces := *expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces - networkInterfaces[0].Primary = ptr.To(false) - networkInterfaces = append(networkInterfaces, compute.NetworkInterfaceReference{ - NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{Primary: ptr.To(false)}, - }) - expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces = &networkInterfaces - } - if test.isInvalidNICID { - networkInterfaces := *expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces - networkInterfaces[0].ID = ptr.To("invalid/id/") - expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces = &networkInterfaces - } - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, test.vmssClientErr).AnyTimes() + + expectedVMSSVMs, expectedInterface, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) + if !test.hasPrimaryInterface { + networkInterfaces := expectedVMSSVMs[0].Properties.NetworkProfile.NetworkInterfaces + networkInterfaces[0].Properties.Primary = ptr.To(false) + networkInterfaces = append(networkInterfaces, &armcompute.NetworkInterfaceReference{ + Properties: &armcompute.NetworkInterfaceReferenceProperties{Primary: ptr.To(false)}, + }) + expectedVMSSVMs[0].Properties.NetworkProfile.NetworkInterfaces = networkInterfaces + } + if test.isInvalidNICID { + networkInterfaces := expectedVMSSVMs[0].Properties.NetworkProfile.NetworkInterfaces + networkInterfaces[0].ID = ptr.To("invalid/id/") + expectedVMSSVMs[0].Properties.NetworkProfile.NetworkInterfaces = networkInterfaces + } + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() - mockVMClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, test.vmClientErr).AnyTimes() + mockVMClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, test.vmClientErr).AnyTimes() - mockInterfaceClient := ss.InterfacesClient.(*mockinterfaceclient.MockInterface) - mockInterfaceClient.EXPECT().GetVirtualMachineScaleSetNetworkInterface(gomock.Any(), ss.ResourceGroup, testVMSSName, "0", test.nodeName, gomock.Any()).Return(expectedInterface, test.nicClientErr).AnyTimes() - expectedInterface.Location = &ss.Location + mockInterfaceClient := ss.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) + mockInterfaceClient.EXPECT().GetVirtualMachineScaleSetNetworkInterface(gomock.Any(), ss.ResourceGroup, testVMSSName, "0", test.nodeName).Return(expectedInterface, test.nicClientErr).AnyTimes() + expectedInterface.Location = &ss.Location - if test.vmClientErr != nil || test.vmssClientErr != nil || test.nicClientErr != nil || !test.hasPrimaryInterface || test.isInvalidNICID { - expectedInterface = network.Interface{} - } + if test.vmClientErr != nil || test.vmssClientErr != nil || test.nicClientErr != nil || !test.hasPrimaryInterface || test.isInvalidNICID { + expectedInterface = &armnetwork.Interface{} + } - nic, err := ss.GetPrimaryInterface(context.Background(), test.nodeName) - if test.expectedErr != nil { - assert.EqualError(t, err, test.expectedErr.Error(), test.description) - } - assert.Equal(t, expectedInterface, nic, test.description) + nic, err := ss.GetPrimaryInterface(context.Background(), test.nodeName) + if test.expectedErr != nil { + assert.Contains(t, err.Error(), test.expectedErr.Error(), test.description) + } else { + assert.Equal(t, expectedInterface, nic, test.description) + } + }) } } @@ -1264,7 +1272,7 @@ func TestGetVMSSPublicIPAddress(t *testing.T) { testCases := []struct { description string - pipClientErr *retry.Error + pipClientErr error pipName string found bool expectedErr error @@ -1278,8 +1286,8 @@ func TestGetVMSSPublicIPAddress(t *testing.T) { description: "GetVMSSPublicIPAddress should report the error if the pip client returns retry.Error", pipName: "pip", found: false, - pipClientErr: &retry.Error{RawError: fmt.Errorf("error")}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: error"), + pipClientErr: &azcore.ResponseError{ErrorCode: "error"}, + expectedErr: fmt.Errorf("error"), }, { description: "GetVMSSPublicIPAddress should not report errors if the pip cannot be found", @@ -1292,28 +1300,26 @@ func TestGetVMSSPublicIPAddress(t *testing.T) { ss, err := NewTestScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test VMSS") - mockPIPClient := ss.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) - mockPIPClient.EXPECT().GetVirtualMachineScaleSetPublicIPAddress(gomock.Any(), ss.ResourceGroup, testVMSSName, "0", "nic", "ip", "pip", "").Return(network.PublicIPAddress{}, test.pipClientErr).AnyTimes() - mockPIPClient.EXPECT().GetVirtualMachineScaleSetPublicIPAddress(gomock.Any(), ss.ResourceGroup, testVMSSName, "0", "nic", "ip", gomock.Not("pip"), "").Return(network.PublicIPAddress{}, &retry.Error{HTTPStatusCode: 404, RawError: fmt.Errorf("not found")}).AnyTimes() + mockPIPClient := ss.NetworkClientFactory.GetPublicIPAddressClient().(*mock_publicipaddressclient.MockInterface) + mockPIPClient.EXPECT().GetVirtualMachineScaleSetPublicIPAddress(gomock.Any(), ss.ResourceGroup, testVMSSName, "0", "nic", "ip", "pip", nil).Return(armnetwork.PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressResponse{}, test.pipClientErr).AnyTimes() + mockPIPClient.EXPECT().GetVirtualMachineScaleSetPublicIPAddress(gomock.Any(), ss.ResourceGroup, testVMSSName, "0", "nic", "ip", gomock.Not("pip"), nil).Return(armnetwork.PublicIPAddressesClientGetVirtualMachineScaleSetPublicIPAddressResponse{}, &azcore.ResponseError{StatusCode: 404, ErrorCode: "not found"}).AnyTimes() _, found, err := ss.getVMSSPublicIPAddress(ss.ResourceGroup, testVMSSName, "0", "nic", "ip", test.pipName) if test.expectedErr != nil { - assert.EqualError(t, test.expectedErr, err.Error(), test.description+errMsgSuffix) + assert.Contains(t, err.Error(), test.expectedErr.Error(), test.description+errMsgSuffix) } assert.Equal(t, test.found, found, test.description) } } func TestGetPrivateIPsByNodeName(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string nodeName string vmList []string isNilIPConfigs bool - vmClientErr *retry.Error + vmClientErr error expectedPrivateIPs []string expectedErr error }{ @@ -1329,45 +1335,50 @@ func TestGetPrivateIPsByNodeName(t *testing.T) { vmList: []string{"vmss-vm-000000"}, isNilIPConfigs: true, expectedPrivateIPs: []string{}, - expectedErr: fmt.Errorf("nic.IPConfigurations for nic (nicname=\"nic\") is nil"), + expectedErr: fmt.Errorf("nic.Properties.IPConfigurations for nic (nicname=\"nic\") is nil"), }, { description: "GetPrivateIPsByNodeName should report the error if error happens during GetPrimaryInterface", nodeName: "vmss-vm-000000", vmList: []string{"vmss-vm-000000"}, - vmClientErr: &retry.Error{RawError: fmt.Errorf("error")}, + vmClientErr: &azcore.ResponseError{ErrorCode: "error"}, expectedPrivateIPs: []string{}, - expectedErr: fmt.Errorf("getter function of nonVmssUniformNodesCache: failed to list vms in the resource group rg: Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: error"), + expectedErr: fmt.Errorf("error"), }, } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test VMSS") + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test VMSS") - expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - expectedVMSSVMs, expectedInterface, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) + expectedVMSSVMs, expectedInterface, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() - mockVMClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, test.vmClientErr).AnyTimes() + mockVMClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, test.vmClientErr).AnyTimes() - if test.isNilIPConfigs { - expectedInterface.IPConfigurations = nil - } - mockInterfaceClient := ss.InterfacesClient.(*mockinterfaceclient.MockInterface) - mockInterfaceClient.EXPECT().GetVirtualMachineScaleSetNetworkInterface(gomock.Any(), ss.ResourceGroup, testVMSSName, "0", test.nodeName, gomock.Any()).Return(expectedInterface, nil).AnyTimes() + if test.isNilIPConfigs { + expectedInterface.Properties.IPConfigurations = nil + } + mockInterfaceClient := ss.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) + mockInterfaceClient.EXPECT().GetVirtualMachineScaleSetNetworkInterface(gomock.Any(), ss.ResourceGroup, testVMSSName, "0", test.nodeName).Return(expectedInterface, nil).AnyTimes() - privateIPs, err := ss.GetPrivateIPsByNodeName(context.Background(), test.nodeName) - if test.expectedErr != nil { - assert.EqualError(t, err, test.expectedErr.Error(), test.description) - } - assert.Equal(t, test.expectedPrivateIPs, privateIPs, test.description) + privateIPs, err := ss.GetPrivateIPsByNodeName(context.Background(), test.nodeName) + if test.expectedErr != nil { + assert.Contains(t, err.Error(), test.expectedErr.Error(), test.description) + } + assert.Equal(t, test.expectedPrivateIPs, privateIPs, test.description) + }) } } @@ -1396,55 +1407,57 @@ func TestExtractResourceGroupByProviderID(t *testing.T) { } func TestListScaleSetVMs(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string - existedVMSSVMs []compute.VirtualMachineScaleSetVM - vmssVMClientErr *retry.Error + existedVMSSVMs []*armcompute.VirtualMachineScaleSetVM + vmssVMClientErr error expectedErr error }{ { description: "listScaleSetVMs should return the correct vmss vms", - existedVMSSVMs: []compute.VirtualMachineScaleSetVM{ + existedVMSSVMs: []*armcompute.VirtualMachineScaleSetVM{ {Name: ptr.To("vmss-vm-000000")}, {Name: ptr.To("vmss-vm-000001")}, }, }, { description: "listScaleSetVMs should report the error that the vmss vm client hits", - vmssVMClientErr: &retry.Error{RawError: fmt.Errorf("error")}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: error"), + vmssVMClientErr: &azcore.ResponseError{ErrorCode: "error"}, + expectedErr: fmt.Errorf("error"), }, } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test VMSS") + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(test.existedVMSSVMs, test.vmssVMClientErr).AnyTimes() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test VMSS") - expectedVMSSVMs := test.existedVMSSVMs + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(test.existedVMSSVMs, test.vmssVMClientErr).AnyTimes() - vmssVMs, err := ss.listScaleSetVMs(testVMSSName, ss.ResourceGroup) - if test.expectedErr != nil { - assert.EqualError(t, test.expectedErr, err.Error(), test.description+errMsgSuffix) - } - assert.Equal(t, expectedVMSSVMs, vmssVMs, test.description) + expectedVMSSVMs := test.existedVMSSVMs + + vmssVMs, err := ss.listScaleSetVMs(testVMSSName, ss.ResourceGroup) + if test.expectedErr != nil { + assert.Contains(t, err.Error(), test.expectedErr.Error(), test.description+errMsgSuffix) + } + assert.Equal(t, expectedVMSSVMs, vmssVMs, test.description) + }) } } func TestGetAgentPoolScaleSets(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string excludeLBNodes []string nodes []*v1.Node - expectedVMSSNames *[]string + expectedVMSSNames []string expectedErr error }{ { @@ -1469,7 +1482,7 @@ func TestGetAgentPoolScaleSets(t *testing.T) { }, }, }, - expectedVMSSNames: &[]string{"vmss"}, + expectedVMSSNames: []string{"vmss"}, }, { description: "getAgentPoolScaleSets should return the correct vmss names", @@ -1487,73 +1500,76 @@ func TestGetAgentPoolScaleSets(t *testing.T) { }, }, }, - expectedVMSSNames: &[]string{"vmss"}, + expectedVMSSNames: []string{"vmss"}, }, } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test VMSS") - ss.excludeLoadBalancerNodes = utilsets.NewString(test.excludeLBNodes...) + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test VMSS") + ss.excludeLoadBalancerNodes = utilsets.NewString(test.excludeLBNodes...) - expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - expectedVMSSVMs := []compute.VirtualMachineScaleSetVM{ - { - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000000")}, - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, + expectedVMSSVMs := []*armcompute.VirtualMachineScaleSetVM{ + { + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ + OSProfile: &armcompute.OSProfile{ComputerName: ptr.To("vmss-vm-000000")}, + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: []*armcompute.NetworkInterfaceReference{}, + }, }, }, - }, - { - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000001")}, - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, + { + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ + OSProfile: &armcompute.OSProfile{ComputerName: ptr.To("vmss-vm-000001")}, + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: []*armcompute.NetworkInterfaceReference{}, + }, }, }, - }, - { - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000002")}, - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, + { + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ + OSProfile: &armcompute.OSProfile{ComputerName: ptr.To("vmss-vm-000002")}, + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: []*armcompute.NetworkInterfaceReference{}, + }, }, }, - }, - } - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + } + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() - mockVMClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + mockVMClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - vmssNames, err := ss.getAgentPoolScaleSets(context.TODO(), test.nodes) - assert.Equal(t, test.expectedErr, err, test.description+errMsgSuffix) - assert.Equal(t, test.expectedVMSSNames, vmssNames) + vmssNames, err := ss.getAgentPoolScaleSets(context.TODO(), test.nodes) + assert.Equal(t, test.expectedErr, err, test.description+errMsgSuffix) + assert.Equal(t, test.expectedVMSSNames, vmssNames) + }) } } func TestGetVMSetNames(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string service *v1.Service nodes []*v1.Node useSingleSLB bool - expectedVMSetNames *[]string + expectedVMSetNames []*string expectedErr error }{ { description: "GetVMSetNames should return the primary vm set name if the service has no mode annotation", service: &v1.Service{}, - expectedVMSetNames: &[]string{"vmss"}, + expectedVMSetNames: to.SliceOfPtrs("vmss"), }, { description: "GetVMSetNames should return the primary vm set name when using the single SLB", @@ -1561,7 +1577,7 @@ func TestGetVMSetNames(t *testing.T) { ObjectMeta: metav1.ObjectMeta{Annotations: map[string]string{consts.ServiceAnnotationLoadBalancerMode: consts.ServiceAnnotationLoadBalancerAutoModeValue}}, }, useSingleSLB: true, - expectedVMSetNames: &[]string{"vmss"}, + expectedVMSetNames: to.SliceOfPtrs("vmss"), }, { description: "GetVMSetNames should return all scale sets if the service has auto mode annotation", @@ -1575,7 +1591,7 @@ func TestGetVMSetNames(t *testing.T) { }, }, }, - expectedVMSetNames: &[]string{"vmss"}, + expectedVMSetNames: to.SliceOfPtrs("vmss"), }, { description: "GetVMSetNames should report the error if there's no such vmss", @@ -1617,64 +1633,69 @@ func TestGetVMSetNames(t *testing.T) { }, }, }, - expectedVMSetNames: &[]string{"vmss"}, + expectedVMSetNames: to.SliceOfPtrs("vmss"), }, } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test VMSS") + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test VMSS") - if test.useSingleSLB { - ss.LoadBalancerSku = consts.LoadBalancerSkuStandard - } + if test.useSingleSLB { + ss.LoadBalancerSKU = consts.LoadBalancerSKUStandard + } - expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - expectedVMSSVMs := []compute.VirtualMachineScaleSetVM{ - { - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000000")}, - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, + expectedVMSSVMs := []*armcompute.VirtualMachineScaleSetVM{ + { + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ + OSProfile: &armcompute.OSProfile{ComputerName: ptr.To("vmss-vm-000000")}, + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: []*armcompute.NetworkInterfaceReference{}, + }, }, }, - }, - { - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000001")}, - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, + { + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ + OSProfile: &armcompute.OSProfile{ComputerName: ptr.To("vmss-vm-000001")}, + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: []*armcompute.NetworkInterfaceReference{}, + }, }, }, - }, - { - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000002")}, - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, + { + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ + OSProfile: &armcompute.OSProfile{ComputerName: ptr.To("vmss-vm-000002")}, + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: []*armcompute.NetworkInterfaceReference{}, + }, }, }, - }, - { - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000003")}, + { + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ + OSProfile: &armcompute.OSProfile{ComputerName: ptr.To("vmss-vm-000003")}, + }, }, - }, - } - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + } + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() - mockVMClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + mockVMClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() - vmSetNames, err := ss.GetVMSetNames(context.TODO(), test.service, test.nodes) - if test.expectedErr != nil { - assert.True(t, errors.Is(err, test.expectedErr), "expected error %v, got %v", test.expectedErr, err) - } - assert.Equal(t, test.expectedVMSetNames, vmSetNames, test.description) + vmSetNames, err := ss.GetVMSetNames(context.TODO(), test.service, test.nodes) + if test.expectedErr != nil { + assert.True(t, errors.Is(err, test.expectedErr), "expected error %v, got %v", test.expectedErr, err) + } + assert.Equal(t, test.expectedVMSetNames, vmSetNames, test.description) + }) } } @@ -1682,41 +1703,41 @@ func TestGetPrimaryNetworkInterfaceConfiguration(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - networkConfigs := []compute.VirtualMachineScaleSetNetworkConfiguration{ + networkConfigs := []*armcompute.VirtualMachineScaleSetNetworkConfiguration{ {Name: ptr.To("config-0")}, } config, err := getPrimaryNetworkInterfaceConfiguration(networkConfigs, testVMSSName) assert.Nil(t, err, "getPrimaryNetworkInterfaceConfiguration should return the correct network config") - assert.Equal(t, &networkConfigs[0], config, "getPrimaryNetworkInterfaceConfiguration should return the correct network config") + assert.Equal(t, networkConfigs[0], config, "getPrimaryNetworkInterfaceConfiguration should return the correct network config") - networkConfigs = []compute.VirtualMachineScaleSetNetworkConfiguration{ + networkConfigs = []*armcompute.VirtualMachineScaleSetNetworkConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ Primary: ptr.To(false), }, }, { Name: ptr.To("config-1"), - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ Primary: ptr.To(true), }, }, } config, err = getPrimaryNetworkInterfaceConfiguration(networkConfigs, testVMSSName) assert.Nil(t, err, "getPrimaryNetworkInterfaceConfiguration should return the correct network config") - assert.Equal(t, &networkConfigs[1], config, "getPrimaryNetworkInterfaceConfiguration should return the correct network config") + assert.Equal(t, networkConfigs[1], config, "getPrimaryNetworkInterfaceConfiguration should return the correct network config") - networkConfigs = []compute.VirtualMachineScaleSetNetworkConfiguration{ + networkConfigs = []*armcompute.VirtualMachineScaleSetNetworkConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ Primary: ptr.To(false), }, }, { Name: ptr.To("config-1"), - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ Primary: ptr.To(false), }, }, @@ -1729,16 +1750,16 @@ func TestGetPrimaryNetworkInterfaceConfiguration(t *testing.T) { func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) { testcases := []struct { desc string - netConfig *compute.VirtualMachineScaleSetNetworkConfiguration + netConfig *armcompute.VirtualMachineScaleSetNetworkConfiguration backendPoolID string - expectedIPConfig *compute.VirtualMachineScaleSetIPConfiguration + expectedIPConfig *armcompute.VirtualMachineScaleSetIPConfiguration expectedErr error }{ { desc: "only one IPv4 without primary (should not exist)", - netConfig: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + netConfig: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), }, @@ -1746,24 +1767,24 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) { }, }, backendPoolID: testLBBackendpoolID0, - expectedIPConfig: &compute.VirtualMachineScaleSetIPConfiguration{ + expectedIPConfig: &armcompute.VirtualMachineScaleSetIPConfiguration{ Name: ptr.To("config-0"), }, }, { desc: "two IPv4 but one with primary", - netConfig: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + netConfig: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(false), }, }, { Name: ptr.To("config-1"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(true), }, }, @@ -1771,27 +1792,27 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) { }, }, backendPoolID: testLBBackendpoolID0, - expectedIPConfig: &compute.VirtualMachineScaleSetIPConfiguration{ + expectedIPConfig: &armcompute.VirtualMachineScaleSetIPConfiguration{ Name: ptr.To("config-1"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(true), }, }, }, { desc: "multiple IPv4 without primary", - netConfig: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + netConfig: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(false), }, }, { Name: ptr.To("config-1"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(false), }, }, @@ -1803,60 +1824,60 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) { }, { desc: "dualstack for IPv4", - netConfig: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + netConfig: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - PrivateIPAddressVersion: compute.IPv4, + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv4), Primary: ptr.To(true), }, }, { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - PrivateIPAddressVersion: compute.IPv6, + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv6), }, }, }, }, }, backendPoolID: testLBBackendpoolID0, - expectedIPConfig: &compute.VirtualMachineScaleSetIPConfiguration{ + expectedIPConfig: &armcompute.VirtualMachineScaleSetIPConfiguration{ Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - PrivateIPAddressVersion: compute.IPv4, + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv4), Primary: ptr.To(true), }, }, }, { desc: "dualstack for IPv6", - netConfig: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + netConfig: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - PrivateIPAddressVersion: compute.IPv4, + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv4), Primary: ptr.To(true), }, }, { Name: ptr.To("config-0-IPv6"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - PrivateIPAddressVersion: compute.IPv6, + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv6), }, }, }, }, }, backendPoolID: testLBBackendpoolID0v6, - expectedIPConfig: &compute.VirtualMachineScaleSetIPConfiguration{ + expectedIPConfig: &armcompute.VirtualMachineScaleSetIPConfiguration{ Name: ptr.To("config-0-IPv6"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - PrivateIPAddressVersion: compute.IPv6, + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv6), }, }, }, @@ -1875,22 +1896,22 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { testcases := []struct { desc string backendPoolID string - primaryNIC *compute.VirtualMachineScaleSetNetworkConfiguration - expectedPrimaryNIC *compute.VirtualMachineScaleSetNetworkConfiguration + primaryNIC *armcompute.VirtualMachineScaleSetNetworkConfiguration + expectedPrimaryNIC *armcompute.VirtualMachineScaleSetNetworkConfiguration expectedFound bool expectedErr error }{ { desc: "delete backend pool from ip config", backendPoolID: "backendpool-0", - primaryNIC: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + primaryNIC: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(true), - LoadBalancerBackendAddressPools: &[]compute.SubResource{ + LoadBalancerBackendAddressPools: []*armcompute.SubResource{ { ID: ptr.To("backendpool-0"), }, @@ -1903,14 +1924,14 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { }, }, }, - expectedPrimaryNIC: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + expectedPrimaryNIC: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(true), - LoadBalancerBackendAddressPools: &[]compute.SubResource{ + LoadBalancerBackendAddressPools: []*armcompute.SubResource{ { ID: ptr.To("backendpool-1"), }, @@ -1925,14 +1946,14 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { { desc: "backend pool not found", backendPoolID: "backendpool-0", - primaryNIC: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + primaryNIC: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(true), - LoadBalancerBackendAddressPools: &[]compute.SubResource{ + LoadBalancerBackendAddressPools: []*armcompute.SubResource{ { ID: ptr.To("backendpool-1"), }, @@ -1942,14 +1963,14 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { }, }, }, - expectedPrimaryNIC: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + expectedPrimaryNIC: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(true), - LoadBalancerBackendAddressPools: &[]compute.SubResource{ + LoadBalancerBackendAddressPools: []*armcompute.SubResource{ { ID: ptr.To("backendpool-1"), }, @@ -1964,14 +1985,14 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { { desc: "delete backend pool from ip config IPv6", backendPoolID: "backendpool-0-IPv6", - primaryNIC: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + primaryNIC: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(true), - LoadBalancerBackendAddressPools: &[]compute.SubResource{ + LoadBalancerBackendAddressPools: []*armcompute.SubResource{ { ID: ptr.To("backendpool-1"), }, @@ -1980,27 +2001,27 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { }, { Name: ptr.To("config-1"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(false), - LoadBalancerBackendAddressPools: &[]compute.SubResource{ + LoadBalancerBackendAddressPools: []*armcompute.SubResource{ { ID: ptr.To("backendpool-0-IPv6"), }, }, - PrivateIPAddressVersion: compute.IPv6, + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv6), }, }, }, }, }, - expectedPrimaryNIC: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + expectedPrimaryNIC: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(true), - LoadBalancerBackendAddressPools: &[]compute.SubResource{ + LoadBalancerBackendAddressPools: []*armcompute.SubResource{ { ID: ptr.To("backendpool-1"), }, @@ -2009,10 +2030,10 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { }, { Name: ptr.To("config-1"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(false), - LoadBalancerBackendAddressPools: &[]compute.SubResource{}, - PrivateIPAddressVersion: compute.IPv6, + LoadBalancerBackendAddressPools: []*armcompute.SubResource{}, + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv6), }, }, }, @@ -2023,36 +2044,36 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { { desc: "primary IP config not found IPv4", backendPoolID: "backendpool-0", - primaryNIC: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + primaryNIC: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(false), }, }, { Name: ptr.To("config-1"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(false), }, }, }, }, }, - expectedPrimaryNIC: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + expectedPrimaryNIC: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(false), }, }, { Name: ptr.To("config-1"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(false), }, }, @@ -2065,41 +2086,41 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { { desc: "primary IP config not found IPv6", backendPoolID: "backendpool-0-IPv6", - primaryNIC: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + primaryNIC: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(true), - PrivateIPAddressVersion: compute.IPv4, + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv4), }, }, { Name: ptr.To("config-1"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(false), - PrivateIPAddressVersion: compute.IPv4, + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv4), }, }, }, }, }, - expectedPrimaryNIC: &compute.VirtualMachineScaleSetNetworkConfiguration{ - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + expectedPrimaryNIC: &armcompute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("config-0"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(true), - PrivateIPAddressVersion: compute.IPv4, + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv4), }, }, { Name: ptr.To("config-1"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(false), - PrivateIPAddressVersion: compute.IPv4, + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv4), }, }, }, @@ -2121,8 +2142,6 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { } func TestEnsureHostInPool(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string @@ -2137,9 +2156,9 @@ func TestEnsureHostInPool(t *testing.T) { expectedNodeResourceGroup string expectedVMSSName string expectedInstanceID string - expectedVMSSVM *compute.VirtualMachineScaleSetVM + expectedVMSSVM *armcompute.VirtualMachineScaleSetVM expectedErr error - vmssVMListError *retry.Error + vmssVMListError error }{ { description: "EnsureHostInPool should skip the current node if the vmSetName is not equal to the node's vmss name and the basic LB is used", @@ -2183,21 +2202,20 @@ func TestEnsureHostInPool(t *testing.T) { expectedNodeResourceGroup: "rg", expectedVMSSName: testVMSSName, expectedInstanceID: "0", - expectedVMSSVM: &compute.VirtualMachineScaleSetVM{ + expectedVMSSVM: &armcompute.VirtualMachineScaleSetVM{ Location: ptr.To("westus"), - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - NetworkProfileConfiguration: &compute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ - NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ + NetworkProfileConfiguration: &armcompute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ + NetworkInterfaceConfigurations: []*armcompute.VirtualMachineScaleSetNetworkConfiguration{ { Name: ptr.To("vmss-nic"), - ID: ptr.To("fakeNetworkConfiguration"), - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("ipconfig1"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(true), - LoadBalancerBackendAddressPools: &[]compute.SubResource{ + LoadBalancerBackendAddressPools: []*armcompute.SubResource{ { ID: ptr.To(testLBBackendpoolID0), }, @@ -2205,7 +2223,7 @@ func TestEnsureHostInPool(t *testing.T) { ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb-internal/backendAddressPools/backendpool-1"), }, }, - PrivateIPAddressVersion: compute.IPv4, + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv4), }, }, }, @@ -2225,52 +2243,56 @@ func TestEnsureHostInPool(t *testing.T) { } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, test.description) + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, test.description) - if !test.isBasicLB { - ss.LoadBalancerSku = consts.LoadBalancerSkuStandard - } + if !test.isBasicLB { + ss.LoadBalancerSKU = consts.LoadBalancerSKUStandard + } - expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - provisionState := "" - if test.isVMBeingDeleted { - provisionState = "Deleting" - } - expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv( - ss.Cloud, - testVMSSName, - "", - 0, - []string{string(test.nodeName)}, - provisionState, - false, - ) - if test.isNilVMNetworkConfigs { - expectedVMSSVMs[0].NetworkProfileConfiguration.NetworkInterfaceConfigurations = nil - } - if test.isVMNotActive { - (*expectedVMSSVMs[0].InstanceView.Statuses)[0] = compute.InstanceViewStatus{ - Code: ptr.To("PowerState/deallocated"), + provisionState := "" + if test.isVMBeingDeleted { + provisionState = "Deleting" } - } - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List( - gomock.Any(), - ss.ResourceGroup, - testVMSSName, - gomock.Any(), - ).Return(expectedVMSSVMs, test.vmssVMListError).AnyTimes() - - nodeResourceGroup, ssName, instanceID, vm, err := ss.EnsureHostInPool(context.Background(), test.service, test.nodeName, test.backendPoolID, test.vmSetName) - assert.Equal(t, test.expectedErr, err, test.description+errMsgSuffix) - assert.Equal(t, test.expectedNodeResourceGroup, nodeResourceGroup, test.description) - assert.Equal(t, test.expectedVMSSName, ssName, test.description) - assert.Equal(t, test.expectedInstanceID, instanceID, test.description) - assert.Equal(t, test.expectedVMSSVM, vm, test.description) + expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv( + ss.Cloud, + testVMSSName, + "", + 0, + []string{string(test.nodeName)}, + provisionState, + false, + ) + if test.isNilVMNetworkConfigs { + expectedVMSSVMs[0].Properties.NetworkProfileConfiguration.NetworkInterfaceConfigurations = nil + } + if test.isVMNotActive { + (expectedVMSSVMs[0].Properties.InstanceView.Statuses)[0] = &armcompute.InstanceViewStatus{ + Code: ptr.To("PowerState/deallocated"), + } + } + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView( + gomock.Any(), + ss.ResourceGroup, + testVMSSName, + ).Return(expectedVMSSVMs, test.vmssVMListError).AnyTimes() + + nodeResourceGroup, ssName, instanceID, vm, err := ss.EnsureHostInPool(context.Background(), test.service, test.nodeName, test.backendPoolID, test.vmSetName) + assert.Equal(t, test.expectedErr, err, test.description+errMsgSuffix) + assert.Equal(t, test.expectedNodeResourceGroup, nodeResourceGroup, test.description) + assert.Equal(t, test.expectedVMSSName, ssName, test.description) + assert.Equal(t, test.expectedInstanceID, instanceID, test.description) + assert.Equal(t, test.expectedVMSSVM, vm, test.description) + }) } } @@ -2550,28 +2572,28 @@ func TestEnsureVMSSInPool(t *testing.T) { assert.NoError(t, err, test.description) if !test.isBasicLB { - ss.LoadBalancerSku = consts.LoadBalancerSkuStandard + ss.LoadBalancerSKU = consts.LoadBalancerSKUStandard } expectedVMSS := buildTestOSSpecificVMSSWithLB(testVMSSName, "vmss-vm-", []string{testLBBackendpoolID0}, test.os, test.setIPv6Config) if test.isVMSSDeallocating { - expectedVMSS.ProvisioningState = ptr.To(consts.ProvisionStateDeleting) + expectedVMSS.Properties.ProvisioningState = ptr.To(consts.ProvisionStateDeleting) } if test.isVMSSNilNICConfig { - expectedVMSS.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = nil + expectedVMSS.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = nil } - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() vmssPutTimes := 0 if test.expectedPutVMSS { vmssPutTimes = 1 - mockVMSSClient.EXPECT().Get(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSS, nil) + mockVMSSClient.EXPECT().Get(gomock.Any(), ss.ResourceGroup, testVMSSName, nil).Return(expectedVMSS, nil) } - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(nil).Times(vmssPutTimes) + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(nil, nil).Times(vmssPutTimes) expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, []string{"vmss-vm-000000"}, "", test.setIPv6Config) - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() if test.expectedGetInstanceID != "" { mockVMSet := NewMockVMSet(ctrl) @@ -2586,8 +2608,6 @@ func TestEnsureVMSSInPool(t *testing.T) { } func TestEnsureHostsInPool(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string @@ -2651,34 +2671,38 @@ func TestEnsureHostsInPool(t *testing.T) { } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, test.description) + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - ss.LoadBalancerSku = consts.LoadBalancerSkuStandard - ss.ExcludeMasterFromStandardLB = ptr.To(true) + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, test.description) - expectedVMSS := buildTestVMSSWithLB(testVMSSName, "vmss-vm-", []string{testLBBackendpoolID0}, false) - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - mockVMSSClient.EXPECT().Get(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSS, nil).MaxTimes(1) - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(nil).MaxTimes(1) + ss.LoadBalancerSKU = consts.LoadBalancerSKUStandard + ss.ExcludeMasterFromStandardLB = ptr.To(true) - expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, []string{"vmss-vm-000000", "vmss-vm-000001", "vmss-vm-000002"}, "", false) - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() - mockVMSSVMClient.EXPECT().UpdateVMs(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).Times(test.expectedVMSSVMPutTimes) + expectedVMSS := buildTestVMSSWithLB(testVMSSName, "vmss-vm-", []string{testLBBackendpoolID0}, false) + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + mockVMSSClient.EXPECT().Get(gomock.Any(), ss.ResourceGroup, testVMSSName, nil).Return(expectedVMSS, nil).MaxTimes(1) + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(nil, nil).MaxTimes(1) - mockVMClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, []string{"vmss-vm-000000", "vmss-vm-000001", "vmss-vm-000002"}, "", false) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() + mockVMSSVMClient.EXPECT().Update(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any(), gomock.Any()).Return(nil, nil).Times(test.expectedVMSSVMPutTimes) - err = ss.EnsureHostsInPool(context.Background(), &v1.Service{}, test.nodes, test.backendpoolID, test.vmSetName) - assert.Equal(t, test.expectedErr, err != nil, test.description+errMsgSuffix) + mockVMClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + + err = ss.EnsureHostsInPool(context.Background(), &v1.Service{}, test.nodes, test.backendpoolID, test.vmSetName) + assert.Equal(t, test.expectedErr, err != nil, test.description+errMsgSuffix) + }) } } func TestEnsureBackendPoolDeletedFromNodeCommon(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string @@ -2689,7 +2713,7 @@ func TestEnsureBackendPoolDeletedFromNodeCommon(t *testing.T) { expectedNodeResourceGroup string expectedVMSSName string expectedInstanceID string - expectedVMSSVM *compute.VirtualMachineScaleSetVM + expectedVMSSVM *armcompute.VirtualMachineScaleSetVM expectedErr error }{ { @@ -2713,30 +2737,29 @@ func TestEnsureBackendPoolDeletedFromNodeCommon(t *testing.T) { expectedNodeResourceGroup: "rg", expectedVMSSName: testVMSSName, expectedInstanceID: "0", - expectedVMSSVM: &compute.VirtualMachineScaleSetVM{ + expectedVMSSVM: &armcompute.VirtualMachineScaleSetVM{ Location: ptr.To("westus"), - VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - NetworkProfileConfiguration: &compute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ - NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetVMProperties{ + NetworkProfileConfiguration: &armcompute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ + NetworkInterfaceConfigurations: []*armcompute.VirtualMachineScaleSetNetworkConfiguration{ { Name: ptr.To("vmss-nic"), - ID: ptr.To("fakeNetworkConfiguration"), - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { Name: ptr.To("ipconfig1"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(true), - LoadBalancerBackendAddressPools: &[]compute.SubResource{}, - PrivateIPAddressVersion: compute.IPv4, + LoadBalancerBackendAddressPools: []*armcompute.SubResource{}, + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv4), }, }, { Name: ptr.To("ipconfigv6"), - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ Primary: ptr.To(false), - LoadBalancerBackendAddressPools: &[]compute.SubResource{}, - PrivateIPAddressVersion: compute.IPv6, + LoadBalancerBackendAddressPools: []*armcompute.SubResource{}, + PrivateIPAddressVersion: to.Ptr(armcompute.IPVersionIPv6), }, }, }, @@ -2756,26 +2779,29 @@ func TestEnsureBackendPoolDeletedFromNodeCommon(t *testing.T) { } for _, test := range testCases { + test := test t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() ss, err := NewTestScaleSet(ctrl) assert.NoError(t, err, test.description) expectedVMSS := buildTestVMSS(testVMSSName, "vmss-vm-") - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() // isIPv6 true means it is a DualStack or IPv6 only cluster. expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, []string{"vmss-vm-000000"}, "", true) if test.isNilVMNetworkConfigs { - expectedVMSSVMs[0].NetworkProfileConfiguration.NetworkInterfaceConfigurations = nil + expectedVMSSVMs[0].Properties.NetworkProfileConfiguration.NetworkInterfaceConfigurations = nil } if test.isVMNotActive { - (*expectedVMSSVMs[0].InstanceView.Statuses)[0] = compute.InstanceViewStatus{ + (expectedVMSSVMs[0].Properties.InstanceView.Statuses)[0] = &armcompute.InstanceViewStatus{ Code: ptr.To("PowerState/deallocated"), } } - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() nodeResourceGroup, ssName, instanceID, vm, err := ss.ensureBackendPoolDeletedFromNode(context.TODO(), test.nodeName, test.backendpoolIDs) assert.Equal(t, test.expectedErr, err) @@ -2802,8 +2828,6 @@ func TestGetScaleSetAndResourceGroupNameByIPConfigurationID(t *testing.T) { } func TestEnsureBackendPoolDeletedFromVMSS(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string @@ -2813,7 +2837,7 @@ func TestEnsureBackendPoolDeletedFromVMSS(t *testing.T) { isVMSSNilNICConfig bool isVMSSNilVirtualMachineProfile bool expectedPutVMSS bool - vmssClientErr *retry.Error + vmssClientErr error expectedErr error }{ { @@ -2841,67 +2865,71 @@ func TestEnsureBackendPoolDeletedFromVMSS(t *testing.T) { ipConfigurationIDs: []string{"/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/vmss-vm-000000/networkInterfaces/nic"}, backendPoolID: testLBBackendpoolID0, expectedPutVMSS: true, - vmssClientErr: &retry.Error{RawError: fmt.Errorf("error")}, - expectedErr: utilerrors.NewAggregate([]error{fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: error")}), + vmssClientErr: &azcore.ResponseError{ErrorCode: "error"}, + expectedErr: fmt.Errorf("error"), }, } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, test.description) + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - ss.LoadBalancerSku = consts.LoadBalancerSkuStandard + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, test.description) - expectedVMSS := buildTestVMSSWithLB(testVMSSName, "vmss-vm-", []string{testLBBackendpoolID0}, false) - if test.isVMSSDeallocating { - expectedVMSS.ProvisioningState = ptr.To(consts.ProvisionStateDeleting) - } - if test.isVMSSNilNICConfig { - expectedVMSS.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = nil - } - if test.isVMSSNilVirtualMachineProfile { - expectedVMSS.VirtualMachineProfile = nil - } - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes().MinTimes(1) - vmssPutTimes := 0 - if test.expectedPutVMSS { - vmssPutTimes = 1 - mockVMSSClient.EXPECT().Get(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSS, nil) - } - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(test.vmssClientErr).Times(vmssPutTimes) + ss.LoadBalancerSKU = consts.LoadBalancerSKUStandard + + expectedVMSS := buildTestVMSSWithLB(testVMSSName, "vmss-vm-", []string{testLBBackendpoolID0}, false) + if test.isVMSSDeallocating { + expectedVMSS.Properties.ProvisioningState = ptr.To(consts.ProvisionStateDeleting) + } + if test.isVMSSNilNICConfig { + expectedVMSS.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = nil + } + if test.isVMSSNilVirtualMachineProfile { + expectedVMSS.Properties.VirtualMachineProfile = nil + } + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes().MinTimes(1) + vmssPutTimes := 0 + if test.expectedPutVMSS { + vmssPutTimes = 1 + mockVMSSClient.EXPECT().Get(gomock.Any(), ss.ResourceGroup, testVMSSName, nil).Return(expectedVMSS, nil) + } + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(nil, test.vmssClientErr).Times(vmssPutTimes) - expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, []string{"vmss-vm-000000"}, "", false) - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() + expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, []string{"vmss-vm-000000"}, "", false) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() - err = ss.ensureBackendPoolDeletedFromVMSS(context.TODO(), []string{test.backendPoolID}, testVMSSName) - if test.expectedErr != nil { - assert.EqualError(t, test.expectedErr, err.Error(), test.description+errMsgSuffix) - } + err = ss.ensureBackendPoolDeletedFromVMSS(context.TODO(), []string{test.backendPoolID}, testVMSSName) + if test.expectedErr != nil { + assert.Contains(t, err.Error(), test.expectedErr.Error(), test.description+errMsgSuffix) + } + }) } } func TestEnsureBackendPoolDeleted(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string backendpoolID string - backendAddressPools *[]network.BackendAddressPool + backendAddressPools []*armnetwork.BackendAddressPool expectedVMSSVMPutTimes int - vmClientErr *retry.Error + vmClientErr error expectedErr bool }{ { description: "EnsureBackendPoolDeleted should skip the unwanted backend address pools and update the VMSS VM correctly", backendpoolID: testLBBackendpoolID0, - backendAddressPools: &[]network.BackendAddressPool{ + backendAddressPools: []*armnetwork.BackendAddressPool{ { ID: ptr.To(testLBBackendpoolID0), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { Name: ptr.To("ip-1"), ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic"), @@ -2925,11 +2953,11 @@ func TestEnsureBackendPoolDeleted(t *testing.T) { { description: "EnsureBackendPoolDeleted should report the error that occurs during the call of VMSS VM client", backendpoolID: testLBBackendpoolID0, - backendAddressPools: &[]network.BackendAddressPool{ + backendAddressPools: []*armnetwork.BackendAddressPool{ { ID: ptr.To(testLBBackendpoolID0), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { Name: ptr.To("ip-1"), ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic"), @@ -2943,16 +2971,16 @@ func TestEnsureBackendPoolDeleted(t *testing.T) { }, expectedVMSSVMPutTimes: 1, expectedErr: true, - vmClientErr: &retry.Error{RawError: fmt.Errorf("error")}, + vmClientErr: &azcore.ResponseError{ErrorCode: "error"}, }, { description: "EnsureBackendPoolDeleted should skip the node that doesn't exist", backendpoolID: testLBBackendpoolID0, - backendAddressPools: &[]network.BackendAddressPool{ + backendAddressPools: []*armnetwork.BackendAddressPool{ { ID: ptr.To(testLBBackendpoolID0), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { Name: ptr.To("ip-1"), ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/6/networkInterfaces/nic"), @@ -2968,28 +2996,34 @@ func TestEnsureBackendPoolDeleted(t *testing.T) { } for _, test := range testCases { - ss, err := NewTestScaleSet(ctrl) - assert.NoError(t, err, test.description) + test := test + t.Run(test.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - expectedVMSS := buildTestVMSSWithLB(testVMSSName, "vmss-vm-", []string{testLBBackendpoolID0}, false) - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() - mockVMSSClient.EXPECT().Get(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSS, nil).MaxTimes(1) - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(nil).Times(1) + ss, err := NewTestScaleSet(ctrl) + assert.NoError(t, err, test.description) - expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, []string{"vmss-vm-000000", "vmss-vm-000001", "vmss-vm-000002"}, "", false) - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() - mockVMSSVMClient.EXPECT().UpdateVMs(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any(), gomock.Any(), gomock.Any()).Return(test.vmClientErr).Times(test.expectedVMSSVMPutTimes) + expectedVMSS := buildTestVMSSWithLB(testVMSSName, "vmss-vm-", []string{testLBBackendpoolID0}, false) + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() + mockVMSSClient.EXPECT().Get(gomock.Any(), ss.ResourceGroup, testVMSSName, nil).Return(expectedVMSS, nil).MaxTimes(1) + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any()).Return(nil, nil).Times(1) - mockVMsClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachine{}, nil).AnyTimes() + expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, []string{"vmss-vm-000000", "vmss-vm-000001", "vmss-vm-000002"}, "", false) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, testVMSSName).Return(expectedVMSSVMs, nil).AnyTimes() + mockVMSSVMClient.EXPECT().Update(gomock.Any(), ss.ResourceGroup, testVMSSName, gomock.Any(), gomock.Any()).Return(nil, test.vmClientErr).Times(test.expectedVMSSVMPutTimes) - updated, err := ss.EnsureBackendPoolDeleted(context.TODO(), &v1.Service{}, []string{test.backendpoolID}, testVMSSName, test.backendAddressPools, true) - assert.Equal(t, test.expectedErr, err != nil, test.description+errMsgSuffix) - if !test.expectedErr && test.expectedVMSSVMPutTimes > 0 { - assert.True(t, updated, test.description) - } + mockVMsClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() + + updated, err := ss.EnsureBackendPoolDeleted(context.TODO(), &v1.Service{}, []string{test.backendpoolID}, testVMSSName, test.backendAddressPools, true) + assert.Equal(t, test.expectedErr, err != nil, test.description+errMsgSuffix) + if !test.expectedErr && test.expectedVMSSVMPutTimes > 0 { + assert.True(t, updated, test.description) + } + }) } } @@ -3007,11 +3041,11 @@ func TestEnsureBackendPoolDeletedConcurrently(t *testing.T) { ss, err := NewTestScaleSet(ctrl) assert.NoError(t, err) - backendAddressPools := &[]network.BackendAddressPool{ + backendAddressPools := []*armnetwork.BackendAddressPool{ { ID: ptr.To(testLBBackendpoolID0), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { Name: ptr.To("ip-1"), ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-0/virtualMachines/0/networkInterfaces/nic"), @@ -3021,8 +3055,8 @@ func TestEnsureBackendPoolDeletedConcurrently(t *testing.T) { }, { ID: ptr.To(testLBBackendpoolID1), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { Name: ptr.To("ip-1"), ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-1/virtualMachines/0/networkInterfaces/nic"), @@ -3032,8 +3066,8 @@ func TestEnsureBackendPoolDeletedConcurrently(t *testing.T) { }, { ID: ptr.To(testLBBackendpoolID2), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { Name: ptr.To("ip-1"), ID: ptr.To("/subscriptions/sub/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-0/virtualMachines/0/networkInterfaces/nic"), @@ -3048,28 +3082,27 @@ func TestEnsureBackendPoolDeletedConcurrently(t *testing.T) { expectedVMSSVMsOfVMSS0, _, _ := buildTestVirtualMachineEnv(ss.Cloud, "vmss-0", "", 0, []string{"vmss-0-vm-000000"}, "succeeded", false) expectedVMSSVMsOfVMSS1, _, _ := buildTestVirtualMachineEnv(ss.Cloud, "vmss-1", "", 0, []string{"vmss-1-vm-000001"}, "succeeded", false) - for _, expectedVMSSVMs := range [][]compute.VirtualMachineScaleSetVM{expectedVMSSVMsOfVMSS0, expectedVMSSVMsOfVMSS1} { - vmssVMNetworkConfigs := expectedVMSSVMs[0].NetworkProfileConfiguration - vmssVMIPConfigs := (*vmssVMNetworkConfigs.NetworkInterfaceConfigurations)[0].VirtualMachineScaleSetNetworkConfigurationProperties.IPConfigurations - lbBackendpools := (*vmssVMIPConfigs)[0].LoadBalancerBackendAddressPools - *lbBackendpools = append(*lbBackendpools, compute.SubResource{ID: ptr.To(testLBBackendpoolID1)}) + for _, expectedVMSSVMs := range [][]*armcompute.VirtualMachineScaleSetVM{expectedVMSSVMsOfVMSS0, expectedVMSSVMsOfVMSS1} { + vmssVMNetworkConfigs := expectedVMSSVMs[0].Properties.NetworkProfileConfiguration + vmssVMIPConfigs := (vmssVMNetworkConfigs.NetworkInterfaceConfigurations)[0].Properties.IPConfigurations + (vmssVMIPConfigs)[0].Properties.LoadBalancerBackendAddressPools = append((vmssVMIPConfigs)[0].Properties.LoadBalancerBackendAddressPools, &armcompute.SubResource{ID: ptr.To(testLBBackendpoolID1)}) } - mockVMClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachine{}, nil).AnyTimes() + mockVMClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{vmss0, vmss1}, nil).AnyTimes() + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{vmss0, vmss1}, nil).AnyTimes() mockVMSSClient.EXPECT().List(gomock.Any(), "rg1").Return(nil, nil).AnyTimes() - mockVMSSClient.EXPECT().Get(gomock.Any(), ss.ResourceGroup, "vmss-0").Return(vmss0, nil).MaxTimes(2) - mockVMSSClient.EXPECT().Get(gomock.Any(), ss.ResourceGroup, "vmss-1").Return(vmss1, nil).MaxTimes(2) - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), ss.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil).Times(2) + mockVMSSClient.EXPECT().Get(gomock.Any(), ss.ResourceGroup, "vmss-0", nil).Return(vmss0, nil).MaxTimes(2) + mockVMSSClient.EXPECT().Get(gomock.Any(), ss.ResourceGroup, "vmss-1", nil).Return(vmss1, nil).MaxTimes(2) + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), ss.ResourceGroup, gomock.Any(), gomock.Any()).Return(nil, nil).Times(2) - mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), "rg1", "vmss-0", gomock.Any()).Return(nil, nil).AnyTimes() - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, "vmss-0", gomock.Any()).Return(expectedVMSSVMsOfVMSS0, nil).AnyTimes() - mockVMSSVMClient.EXPECT().List(gomock.Any(), ss.ResourceGroup, "vmss-1", gomock.Any()).Return(expectedVMSSVMsOfVMSS1, nil).AnyTimes() - mockVMSSVMClient.EXPECT().UpdateVMs(gomock.Any(), ss.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).Times(2) + mockVMSSVMClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), "rg1", "vmss-0").Return(nil, nil).AnyTimes() + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, "vmss-0").Return(expectedVMSSVMsOfVMSS0, nil).AnyTimes() + mockVMSSVMClient.EXPECT().ListVMInstanceView(gomock.Any(), ss.ResourceGroup, "vmss-1").Return(expectedVMSSVMsOfVMSS1, nil).AnyTimes() + mockVMSSVMClient.EXPECT().Update(gomock.Any(), ss.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).Times(2) backendpoolAddressIDs := []string{testLBBackendpoolID0, testLBBackendpoolID1, testLBBackendpoolID2} testVMSSNames := []string{"vmss-0", "vmss-1", "vmss-2"} @@ -3134,18 +3167,18 @@ func TestGetNodeCIDRMasksByProviderID(t *testing.T) { ss, err := NewTestScaleSet(ctrl) assert.NoError(t, err) - expectedVMSS := compute.VirtualMachineScaleSet{ + expectedVMSS := &armcompute.VirtualMachineScaleSet{ Name: ptr.To("vmss"), Tags: tc.tags, - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - OrchestrationMode: compute.Uniform, + Properties: &armcompute.VirtualMachineScaleSetProperties{ + OrchestrationMode: to.Ptr(armcompute.OrchestrationModeUniform), }, } - mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).MaxTimes(1) + mockVMSSClient := ss.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), ss.ResourceGroup).Return([]*armcompute.VirtualMachineScaleSet{expectedVMSS}, nil).MaxTimes(1) - mockVMsClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachine{}, nil).AnyTimes() + mockVMsClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() ipv4MaskSize, ipv6MaskSize, err := ss.GetNodeCIDRMasksByProviderID(context.TODO(), tc.providerID) assert.Equal(t, tc.expectedErr, err, tc.description) @@ -3162,25 +3195,25 @@ func TestGetAgentPoolVMSetNamesMixedInstances(t *testing.T) { ss, err := NewTestScaleSet(ctrl) assert.NoError(t, err) - existingVMs := []compute.VirtualMachine{ + existingVMs := []*armcompute.VirtualMachine{ { Name: ptr.To("vm-0"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ - OsProfile: &compute.OSProfile{ + Properties: &armcompute.VirtualMachineProperties{ + OSProfile: &armcompute.OSProfile{ ComputerName: ptr.To("vm-0"), }, - AvailabilitySet: &compute.SubResource{ + AvailabilitySet: &armcompute.SubResource{ ID: ptr.To("vmas-0"), }, }, }, { Name: ptr.To("vm-1"), - VirtualMachineProperties: &compute.VirtualMachineProperties{ - OsProfile: &compute.OSProfile{ + Properties: &armcompute.VirtualMachineProperties{ + OSProfile: &armcompute.OSProfile{ ComputerName: ptr.To("vm-1"), }, - AvailabilitySet: &compute.SubResource{ + AvailabilitySet: &armcompute.SubResource{ ID: ptr.To("vmas-1"), }, }, @@ -3190,14 +3223,14 @@ func TestGetAgentPoolVMSetNamesMixedInstances(t *testing.T) { vmList := []string{"vmssee6c2000000", "vmssee6c2000001", "vmssee6c2000002"} existingVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, vmList, "", false) - mockVMClient := ss.Cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) + mockVMClient := ss.Cloud.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(existingVMs, nil).AnyTimes() - mockVMSSClient := ss.Cloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{expectedScaleSet}, nil) + mockVMSSClient := ss.Cloud.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachineScaleSet{expectedScaleSet}, nil) - mockVMSSVMClient := ss.Cloud.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) - mockVMSSVMClient.EXPECT().List(gomock.Any(), gomock.Any(), testVMSSName, gomock.Any()).Return(existingVMSSVMs, nil) + mockVMSSVMClient := ss.Cloud.ComputeClientFactory.GetVirtualMachineScaleSetVMClient().(*mock_virtualmachinescalesetvmclient.MockInterface) + mockVMSSVMClient.EXPECT().List(gomock.Any(), gomock.Any(), testVMSSName).Return(existingVMSSVMs, nil) nodes := []*v1.Node{ { @@ -3211,7 +3244,7 @@ func TestGetAgentPoolVMSetNamesMixedInstances(t *testing.T) { }, }, } - expectedVMSetNames := &[]string{testVMSSName, "vmas-0"} + expectedVMSetNames := []string{testVMSSName, "vmas-0"} vmSetNames, err := ss.GetAgentPoolVMSetNames(context.TODO(), nodes) assert.NoError(t, err) assert.Equal(t, expectedVMSetNames, vmSetNames) @@ -3230,8 +3263,8 @@ func TestGetNodeVMSetNameVMSS(t *testing.T) { ss, err := NewTestScaleSet(ctrl) assert.NoError(t, err) - mockVMsClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachine{}, nil).AnyTimes() + mockVMsClient := ss.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMsClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachine{}, nil).AnyTimes() vmSetName, err := ss.GetNodeVMSetName(context.TODO(), node) assert.Equal(t, ErrorNotVmssInstance, err) @@ -3262,9 +3295,9 @@ func TestScaleSet_VMSSBatchSize(t *testing.T) { var ( vmssName = "foo" - getVMSSErr = &retry.Error{RawError: fmt.Errorf("list vmss error")} + getVMSSErr = &azcore.ResponseError{ErrorCode: "list vmss error"} ) - mockVMSSClient := ss.Cloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := ss.Cloud.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()). Return(nil, getVMSSErr) @@ -3279,18 +3312,18 @@ func TestScaleSet_VMSSBatchSize(t *testing.T) { assert.NoError(t, err) ss.Cloud.PutVMSSVMBatchSize = BatchSize - scaleSet := compute.VirtualMachineScaleSet{ + scaleSet := &armcompute.VirtualMachineScaleSet{ Name: ptr.To("foo"), Tags: map[string]*string{ consts.VMSSTagForBatchOperation: ptr.To(""), }, - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - OrchestrationMode: compute.Uniform, + Properties: &armcompute.VirtualMachineScaleSetProperties{ + OrchestrationMode: to.Ptr(armcompute.OrchestrationModeUniform), }, } - mockVMSSClient := ss.Cloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := ss.Cloud.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()). - Return([]compute.VirtualMachineScaleSet{scaleSet}, nil) + Return([]*armcompute.VirtualMachineScaleSet{scaleSet}, nil) batchSize, err := ss.VMSSBatchSize(context.TODO(), ptr.Deref(scaleSet.Name, "")) assert.NoError(t, err) @@ -3304,15 +3337,15 @@ func TestScaleSet_VMSSBatchSize(t *testing.T) { assert.NoError(t, err) ss.Cloud.PutVMSSVMBatchSize = BatchSize - scaleSet := compute.VirtualMachineScaleSet{ + scaleSet := &armcompute.VirtualMachineScaleSet{ Name: ptr.To("bar"), - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - OrchestrationMode: compute.Uniform, + Properties: &armcompute.VirtualMachineScaleSetProperties{ + OrchestrationMode: to.Ptr(armcompute.OrchestrationModeUniform), }, } - mockVMSSClient := ss.Cloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := ss.Cloud.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()). - Return([]compute.VirtualMachineScaleSet{scaleSet}, nil) + Return([]*armcompute.VirtualMachineScaleSet{scaleSet}, nil) batchSize, err := ss.VMSSBatchSize(context.TODO(), ptr.Deref(scaleSet.Name, "")) assert.NoError(t, err) diff --git a/pkg/provider/azure_vmssflex.go b/pkg/provider/azure_vmssflex.go index 666fe2948a..35c715b339 100644 --- a/pkg/provider/azure_vmssflex.go +++ b/pkg/provider/azure_vmssflex.go @@ -25,8 +25,10 @@ import ( "sync" "sync/atomic" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/samber/lo" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" @@ -116,17 +118,17 @@ func (fs *FlexScaleSet) GetNodeVMSetName(ctx context.Context, node *v1.Node) (st } // GetAgentPoolVMSetNames returns all vmSet names according to the nodes -func (fs *FlexScaleSet) GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1.Node) (*[]string, error) { - vmSetNames := make([]string, 0) +func (fs *FlexScaleSet) GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1.Node) ([]*string, error) { + vmSetNames := make([]*string, 0) for _, node := range nodes { vmSetName, err := fs.GetNodeVMSetName(ctx, node) if err != nil { klog.Errorf("Unable to get the vmss flex name by node name %s: %v", node.Name, err) continue } - vmSetNames = append(vmSetNames, vmSetName) + vmSetNames = append(vmSetNames, &vmSetName) } - return &vmSetNames, nil + return vmSetNames, nil } // GetVMSetNames selects all possible availability sets or scale sets @@ -134,12 +136,12 @@ func (fs *FlexScaleSet) GetAgentPoolVMSetNames(ctx context.Context, nodes []*v1. // no loadbalancer mode annotation returns the primary VMSet. If service annotation // for loadbalancer exists then returns the eligible VMSet. The mode selection // annotation would be ignored when using one SLB per cluster. -func (fs *FlexScaleSet) GetVMSetNames(ctx context.Context, service *v1.Service, nodes []*v1.Node) (*[]string, error) { +func (fs *FlexScaleSet) GetVMSetNames(ctx context.Context, service *v1.Service, nodes []*v1.Node) ([]*string, error) { hasMode, isAuto, serviceVMSetName := fs.getServiceLoadBalancerMode(service) if !hasMode || fs.UseStandardLoadBalancer() { // no mode specified in service annotation or use single SLB mode // default to PrimaryScaleSetName - vmssFlexNames := &[]string{fs.Config.PrimaryScaleSetName} + vmssFlexNames := to.SliceOfPtrs(fs.Config.PrimaryScaleSetName) return vmssFlexNames, nil } @@ -151,10 +153,10 @@ func (fs *FlexScaleSet) GetVMSetNames(ctx context.Context, service *v1.Service, if !isAuto { found := false - for asx := range *vmssFlexNames { - if strings.EqualFold((*vmssFlexNames)[asx], serviceVMSetName) { + for asx := range vmssFlexNames { + if strings.EqualFold(*(vmssFlexNames)[asx], serviceVMSetName) { found = true - serviceVMSetName = (*vmssFlexNames)[asx] + serviceVMSetName = *(vmssFlexNames)[asx] break } } @@ -162,7 +164,7 @@ func (fs *FlexScaleSet) GetVMSetNames(ctx context.Context, service *v1.Service, klog.Errorf("fs.GetVMSetNames - scale set (%s) in service annotation not found", serviceVMSetName) return nil, fmt.Errorf("scale set (%s) - not found", serviceVMSetName) } - return &[]string{serviceVMSetName}, nil + return to.SliceOfPtrs(serviceVMSetName), nil } return vmssFlexNames, nil } @@ -171,7 +173,7 @@ func (fs *FlexScaleSet) GetVMSetNames(ctx context.Context, service *v1.Service, // providerID example: // azure:///subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/flexprofile-mp-0_df53ee36 // Different from vmas where vm name is always equal to nodeName, we need to further map vmName to actual nodeName in vmssflex. -// Note: nodeName is always equal ptr.Derefs.ToLower(*vm.OsProfile.ComputerName, "") +// Note: nodeName is always equal ptr.Derefs.ToLower(*vm.Properties.OSProfile.ComputerName, "") func (fs *FlexScaleSet) GetNodeNameByProviderID(ctx context.Context, providerID string) (types.NodeName, error) { // NodeName is part of providerID for standard instances. matches := providerIDRE.FindStringSubmatch(providerID) @@ -214,10 +216,10 @@ func (fs *FlexScaleSet) GetInstanceTypeByNodeName(ctx context.Context, name stri return "", err } - if machine.HardwareProfile == nil { + if machine.Properties.HardwareProfile == nil { return "", fmt.Errorf("HardwareProfile of node(%s) is nil", name) } - return string(machine.HardwareProfile.VMSize), nil + return string(*machine.Properties.HardwareProfile.VMSize), nil } // GetZoneByNodeName gets availability zone for the specified node. If the node is not running @@ -231,18 +233,18 @@ func (fs *FlexScaleSet) GetZoneByNodeName(ctx context.Context, name string) (clo } var failureDomain string - if vm.Zones != nil && len(*vm.Zones) > 0 { + if len(vm.Zones) > 0 { // Get availability zone for the node. - zones := *vm.Zones - zoneID, err := strconv.Atoi(zones[0]) + zones := vm.Zones + zoneID, err := strconv.Atoi(*zones[0]) if err != nil { - return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone %q: %w", zones, err) + return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone %q: %w", lo.FromSlicePtr(zones), err) } failureDomain = fs.makeZone(ptr.Deref(vm.Location, ""), zoneID) - } else if vm.VirtualMachineProperties.InstanceView != nil && vm.VirtualMachineProperties.InstanceView.PlatformFaultDomain != nil { + } else if vm.Properties.InstanceView != nil && vm.Properties.InstanceView.PlatformFaultDomain != nil { // Availability zone is not used for the node, falling back to fault domain. - failureDomain = strconv.Itoa(int(ptr.Deref(vm.VirtualMachineProperties.InstanceView.PlatformFaultDomain, 0))) + failureDomain = strconv.Itoa(int(ptr.Deref(vm.Properties.InstanceView.PlatformFaultDomain, 0))) } else { err = fmt.Errorf("failed to get zone info") klog.Errorf("GetZoneByNodeName: got unexpected error %v", err) @@ -263,11 +265,11 @@ func (fs *FlexScaleSet) GetProvisioningStateByNodeName(ctx context.Context, name return provisioningState, err } - if vm.VirtualMachineProperties == nil || vm.VirtualMachineProperties.ProvisioningState == nil { + if vm.Properties == nil || vm.Properties.ProvisioningState == nil { return provisioningState, nil } - return ptr.Deref(vm.VirtualMachineProperties.ProvisioningState, ""), nil + return ptr.Deref(vm.Properties.ProvisioningState, ""), nil } // GetPowerStatusByNodeName returns the powerState for the specified node. @@ -277,40 +279,40 @@ func (fs *FlexScaleSet) GetPowerStatusByNodeName(ctx context.Context, name strin return powerState, err } - if vm.InstanceView != nil { - return vmutil.GetVMPowerState(ptr.Deref(vm.Name, ""), vm.InstanceView.Statuses), nil + if vm.Properties.InstanceView != nil { + return vmutil.GetVMPowerState(ptr.Deref(vm.Name, ""), vm.Properties.InstanceView.Statuses), nil } - // vm.InstanceView or vm.InstanceView.Statuses are nil when the VM is under deleting. + // vm.Properties.InstanceView or vm.Properties.InstanceView.Statuses are nil when the VM is under deleting. klog.V(3).Infof("InstanceView for node %q is nil, assuming it's deleting", name) return consts.VMPowerStateUnknown, nil } // GetPrimaryInterface gets machine primary network interface by node name. -func (fs *FlexScaleSet) GetPrimaryInterface(ctx context.Context, nodeName string) (network.Interface, error) { +func (fs *FlexScaleSet) GetPrimaryInterface(ctx context.Context, nodeName string) (*armnetwork.Interface, error) { machine, err := fs.getVmssFlexVM(ctx, nodeName, azcache.CacheReadTypeDefault) if err != nil { klog.Errorf("fs.GetInstanceTypeByNodeName(%s) failed: fs.getVmssFlexVMWithoutInstanceView(%s) err=%v", nodeName, nodeName, err) - return network.Interface{}, err + return nil, err } primaryNicID, err := getPrimaryInterfaceID(machine) if err != nil { - return network.Interface{}, err + return nil, err } nicName, err := getLastSegment(primaryNicID, "/") if err != nil { - return network.Interface{}, err + return nil, err } nicResourceGroup, err := extractResourceGroupByNicID(primaryNicID) if err != nil { - return network.Interface{}, err + return nil, err } - nic, rerr := fs.InterfacesClient.Get(ctx, nicResourceGroup, nicName, "") + nic, rerr := fs.NetworkClientFactory.GetInterfaceClient().Get(ctx, nicResourceGroup, nicName, nil) if rerr != nil { - return network.Interface{}, rerr.Error() + return nil, rerr } return nic, nil @@ -329,10 +331,10 @@ func (fs *FlexScaleSet) GetIPByNodeName(ctx context.Context, name string) (strin return "", "", err } - privateIP := *ipConfig.PrivateIPAddress + privateIP := *ipConfig.Properties.PrivateIPAddress publicIP := "" - if ipConfig.PublicIPAddress != nil && ipConfig.PublicIPAddress.ID != nil { - pipID := *ipConfig.PublicIPAddress.ID + if ipConfig.Properties.PublicIPAddress != nil && ipConfig.Properties.PublicIPAddress.ID != nil { + pipID := *ipConfig.Properties.PublicIPAddress.ID pipName, err := getLastSegment(pipID, "/") if err != nil { return "", "", fmt.Errorf("failed to publicIP name for node %q with pipID %q", name, pipID) @@ -342,7 +344,7 @@ func (fs *FlexScaleSet) GetIPByNodeName(ctx context.Context, name string) (strin return "", "", err } if existsPip { - publicIP = *pip.IPAddress + publicIP = *pip.Properties.IPAddress } } @@ -359,13 +361,13 @@ func (fs *FlexScaleSet) GetPrivateIPsByNodeName(ctx context.Context, name string return ips, err } - if nic.IPConfigurations == nil { - return ips, fmt.Errorf("nic.IPConfigurations for nic (nicname=%s) is nil", *nic.Name) + if nic.Properties.IPConfigurations == nil { + return ips, fmt.Errorf("nic.Properties.IPConfigurations for nic (nicname=%s) is nil", *nic.Name) } - for _, ipConfig := range *(nic.IPConfigurations) { - if ipConfig.PrivateIPAddress != nil { - ips = append(ips, *(ipConfig.PrivateIPAddress)) + for _, ipConfig := range nic.Properties.IPConfigurations { + if ipConfig.Properties.PrivateIPAddress != nil { + ips = append(ips, *ipConfig.Properties.PrivateIPAddress) } } @@ -445,7 +447,7 @@ func (fs *FlexScaleSet) GetNodeCIDRMasksByProviderID(ctx context.Context, provid // EnsureHostInPool ensures the given VM's Primary NIC's Primary IP Configuration is // participating in the specified LoadBalancer Backend Pool, which returns (resourceGroup, vmasName, instanceID, vmssVM, error). -func (fs *FlexScaleSet) EnsureHostInPool(ctx context.Context, service *v1.Service, nodeName types.NodeName, backendPoolID string, vmSetNameOfLB string) (string, string, string, *compute.VirtualMachineScaleSetVM, error) { +func (fs *FlexScaleSet) EnsureHostInPool(ctx context.Context, service *v1.Service, nodeName types.NodeName, backendPoolID string, vmSetNameOfLB string) (string, string, string, *armcompute.VirtualMachineScaleSetVM, error) { serviceName := getServiceName(service) name := mapNodeNameToVMName(nodeName) vmssFlexName, err := fs.getNodeVmssFlexName(ctx, name) @@ -474,12 +476,12 @@ func (fs *FlexScaleSet) EnsureHostInPool(ctx context.Context, service *v1.Servic return "", "", "", nil, err } - if nic.ProvisioningState == consts.NicFailedState { + if *nic.Properties.ProvisioningState == consts.NicFailedState { klog.Warningf("EnsureHostInPool skips node %s because its primary nic %s is in Failed state", nodeName, *nic.Name) return "", "", "", nil, nil } - var primaryIPConfig *network.InterfaceIPConfiguration + var primaryIPConfig *armnetwork.InterfaceIPConfiguration ipv6 := isBackendPoolIPv6(backendPoolID) if !fs.Cloud.ipv6DualStackEnabled && !ipv6 { primaryIPConfig, err = getPrimaryIPConfig(nic) @@ -494,9 +496,9 @@ func (fs *FlexScaleSet) EnsureHostInPool(ctx context.Context, service *v1.Servic } foundPool := false - newBackendPools := []network.BackendAddressPool{} - if primaryIPConfig.LoadBalancerBackendAddressPools != nil { - newBackendPools = *primaryIPConfig.LoadBalancerBackendAddressPools + newBackendPools := []*armnetwork.BackendAddressPool{} + if primaryIPConfig.Properties.LoadBalancerBackendAddressPools != nil { + newBackendPools = primaryIPConfig.Properties.LoadBalancerBackendAddressPools } for _, existingPool := range newBackendPools { if strings.EqualFold(backendPoolID, *existingPool.ID) { @@ -531,11 +533,11 @@ func (fs *FlexScaleSet) EnsureHostInPool(ctx context.Context, service *v1.Servic } newBackendPools = append(newBackendPools, - network.BackendAddressPool{ + &armnetwork.BackendAddressPool{ ID: ptr.To(backendPoolID), }) - primaryIPConfig.LoadBalancerBackendAddressPools = &newBackendPools + primaryIPConfig.Properties.LoadBalancerBackendAddressPools = newBackendPools nicName := *nic.Name klog.V(3).Infof("nicupdate(%s): nic(%s) - updating", serviceName, nicName) @@ -615,16 +617,16 @@ func (fs *FlexScaleSet) ensureVMSSFlexInPool(ctx context.Context, _ *v1.Service, // When vmss is being deleted, CreateOrUpdate API would report "the vmss is being deleted" error. // Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it. - if vmssFlex.ProvisioningState != nil && strings.EqualFold(*vmssFlex.ProvisioningState, consts.ProvisionStateDeleting) { + if vmssFlex.Properties.ProvisioningState != nil && strings.EqualFold(*vmssFlex.Properties.ProvisioningState, consts.ProvisionStateDeleting) { klog.V(3).Infof("ensureVMSSFlexInPool: found vmss %s being deleted, skipping", vmssFlexID) continue } - if vmssFlex.VirtualMachineProfile == nil || vmssFlex.VirtualMachineProfile.NetworkProfile == nil || vmssFlex.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == nil { + if vmssFlex.Properties.VirtualMachineProfile == nil || vmssFlex.Properties.VirtualMachineProfile.NetworkProfile == nil || vmssFlex.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == nil { klog.V(4).Infof("ensureVMSSFlexInPool: cannot obtain the primary network interface configuration of vmss %s, just skip it as it might not have default vm profile", vmssFlexID) continue } - vmssNIC := *vmssFlex.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations + vmssNIC := vmssFlex.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations primaryNIC, err := getPrimaryNetworkInterfaceConfiguration(vmssNIC, vmssFlexName) if err != nil { return err @@ -634,9 +636,9 @@ func (fs *FlexScaleSet) ensureVMSSFlexInPool(ctx context.Context, _ *v1.Service, return err } - loadBalancerBackendAddressPools := []compute.SubResource{} - if primaryIPConfig.LoadBalancerBackendAddressPools != nil { - loadBalancerBackendAddressPools = *primaryIPConfig.LoadBalancerBackendAddressPools + loadBalancerBackendAddressPools := []*armcompute.SubResource{} + if primaryIPConfig.Properties.LoadBalancerBackendAddressPools != nil { + loadBalancerBackendAddressPools = primaryIPConfig.Properties.LoadBalancerBackendAddressPools } var found bool @@ -673,17 +675,17 @@ func (fs *FlexScaleSet) ensureVMSSFlexInPool(ctx context.Context, _ *v1.Service, // Compose a new vmss with added backendPoolID. loadBalancerBackendAddressPools = append(loadBalancerBackendAddressPools, - compute.SubResource{ + &armcompute.SubResource{ ID: ptr.To(backendPoolID), }) - primaryIPConfig.LoadBalancerBackendAddressPools = &loadBalancerBackendAddressPools - newVMSS := compute.VirtualMachineScaleSet{ + primaryIPConfig.Properties.LoadBalancerBackendAddressPools = loadBalancerBackendAddressPools + newVMSS := armcompute.VirtualMachineScaleSet{ Location: vmssFlex.Location, - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{ - NetworkProfile: &compute.VirtualMachineScaleSetNetworkProfile{ - NetworkInterfaceConfigurations: &vmssNIC, - NetworkAPIVersion: compute.TwoZeroTwoZeroHyphenMinusOneOneHyphenMinusZeroOne, + Properties: &armcompute.VirtualMachineScaleSetProperties{ + VirtualMachineProfile: &armcompute.VirtualMachineScaleSetVMProfile{ + NetworkProfile: &armcompute.VirtualMachineScaleSetNetworkProfile{ + NetworkInterfaceConfigurations: vmssNIC, + NetworkAPIVersion: to.Ptr(armcompute.NetworkAPIVersionTwoThousandTwenty1101), }, }, }, @@ -697,7 +699,7 @@ func (fs *FlexScaleSet) ensureVMSSFlexInPool(ctx context.Context, _ *v1.Service, rerr := fs.CreateOrUpdateVMSS(fs.ResourceGroup, vmssFlexName, newVMSS) if rerr != nil { klog.Errorf("ensureVMSSFlexInPool CreateOrUpdateVMSS(%s) with new backendPoolID %s, err: %v", vmssFlexName, backendPoolID, err) - return rerr.Error() + return rerr } } return nil @@ -764,7 +766,7 @@ func (fs *FlexScaleSet) ensureBackendPoolDeletedFromVmssFlex(ctx context.Context } vmssFlexes := cached.(*sync.Map) vmssFlexes.Range(func(_, value interface{}) bool { - vmssFlex := value.(*compute.VirtualMachineScaleSet) + vmssFlex := value.(*armcompute.VirtualMachineScaleSet) vmssNamesMap[ptr.Deref(vmssFlex.Name, "")] = true return true }) @@ -789,15 +791,15 @@ func (fs *FlexScaleSet) EnsureBackendPoolDeletedFromVMSets(ctx context.Context, // When vmss is being deleted, CreateOrUpdate API would report "the vmss is being deleted" error. // Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it. - if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.ProvisionStateDeleting) { + if vmss.Properties.ProvisioningState != nil && strings.EqualFold(*vmss.Properties.ProvisioningState, consts.ProvisionStateDeleting) { klog.V(3).Infof("fs.EnsureBackendPoolDeletedFromVMSets: found vmss %s being deleted, skipping", vmssName) continue } - if vmss.VirtualMachineProfile == nil || vmss.VirtualMachineProfile.NetworkProfile == nil || vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == nil { + if vmss.Properties.VirtualMachineProfile == nil || vmss.Properties.VirtualMachineProfile.NetworkProfile == nil || vmss.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == nil { klog.V(4).Infof("fs.EnsureBackendPoolDeletedFromVMSets: cannot obtain the primary network interface configurations, of vmss %s", vmssName) continue } - vmssNIC := *vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations + vmssNIC := vmss.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations primaryNIC, err := getPrimaryNetworkInterfaceConfiguration(vmssNIC, vmssName) if err != nil { klog.Errorf("fs.EnsureBackendPoolDeletedFromVMSets: failed to get the primary network interface config of the VMSS %s: %v", vmssName, err) @@ -821,13 +823,13 @@ func (fs *FlexScaleSet) EnsureBackendPoolDeletedFromVMSets(ctx context.Context, vmssUpdaters = append(vmssUpdaters, func() error { // Compose a new vmss with added backendPoolID. - newVMSS := compute.VirtualMachineScaleSet{ + newVMSS := armcompute.VirtualMachineScaleSet{ Location: vmss.Location, - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{ - NetworkProfile: &compute.VirtualMachineScaleSetNetworkProfile{ - NetworkInterfaceConfigurations: &vmssNIC, - NetworkAPIVersion: compute.TwoZeroTwoZeroHyphenMinusOneOneHyphenMinusZeroOne, + Properties: &armcompute.VirtualMachineScaleSetProperties{ + VirtualMachineProfile: &armcompute.VirtualMachineScaleSetVMProfile{ + NetworkProfile: &armcompute.VirtualMachineScaleSetNetworkProfile{ + NetworkInterfaceConfigurations: vmssNIC, + NetworkAPIVersion: to.Ptr(armcompute.NetworkAPIVersionTwoThousandTwenty1101), }, }, }, @@ -841,7 +843,7 @@ func (fs *FlexScaleSet) EnsureBackendPoolDeletedFromVMSets(ctx context.Context, rerr := fs.CreateOrUpdateVMSS(fs.ResourceGroup, vmssName, newVMSS) if rerr != nil { klog.Errorf("fs.EnsureBackendPoolDeletedFromVMSets CreateOrUpdateVMSS(%s) for backendPoolIDs %q, err: %v", vmssName, backendPoolIDs, rerr) - return rerr.Error() + return rerr } return nil @@ -861,7 +863,7 @@ func (fs *FlexScaleSet) EnsureBackendPoolDeletedFromVMSets(ctx context.Context, } // EnsureBackendPoolDeleted ensures the loadBalancer backendAddressPools deleted from the specified nodes. -func (fs *FlexScaleSet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Service, backendPoolIDs []string, vmSetName string, backendAddressPools *[]network.BackendAddressPool, deleteFromVMSet bool) (bool, error) { +func (fs *FlexScaleSet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Service, backendPoolIDs []string, vmSetName string, backendAddressPools []*armnetwork.BackendAddressPool, deleteFromVMSet bool) (bool, error) { // Returns nil if backend address pools already deleted. if backendAddressPools == nil { return false, nil @@ -874,10 +876,10 @@ func (fs *FlexScaleSet) EnsureBackendPoolDeleted(ctx context.Context, service *v }() ipConfigurationIDs := []string{} - for _, backendPool := range *backendAddressPools { + for _, backendPool := range backendAddressPools { for _, backendPoolID := range backendPoolIDs { - if strings.EqualFold(ptr.Deref(backendPool.ID, ""), backendPoolID) && backendPool.BackendAddressPoolPropertiesFormat != nil && backendPool.BackendIPConfigurations != nil { - for _, ipConf := range *backendPool.BackendIPConfigurations { + if strings.EqualFold(ptr.Deref(backendPool.ID, ""), backendPoolID) && backendPool.Properties != nil && backendPool.Properties.BackendIPConfigurations != nil { + for _, ipConf := range backendPool.Properties.BackendIPConfigurations { if ipConf.ID == nil { continue } @@ -945,23 +947,23 @@ func (fs *FlexScaleSet) EnsureBackendPoolDeleted(ctx context.Context, service *v func (fs *FlexScaleSet) ensureBackendPoolDeletedFromNode(ctx context.Context, vmssFlexVMNameMap map[string]string, backendPoolIDs []string) (bool, error) { nicUpdaters := make([]func() error, 0) allErrs := make([]error, 0) - nics := map[string]network.Interface{} // nicName -> nic + nics := map[string]*armnetwork.Interface{} // nicName -> nic for nodeName, nicName := range vmssFlexVMNameMap { if _, ok := nics[nicName]; ok { continue } - nic, rerr := fs.InterfacesClient.Get(ctx, fs.ResourceGroup, nicName, "") + nic, rerr := fs.NetworkClientFactory.GetInterfaceClient().Get(ctx, fs.ResourceGroup, nicName, nil) if rerr != nil { - return false, fmt.Errorf("ensureBackendPoolDeletedFromNode: failed to get interface of name %s: %w", nicName, rerr.Error()) + return false, fmt.Errorf("ensureBackendPoolDeletedFromNode: failed to get interface of name %s: %w", nicName, rerr) } - if nic.ProvisioningState == consts.NicFailedState { + if *nic.Properties.ProvisioningState == consts.NicFailedState { klog.Warningf("EnsureBackendPoolDeleted skips node %s because its primary nic %s is in Failed state", nodeName, *nic.Name) continue } - if nic.InterfacePropertiesFormat != nil && nic.InterfacePropertiesFormat.IPConfigurations != nil { + if nic.Properties != nil && nic.Properties.IPConfigurations != nil { nicName := ptr.Deref(nic.Name, "") nics[nicName] = nic } @@ -969,14 +971,14 @@ func (fs *FlexScaleSet) ensureBackendPoolDeletedFromNode(ctx context.Context, vm var nicUpdated atomic.Bool for _, nic := range nics { nic := nic - newIPConfigs := *nic.IPConfigurations + newIPConfigs := nic.Properties.IPConfigurations for j, ipConf := range newIPConfigs { - if !ptr.Deref(ipConf.Primary, false) { + if !ptr.Deref(ipConf.Properties.Primary, false) { continue } // found primary ip configuration - if ipConf.LoadBalancerBackendAddressPools != nil { - newLBAddressPools := *ipConf.LoadBalancerBackendAddressPools + if ipConf.Properties.LoadBalancerBackendAddressPools != nil { + newLBAddressPools := ipConf.Properties.LoadBalancerBackendAddressPools for k := len(newLBAddressPools) - 1; k >= 0; k-- { pool := newLBAddressPools[k] for _, backendPoolID := range backendPoolIDs { @@ -985,17 +987,17 @@ func (fs *FlexScaleSet) ensureBackendPoolDeletedFromNode(ctx context.Context, vm } } } - newIPConfigs[j].LoadBalancerBackendAddressPools = &newLBAddressPools + newIPConfigs[j].Properties.LoadBalancerBackendAddressPools = newLBAddressPools } } - nic.IPConfigurations = &newIPConfigs + nic.Properties.IPConfigurations = newIPConfigs nicUpdaters = append(nicUpdaters, func() error { klog.V(2).Infof("EnsureBackendPoolDeleted begins to CreateOrUpdate for NIC(%s, %s) with backendPoolIDs %q", fs.ResourceGroup, ptr.Deref(nic.Name, ""), backendPoolIDs) - rerr := fs.InterfacesClient.CreateOrUpdate(ctx, fs.ResourceGroup, ptr.Deref(nic.Name, ""), nic) + _, rerr := fs.NetworkClientFactory.GetInterfaceClient().CreateOrUpdate(ctx, fs.ResourceGroup, ptr.Deref(nic.Name, ""), *nic) if rerr != nil { klog.Errorf("EnsureBackendPoolDeleted CreateOrUpdate for NIC(%s, %s) failed with error %v", fs.ResourceGroup, ptr.Deref(nic.Name, ""), rerr.Error()) - return rerr.Error() + return rerr } nicUpdated.Store(true) klog.V(2).Infof("EnsureBackendPoolDeleted done") diff --git a/pkg/provider/azure_vmssflex_cache.go b/pkg/provider/azure_vmssflex_cache.go index 59c423a8ad..a11d3f0daf 100644 --- a/pkg/provider/azure_vmssflex_cache.go +++ b/pkg/provider/azure_vmssflex_cache.go @@ -24,14 +24,14 @@ import ( "sync" "time" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" + "sigs.k8s.io/cloud-provider-azure/pkg/util/errutils" ) func (fs *FlexScaleSet) newVmssFlexCache() (azcache.Resource, error) { @@ -44,14 +44,14 @@ func (fs *FlexScaleSet) newVmssFlexCache() (azcache.Resource, error) { } for _, resourceGroup := range allResourceGroups.UnsortedList() { - allScaleSets, rerr := fs.VirtualMachineScaleSetsClient.List(ctx, resourceGroup) + allScaleSets, rerr := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().List(ctx, resourceGroup) if rerr != nil { - if rerr.IsNotFound() { + if exists, err := errutils.CheckResourceExistsFromAzcoreError(rerr); !exists && err == nil { klog.Warningf("Skip caching vmss for resource group %s due to error: %v", resourceGroup, rerr.Error()) continue } klog.Errorf("VirtualMachineScaleSetsClient.List failed: %v", rerr) - return nil, rerr.Error() + return nil, rerr } for i := range allScaleSets { @@ -61,8 +61,8 @@ func (fs *FlexScaleSet) newVmssFlexCache() (azcache.Resource, error) { continue } - if scaleSet.OrchestrationMode == compute.Flexible { - localCache.Store(*scaleSet.ID, &scaleSet) + if *scaleSet.Properties.OrchestrationMode == armcompute.OrchestrationModeFlexible { + localCache.Store(*scaleSet.ID, scaleSet) } } } @@ -80,25 +80,25 @@ func (fs *FlexScaleSet) newVmssFlexVMCache() (azcache.Resource, error) { getter := func(ctx context.Context, key string) (interface{}, error) { localCache := &sync.Map{} - vms, rerr := fs.VirtualMachinesClient.ListVmssFlexVMsWithoutInstanceView(ctx, key) + vms, rerr := fs.ComputeClientFactory.GetVirtualMachineClient().List(ctx, key) if rerr != nil { - klog.Errorf("ListVmssFlexVMsWithoutInstanceView failed: %v", rerr) - return nil, rerr.Error() + klog.Errorf("List failed: %v", rerr) + return nil, rerr } for i := range vms { vm := vms[i] - if vm.OsProfile != nil && vm.OsProfile.ComputerName != nil { - localCache.Store(strings.ToLower(*vm.OsProfile.ComputerName), &vm) - fs.vmssFlexVMNameToVmssID.Store(strings.ToLower(*vm.OsProfile.ComputerName), key) - fs.vmssFlexVMNameToNodeName.Store(*vm.Name, strings.ToLower(*vm.OsProfile.ComputerName)) + if vm.Properties.OSProfile != nil && vm.Properties.OSProfile.ComputerName != nil { + localCache.Store(strings.ToLower(*vm.Properties.OSProfile.ComputerName), vm) + fs.vmssFlexVMNameToVmssID.Store(strings.ToLower(*vm.Properties.OSProfile.ComputerName), key) + fs.vmssFlexVMNameToNodeName.Store(*vm.Name, strings.ToLower(*vm.Properties.OSProfile.ComputerName)) } } - vms, rerr = fs.VirtualMachinesClient.ListVmssFlexVMsWithOnlyInstanceView(ctx, key) + vms, rerr = fs.ComputeClientFactory.GetVirtualMachineClient().ListVMInstanceView(ctx, key) if rerr != nil { - klog.Errorf("ListVmssFlexVMsWithOnlyInstanceView failed: %v", rerr) - return nil, rerr.Error() + klog.Errorf("ListVMInstanceView failed: %v", rerr) + return nil, rerr } for i := range vms { @@ -111,8 +111,8 @@ func (fs *FlexScaleSet) newVmssFlexVMCache() (azcache.Resource, error) { cached, ok := localCache.Load(nodeName) if ok { - cachedVM := cached.(*compute.VirtualMachine) - cachedVM.VirtualMachineProperties.InstanceView = vm.VirtualMachineProperties.InstanceView + cachedVM := cached.(*armcompute.VirtualMachine) + cachedVM.Properties.InstanceView = vm.Properties.InstanceView } } } @@ -185,12 +185,12 @@ func (fs *FlexScaleSet) getNodeVmssFlexID(ctx context.Context, nodeName string) var vmssFlexIDs []string vmssFlexes.Range(func(key, value interface{}) bool { vmssFlexID := key.(string) - vmssFlex := value.(*compute.VirtualMachineScaleSet) + vmssFlex := value.(*armcompute.VirtualMachineScaleSet) vmssPrefix := ptr.Deref(vmssFlex.Name, "") - if vmssFlex.VirtualMachineProfile != nil && - vmssFlex.VirtualMachineProfile.OsProfile != nil && - vmssFlex.VirtualMachineProfile.OsProfile.ComputerNamePrefix != nil { - vmssPrefix = ptr.Deref(vmssFlex.VirtualMachineProfile.OsProfile.ComputerNamePrefix, "") + if vmssFlex.Properties.VirtualMachineProfile != nil && + vmssFlex.Properties.VirtualMachineProfile.OSProfile != nil && + vmssFlex.Properties.VirtualMachineProfile.OSProfile.ComputerNamePrefix != nil { + vmssPrefix = ptr.Deref(vmssFlex.Properties.VirtualMachineProfile.OSProfile.ComputerNamePrefix, "") } if strings.EqualFold(vmssPrefix, nodeName[:len(nodeName)-6]) { // we should check this vmss first since nodeName and vmssFlex.Name or @@ -224,7 +224,7 @@ func (fs *FlexScaleSet) getNodeVmssFlexID(ctx context.Context, nodeName string) } -func (fs *FlexScaleSet) getVmssFlexVM(ctx context.Context, nodeName string, crt azcache.AzureCacheReadType) (vm compute.VirtualMachine, err error) { +func (fs *FlexScaleSet) getVmssFlexVM(ctx context.Context, nodeName string, crt azcache.AzureCacheReadType) (vm *armcompute.VirtualMachine, err error) { vmssFlexID, err := fs.getNodeVmssFlexID(ctx, nodeName) if err != nil { return vm, err @@ -241,17 +241,17 @@ func (fs *FlexScaleSet) getVmssFlexVM(ctx context.Context, nodeName string, crt return vm, cloudprovider.InstanceNotFound } - return *(cachedVM.(*compute.VirtualMachine)), nil + return (cachedVM.(*armcompute.VirtualMachine)), nil } -func (fs *FlexScaleSet) getVmssFlexByVmssFlexID(ctx context.Context, vmssFlexID string, crt azcache.AzureCacheReadType) (*compute.VirtualMachineScaleSet, error) { +func (fs *FlexScaleSet) getVmssFlexByVmssFlexID(ctx context.Context, vmssFlexID string, crt azcache.AzureCacheReadType) (*armcompute.VirtualMachineScaleSet, error) { cached, err := fs.vmssFlexCache.Get(ctx, consts.VmssFlexKey, crt) if err != nil { return nil, err } vmssFlexes := cached.(*sync.Map) if vmssFlex, ok := vmssFlexes.Load(vmssFlexID); ok { - result := vmssFlex.(*compute.VirtualMachineScaleSet) + result := vmssFlex.(*armcompute.VirtualMachineScaleSet) return result, nil } @@ -262,13 +262,13 @@ func (fs *FlexScaleSet) getVmssFlexByVmssFlexID(ctx context.Context, vmssFlexID } vmssFlexes = cached.(*sync.Map) if vmssFlex, ok := vmssFlexes.Load(vmssFlexID); ok { - result := vmssFlex.(*compute.VirtualMachineScaleSet) + result := vmssFlex.(*armcompute.VirtualMachineScaleSet) return result, nil } return nil, cloudprovider.InstanceNotFound } -func (fs *FlexScaleSet) getVmssFlexByNodeName(ctx context.Context, nodeName string, crt azcache.AzureCacheReadType) (*compute.VirtualMachineScaleSet, error) { +func (fs *FlexScaleSet) getVmssFlexByNodeName(ctx context.Context, nodeName string, crt azcache.AzureCacheReadType) (*armcompute.VirtualMachineScaleSet, error) { vmssFlexID, err := fs.getNodeVmssFlexID(ctx, nodeName) if err != nil { return nil, err @@ -305,17 +305,17 @@ func (fs *FlexScaleSet) getVmssFlexIDByName(ctx context.Context, vmssFlexName st return "", cloudprovider.InstanceNotFound } -func (fs *FlexScaleSet) getVmssFlexByName(ctx context.Context, vmssFlexName string) (*compute.VirtualMachineScaleSet, error) { +func (fs *FlexScaleSet) getVmssFlexByName(ctx context.Context, vmssFlexName string) (*armcompute.VirtualMachineScaleSet, error) { cached, err := fs.vmssFlexCache.Get(ctx, consts.VmssFlexKey, azcache.CacheReadTypeDefault) if err != nil { return nil, err } - var targetVmssFlex *compute.VirtualMachineScaleSet + var targetVmssFlex *armcompute.VirtualMachineScaleSet vmssFlexes := cached.(*sync.Map) vmssFlexes.Range(func(key, value interface{}) bool { vmssFlexID := key.(string) - vmssFlex := value.(*compute.VirtualMachineScaleSet) + vmssFlex := value.(*armcompute.VirtualMachineScaleSet) name, err := getLastSegment(vmssFlexID, "/") if err != nil { return true diff --git a/pkg/provider/azure_vmssflex_cache_test.go b/pkg/provider/azure_vmssflex_cache_test.go index 3bf2e0b2f5..70b38cda0c 100644 --- a/pkg/provider/azure_vmssflex_cache_test.go +++ b/pkg/provider/azure_vmssflex_cache_test.go @@ -22,19 +22,18 @@ import ( "net/http" "testing" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - cloudprovider "k8s.io/cloud-provider" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/mock_virtualmachinescalesetclient" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) var ( @@ -47,9 +46,9 @@ var ( ComputerName: "vmssflex1000001", ProvisioningState: ptr.To("Succeeded"), VmssFlexID: testVmssFlex1ID, - Zones: &[]string{"1", "2", "3"}, + Zones: to.SliceOfPtrs("1", "2", "3"), PlatformFaultDomain: ptr.To(int32(1)), - Status: &[]compute.InstanceViewStatus{ + Status: []*armcompute.InstanceViewStatus{ { Code: ptr.To("PowerState/running"), }, @@ -67,7 +66,7 @@ var ( VmssFlexID: testVmssFlex1ID, Zones: nil, PlatformFaultDomain: ptr.To(int32(1)), - Status: &[]compute.InstanceViewStatus{ + Status: []*armcompute.InstanceViewStatus{ { Code: ptr.To("PowerState/running"), }, @@ -85,7 +84,7 @@ var ( VmssFlexID: testVmssFlex1ID, Zones: nil, PlatformFaultDomain: nil, - Status: &[]compute.InstanceViewStatus{}, + Status: []*armcompute.InstanceViewStatus{}, NicID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/testvm3-nic", } @@ -98,35 +97,35 @@ var ( testVmssFlexList = genreateTestVmssFlexList() ) -func generateTestVMListWithoutInstanceView() []compute.VirtualMachine { - return []compute.VirtualMachine{generateVmssFlexTestVMWithoutInstanceView(testVM1Spec), generateVmssFlexTestVMWithoutInstanceView(testVM2Spec), generateVmssFlexTestVMWithoutInstanceView(testVM3Spec)} +func generateTestVMListWithoutInstanceView() []*armcompute.VirtualMachine { + return []*armcompute.VirtualMachine{generateVmssFlexTestVMWithoutInstanceView(testVM1Spec), generateVmssFlexTestVMWithoutInstanceView(testVM2Spec), generateVmssFlexTestVMWithoutInstanceView(testVM3Spec)} } -func generateTestVMListWithOnlyInstanceView() []compute.VirtualMachine { - return []compute.VirtualMachine{generateVmssFlexTestVMWithOnlyInstanceView(testVM1Spec), generateVmssFlexTestVMWithOnlyInstanceView(testVM2Spec), generateVmssFlexTestVMWithOnlyInstanceView(testVM3Spec)} +func generateTestVMListWithOnlyInstanceView() []*armcompute.VirtualMachine { + return []*armcompute.VirtualMachine{generateVmssFlexTestVMWithOnlyInstanceView(testVM1Spec), generateVmssFlexTestVMWithOnlyInstanceView(testVM2Spec), generateVmssFlexTestVMWithOnlyInstanceView(testVM3Spec)} } -func genreateTestVmssFlexList() []compute.VirtualMachineScaleSet { - return []compute.VirtualMachineScaleSet{genreteTestVmssFlex("vmssflex1", testVmssFlex1ID)} +func genreateTestVmssFlexList() []*armcompute.VirtualMachineScaleSet { + return []*armcompute.VirtualMachineScaleSet{genreteTestVmssFlex("vmssflex1", testVmssFlex1ID)} } -func genreteTestVmssFlex(vmssFlexName string, testVmssFlexID string) compute.VirtualMachineScaleSet { - return compute.VirtualMachineScaleSet{ +func genreteTestVmssFlex(vmssFlexName string, testVmssFlexID string) *armcompute.VirtualMachineScaleSet { + return &armcompute.VirtualMachineScaleSet{ ID: ptr.To(testVmssFlexID), Name: ptr.To(vmssFlexName), - VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{ - OsProfile: &compute.VirtualMachineScaleSetOSProfile{ + Properties: &armcompute.VirtualMachineScaleSetProperties{ + VirtualMachineProfile: &armcompute.VirtualMachineScaleSetVMProfile{ + OSProfile: &armcompute.VirtualMachineScaleSetOSProfile{ ComputerNamePrefix: ptr.To(vmssFlexName), }, - NetworkProfile: &compute.VirtualMachineScaleSetNetworkProfile{ - NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{ + NetworkProfile: &armcompute.VirtualMachineScaleSetNetworkProfile{ + NetworkInterfaceConfigurations: []*armcompute.VirtualMachineScaleSetNetworkConfiguration{ { - VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ + Properties: &armcompute.VirtualMachineScaleSetNetworkConfigurationProperties{ + IPConfigurations: []*armcompute.VirtualMachineScaleSetIPConfiguration{ { - VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - LoadBalancerBackendAddressPools: &[]compute.SubResource{ + Properties: &armcompute.VirtualMachineScaleSetIPConfigurationProperties{ + LoadBalancerBackendAddressPools: []*armcompute.SubResource{ { ID: ptr.To(testBackendPoolID0), }, @@ -140,7 +139,7 @@ func genreteTestVmssFlex(vmssFlexName string, testVmssFlexID string) compute.Vir }, }, }, - OrchestrationMode: compute.Flexible, + OrchestrationMode: to.Ptr(armcompute.OrchestrationModeFlexible), }, Tags: map[string]*string{ consts.VMSetCIDRIPV4TagKey: ptr.To("24"), @@ -155,47 +154,47 @@ type VmssFlexTestVMSpec struct { ComputerName string ProvisioningState *string VmssFlexID string - Zones *[]string + Zones []*string PlatformFaultDomain *int32 - Status *[]compute.InstanceViewStatus + Status []*armcompute.InstanceViewStatus NicID string } -func generateVmssFlexTestVMWithoutInstanceView(spec VmssFlexTestVMSpec) (testVMWithoutInstanceView compute.VirtualMachine) { - return compute.VirtualMachine{ +func generateVmssFlexTestVMWithoutInstanceView(spec VmssFlexTestVMSpec) (testVMWithoutInstanceView *armcompute.VirtualMachine) { + return &armcompute.VirtualMachine{ Name: ptr.To(spec.VMName), ID: ptr.To(spec.VMID), - VirtualMachineProperties: &compute.VirtualMachineProperties{ - OsProfile: &compute.OSProfile{ + Properties: &armcompute.VirtualMachineProperties{ + OSProfile: &armcompute.OSProfile{ ComputerName: ptr.To(spec.ComputerName), }, ProvisioningState: spec.ProvisioningState, - VirtualMachineScaleSet: &compute.SubResource{ + VirtualMachineScaleSet: &armcompute.SubResource{ ID: ptr.To(spec.VmssFlexID), }, - StorageProfile: &compute.StorageProfile{ - OsDisk: &compute.OSDisk{ - Name: ptr.To("osdisk" + spec.VMName), - ManagedDisk: &compute.ManagedDiskParameters{ + StorageProfile: &armcompute.StorageProfile{ + OSDisk: &armcompute.OSDisk{ + Name: ptr.To("OSDisk" + spec.VMName), + ManagedDisk: &armcompute.ManagedDiskParameters{ ID: ptr.To("ManagedID" + spec.VMName), - DiskEncryptionSet: &compute.DiskEncryptionSetParameters{ + DiskEncryptionSet: &armcompute.DiskEncryptionSetParameters{ ID: ptr.To("DiskEncryptionSetID" + spec.VMName), }, }, }, - DataDisks: &[]compute.DataDisk{ + DataDisks: []*armcompute.DataDisk{ { Lun: ptr.To(int32(1)), Name: ptr.To("dataDisk" + spec.VMName), - ManagedDisk: &compute.ManagedDiskParameters{ID: ptr.To("uri")}, + ManagedDisk: &armcompute.ManagedDiskParameters{ID: ptr.To("uri")}, }, }, }, - HardwareProfile: &compute.HardwareProfile{ - VMSize: compute.StandardD2sV3, + HardwareProfile: &armcompute.HardwareProfile{ + VMSize: to.Ptr(armcompute.VirtualMachineSizeTypesStandardD2SV3), }, - NetworkProfile: &compute.NetworkProfile{ - NetworkInterfaces: &[]compute.NetworkInterfaceReference{ + NetworkProfile: &armcompute.NetworkProfile{ + NetworkInterfaces: []*armcompute.NetworkInterfaceReference{ { ID: ptr.To(spec.NicID), }, @@ -207,12 +206,12 @@ func generateVmssFlexTestVMWithoutInstanceView(spec VmssFlexTestVMSpec) (testVMW } } -func generateVmssFlexTestVMWithOnlyInstanceView(spec VmssFlexTestVMSpec) (testVMWithOnlyInstanceView compute.VirtualMachine) { - return compute.VirtualMachine{ +func generateVmssFlexTestVMWithOnlyInstanceView(spec VmssFlexTestVMSpec) (testVMWithOnlyInstanceView *armcompute.VirtualMachine) { + return &armcompute.VirtualMachine{ Name: ptr.To(spec.VMName), ID: ptr.To(spec.VMID), - VirtualMachineProperties: &compute.VirtualMachineProperties{ - InstanceView: &compute.VirtualMachineInstanceView{ + Properties: &armcompute.VirtualMachineProperties{ + InstanceView: &armcompute.VirtualMachineInstanceView{ PlatformFaultDomain: spec.PlatformFaultDomain, Statuses: spec.Status, }, @@ -220,21 +219,19 @@ func generateVmssFlexTestVMWithOnlyInstanceView(spec VmssFlexTestVMSpec) (testVM } } -func generateVmssFlexTestVM(spec VmssFlexTestVMSpec) compute.VirtualMachine { +func generateVmssFlexTestVM(spec VmssFlexTestVMSpec) *armcompute.VirtualMachine { testVM := generateVmssFlexTestVMWithoutInstanceView(spec) - testVM.InstanceView = generateVmssFlexTestVMWithOnlyInstanceView(spec).InstanceView + testVM.Properties.InstanceView = generateVmssFlexTestVMWithOnlyInstanceView(spec).Properties.InstanceView return testVM } func TestGetNodeNameByVMName(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string vmName string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error expectedNodeName string expectedErr error @@ -251,8 +248,8 @@ func TestGetNodeNameByVMName(t *testing.T) { { description: "getNodeVmssFlexID should throw InstanceNotFound error if the VM cannot be found", vmName: nonExistingNodeName, - testVMListWithoutInstanceView: []compute.VirtualMachine{}, - testVMListWithOnlyInstanceView: []compute.VirtualMachine{}, + testVMListWithoutInstanceView: []*armcompute.VirtualMachine{}, + testVMListWithOnlyInstanceView: []*armcompute.VirtualMachine{}, vmListErr: nil, expectedNodeName: "", expectedErr: cloudprovider.InstanceNotFound, @@ -260,31 +257,35 @@ func TestGetNodeNameByVMName(t *testing.T) { } for _, tc := range testCases { - fs, err := NewTestFlexScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() + fs, err := NewTestFlexScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - nodeName, err := fs.getNodeNameByVMName(context.TODO(), tc.vmName) - assert.Equal(t, tc.expectedErr, err, tc.description) - assert.Equal(t, tc.expectedNodeName, nodeName, tc.description) + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + + nodeName, err := fs.getNodeNameByVMName(context.TODO(), tc.vmName) + assert.Equal(t, tc.expectedErr, err, tc.description) + assert.Equal(t, tc.expectedNodeName, nodeName, tc.description) + }) } } func TestGetNodeVmssFlexID(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string nodeName string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error expectedVmssFlexID string expectedErr error @@ -301,8 +302,8 @@ func TestGetNodeVmssFlexID(t *testing.T) { { description: "getNodeVmssFlexID should throw InstanceNotFound error if the VM cannot be found", nodeName: "NonExistingNodeName", - testVMListWithoutInstanceView: []compute.VirtualMachine{}, - testVMListWithOnlyInstanceView: []compute.VirtualMachine{}, + testVMListWithoutInstanceView: []*armcompute.VirtualMachine{}, + testVMListWithOnlyInstanceView: []*armcompute.VirtualMachine{}, vmListErr: nil, expectedVmssFlexID: "", expectedErr: cloudprovider.InstanceNotFound, @@ -310,34 +311,38 @@ func TestGetNodeVmssFlexID(t *testing.T) { } for _, tc := range testCases { - fs, err := NewTestFlexScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + fs, err := NewTestFlexScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() - vmssFlexID, err := fs.getNodeVmssFlexID(context.TODO(), tc.nodeName) - assert.Equal(t, tc.expectedErr, err, tc.description) - assert.Equal(t, tc.expectedVmssFlexID, vmssFlexID, tc.description) + vmssFlexID, err := fs.getNodeVmssFlexID(context.TODO(), tc.nodeName) + assert.Equal(t, tc.expectedErr, err, tc.description) + assert.Equal(t, tc.expectedVmssFlexID, vmssFlexID, tc.description) + }) } } func TestGetVmssFlexVM(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string nodeName string - testVM compute.VirtualMachine - vmGetErr *retry.Error - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVM *armcompute.VirtualMachine + vmGetErr error + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error - expectedVmssFlexVM compute.VirtualMachine + expectedVmssFlexVM *armcompute.VirtualMachine expectedErr error }{ { @@ -354,12 +359,12 @@ func TestGetVmssFlexVM(t *testing.T) { { description: "getVmssFlexVM should throw InstanceNotFound error if the VM cannot be found", nodeName: "vmssflex1000001", - testVM: compute.VirtualMachine{}, - vmGetErr: &retry.Error{HTTPStatusCode: http.StatusNotFound}, - testVMListWithoutInstanceView: []compute.VirtualMachine{}, - testVMListWithOnlyInstanceView: []compute.VirtualMachine{}, + testVM: &armcompute.VirtualMachine{}, + vmGetErr: &azcore.ResponseError{StatusCode: http.StatusNotFound}, + testVMListWithoutInstanceView: []*armcompute.VirtualMachine{}, + testVMListWithOnlyInstanceView: []*armcompute.VirtualMachine{}, vmListErr: nil, - expectedVmssFlexVM: compute.VirtualMachine{}, + expectedVmssFlexVM: nil, expectedErr: cloudprovider.InstanceNotFound, }, { @@ -367,28 +372,39 @@ func TestGetVmssFlexVM(t *testing.T) { nodeName: "vmssflex1000001", testVM: testVMWithoutInstanceView1, vmGetErr: nil, - testVMListWithoutInstanceView: []compute.VirtualMachine{testVMWithoutInstanceView2}, - testVMListWithOnlyInstanceView: []compute.VirtualMachine{testVMWithOnlyInstanceView2}, + testVMListWithoutInstanceView: []*armcompute.VirtualMachine{testVMWithoutInstanceView2}, + testVMListWithOnlyInstanceView: []*armcompute.VirtualMachine{testVMWithOnlyInstanceView2}, vmListErr: nil, - expectedVmssFlexVM: compute.VirtualMachine{}, + expectedVmssFlexVM: nil, expectedErr: cloudprovider.InstanceNotFound, }, } for _, tc := range testCases { - fs, err := NewTestFlexScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() - - vmssFlexVM, err := fs.getVmssFlexVM(context.TODO(), tc.nodeName, azcache.CacheReadTypeDefault) - assert.Equal(t, tc.expectedErr, err, tc.description) - assert.Equal(t, tc.expectedVmssFlexVM, vmssFlexVM, tc.description) + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + fs, err := NewTestFlexScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") + + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() + + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + + vmssFlexVM, err := fs.getVmssFlexVM(context.TODO(), tc.nodeName, azcache.CacheReadTypeDefault) + assert.Equal(t, tc.expectedErr, err, tc.description) + if tc.expectedVmssFlexVM != nil { + assert.Equal(t, *tc.expectedVmssFlexVM, *vmssFlexVM, tc.description) + } else { + assert.Nil(t, vmssFlexVM, tc.description) + } + + }) } } @@ -400,9 +416,9 @@ func TestGetVmssFlexByVmssFlexID(t *testing.T) { testCases := []struct { description string vmssFlexID string - testVmssFlexList []compute.VirtualMachineScaleSet - vmssFlexListErr *retry.Error - expectedVmssFlex *compute.VirtualMachineScaleSet + testVmssFlexList []*armcompute.VirtualMachineScaleSet + vmssFlexListErr error + expectedVmssFlex *armcompute.VirtualMachineScaleSet expectedErr error }{ { @@ -410,13 +426,13 @@ func TestGetVmssFlexByVmssFlexID(t *testing.T) { vmssFlexID: "subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmssflex1", testVmssFlexList: testVmssFlexList, vmssFlexListErr: nil, - expectedVmssFlex: &testVmssFlex1, + expectedVmssFlex: testVmssFlex1, expectedErr: nil, }, { description: "getVmssFlexByVmssFlexID should return cloudprovider.InstanceNotFound if there's no matching VMSS", vmssFlexID: "subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmssflex1", - testVmssFlexList: []compute.VirtualMachineScaleSet{}, + testVmssFlexList: []*armcompute.VirtualMachineScaleSet{}, vmssFlexListErr: nil, expectedVmssFlex: nil, expectedErr: cloudprovider.InstanceNotFound, @@ -424,10 +440,10 @@ func TestGetVmssFlexByVmssFlexID(t *testing.T) { { description: "getVmssFlexByVmssFlexID should report an error if there's something wrong during an api call", vmssFlexID: "subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmssflex1", - testVmssFlexList: []compute.VirtualMachineScaleSet{}, - vmssFlexListErr: &retry.Error{RawError: fmt.Errorf("error during vmss list")}, + testVmssFlexList: []*armcompute.VirtualMachineScaleSet{}, + vmssFlexListErr: &azcore.ResponseError{ErrorCode: "error during vmss list"}, expectedVmssFlex: nil, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: error during vmss list"), + expectedErr: fmt.Errorf("error during vmss list"), }, } @@ -435,26 +451,24 @@ func TestGetVmssFlexByVmssFlexID(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVmssFlexList, tc.vmssFlexListErr).AnyTimes() vmssFlex, err := fs.getVmssFlexByVmssFlexID(context.TODO(), tc.vmssFlexID, azcache.CacheReadTypeDefault) if tc.expectedErr != nil { - assert.EqualError(t, tc.expectedErr, err.Error(), tc.description) + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) } assert.Equal(t, tc.expectedVmssFlex, vmssFlex, tc.description) } } func TestGetVmssFlexIDByName(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string vmssFlexName string - testVmssFlexList []compute.VirtualMachineScaleSet - vmssFlexListErr *retry.Error + testVmssFlexList []*armcompute.VirtualMachineScaleSet + vmssFlexListErr error expectedVmssFlexID string expectedErr error }{ @@ -469,7 +483,7 @@ func TestGetVmssFlexIDByName(t *testing.T) { { description: "getVmssFlexIDByName should return cloudprovider.InstanceNotFound if there's no matching VMSS", vmssFlexName: "vmssflex1", - testVmssFlexList: []compute.VirtualMachineScaleSet{}, + testVmssFlexList: []*armcompute.VirtualMachineScaleSet{}, vmssFlexListErr: nil, expectedVmssFlexID: "", expectedErr: cloudprovider.InstanceNotFound, @@ -477,40 +491,43 @@ func TestGetVmssFlexIDByName(t *testing.T) { { description: "getVmssFlexIDByName should report an error if there's something wrong during an api call", vmssFlexName: "vmssflex1", - testVmssFlexList: []compute.VirtualMachineScaleSet{}, - vmssFlexListErr: &retry.Error{RawError: fmt.Errorf("error during vmss list")}, + testVmssFlexList: []*armcompute.VirtualMachineScaleSet{}, + vmssFlexListErr: &azcore.ResponseError{ErrorCode: "error during vmss list"}, expectedVmssFlexID: "", - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: error during vmss list"), + expectedErr: fmt.Errorf("error during vmss list"), }, } for _, tc := range testCases { - fs, err := NewTestFlexScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVmssFlexList, tc.vmssFlexListErr).AnyTimes() + fs, err := NewTestFlexScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - vmssFlexID, err := fs.getVmssFlexIDByName(context.TODO(), tc.vmssFlexName) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVmssFlexList, tc.vmssFlexListErr).AnyTimes() - assert.Equal(t, tc.expectedVmssFlexID, vmssFlexID, tc.description) - if tc.expectedErr != nil { - assert.EqualError(t, tc.expectedErr, err.Error(), tc.description) - } - } + vmssFlexID, err := fs.getVmssFlexIDByName(context.TODO(), tc.vmssFlexName) + assert.Equal(t, tc.expectedVmssFlexID, vmssFlexID, tc.description) + if tc.expectedErr != nil { + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) + } + }) + } } func TestGetVmssFlexByName(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string vmssFlexName string - testVmssFlexList []compute.VirtualMachineScaleSet - vmssFlexListErr *retry.Error - expectedVmssFlex *compute.VirtualMachineScaleSet + testVmssFlexList []*armcompute.VirtualMachineScaleSet + vmssFlexListErr error + expectedVmssFlex *armcompute.VirtualMachineScaleSet expectedErr error }{ { @@ -518,13 +535,13 @@ func TestGetVmssFlexByName(t *testing.T) { vmssFlexName: "vmssflex1", testVmssFlexList: testVmssFlexList, vmssFlexListErr: nil, - expectedVmssFlex: &testVmssFlex1, + expectedVmssFlex: testVmssFlex1, expectedErr: nil, }, { description: "getVmssFlexByName should return cloudprovider.InstanceNotFound if there's no matching VMSS", vmssFlexName: "vmssflex1", - testVmssFlexList: []compute.VirtualMachineScaleSet{}, + testVmssFlexList: []*armcompute.VirtualMachineScaleSet{}, vmssFlexListErr: nil, expectedVmssFlex: nil, expectedErr: cloudprovider.InstanceNotFound, @@ -532,45 +549,49 @@ func TestGetVmssFlexByName(t *testing.T) { { description: "getVmssFlexByName should report an error if there's something wrong during an api call", vmssFlexName: "vmssflex1", - testVmssFlexList: []compute.VirtualMachineScaleSet{}, - vmssFlexListErr: &retry.Error{RawError: fmt.Errorf("error during vmss list")}, + testVmssFlexList: []*armcompute.VirtualMachineScaleSet{}, + vmssFlexListErr: &azcore.ResponseError{ErrorCode: "error during vmss list"}, expectedVmssFlex: nil, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: error during vmss list"), + expectedErr: fmt.Errorf("error during vmss list"), }, } for _, tc := range testCases { - fs, err := NewTestFlexScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVmssFlexList, tc.vmssFlexListErr).AnyTimes() + fs, err := NewTestFlexScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - vmssFlex, err := fs.getVmssFlexByName(context.TODO(), tc.vmssFlexName) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVmssFlexList, tc.vmssFlexListErr).AnyTimes() - assert.Equal(t, tc.expectedVmssFlex, vmssFlex, tc.description) - if tc.expectedErr != nil { - assert.EqualError(t, tc.expectedErr, err.Error(), tc.description) - } + vmssFlex, err := fs.getVmssFlexByName(context.TODO(), tc.vmssFlexName) + + assert.Equal(t, tc.expectedVmssFlex, vmssFlex, tc.description) + if tc.expectedErr != nil { + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) + } + }) } } func TestGetVmssFlexByNodeName(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string nodeName string - testVM compute.VirtualMachine - vmGetErr *retry.Error - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVM *armcompute.VirtualMachine + vmGetErr error + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error - testVmssFlexList []compute.VirtualMachineScaleSet - vmssFlexListErr *retry.Error - expectedVmssFlex *compute.VirtualMachineScaleSet + testVmssFlexList []*armcompute.VirtualMachineScaleSet + vmssFlexListErr error + expectedVmssFlex *armcompute.VirtualMachineScaleSet expectedErr error }{ { @@ -583,25 +604,31 @@ func TestGetVmssFlexByNodeName(t *testing.T) { vmListErr: nil, testVmssFlexList: testVmssFlexList, vmssFlexListErr: nil, - expectedVmssFlex: &testVmssFlex1, + expectedVmssFlex: testVmssFlex1, expectedErr: nil, }, } for _, tc := range testCases { - fs, err := NewTestFlexScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().Get(gomock.Any(), fs.ResourceGroup, tc.nodeName, gomock.Any()).Return(tc.testVM, tc.vmGetErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVmssFlexList, tc.vmssFlexListErr).AnyTimes() - - vmssFlex, err := fs.getVmssFlexByNodeName(context.TODO(), tc.nodeName, azcache.CacheReadTypeDefault) - assert.Equal(t, tc.expectedErr, err, tc.description) - assert.Equal(t, tc.expectedVmssFlex, vmssFlex, tc.description) + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + fs, err := NewTestFlexScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") + + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().Get(gomock.Any(), fs.ResourceGroup, tc.nodeName, gomock.Any()).Return(tc.testVM, tc.vmGetErr).AnyTimes() + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVmssFlexList, tc.vmssFlexListErr).AnyTimes() + + vmssFlex, err := fs.getVmssFlexByNodeName(context.TODO(), tc.nodeName, azcache.CacheReadTypeDefault) + assert.Equal(t, tc.expectedErr, err, tc.description) + assert.Equal(t, tc.expectedVmssFlex, vmssFlex, tc.description) + }) } } diff --git a/pkg/provider/azure_vmssflex_test.go b/pkg/provider/azure_vmssflex_test.go index 0adc72a4ee..d5cc63b79d 100644 --- a/pkg/provider/azure_vmssflex_test.go +++ b/pkg/provider/azure_vmssflex_test.go @@ -22,8 +22,12 @@ import ( "fmt" "testing" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/samber/lo" + "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -34,11 +38,10 @@ import ( cloudprovider "k8s.io/cloud-provider" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/interfaceclient/mock_interfaceclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachinescalesetclient/mock_virtualmachinescalesetclient" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) var ( @@ -63,11 +66,11 @@ var ( testIPConfigurationID = "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/testvm1-nic/ipConfigurations/pipConfig" testBackendPoolID0 = "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/backendAddressPools/backendpool-0" - testBackendPools = &[]network.BackendAddressPool{ + testBackendPools = []*armnetwork.BackendAddressPool{ { ID: ptr.To(testBackendPoolID0), - BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.BackendAddressPoolPropertiesFormat{ + BackendIPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { ID: ptr.To(testIPConfigurationID), }, @@ -76,22 +79,22 @@ var ( }, } - testNic1 = generateTestNic("testvm1-nic", false, network.ProvisioningStateSucceeded, "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1") + testNic1 = generateTestNic("testvm1-nic", false, to.Ptr(armnetwork.ProvisioningStateSucceeded), "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1") - testNic2 = generateTestNic("testvm2-nic", true, network.ProvisioningStateSucceeded, "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm2") + testNic2 = generateTestNic("testvm2-nic", true, to.Ptr(armnetwork.ProvisioningStateSucceeded), "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm2") ) -func generateTestNic(nicName string, isIPConfigurationsNil bool, provisioningState network.ProvisioningState, vmID string) network.Interface { - result := network.Interface{ +func generateTestNic(nicName string, isIPConfigurationsNil bool, provisioningState *armnetwork.ProvisioningState, vmID string) *armnetwork.Interface { + result := &armnetwork.Interface{ ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/" + nicName), Name: ptr.To(nicName), - InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ - IPConfigurations: &[]network.InterfaceIPConfiguration{ + Properties: &armnetwork.InterfacePropertiesFormat{ + IPConfigurations: []*armnetwork.InterfaceIPConfiguration{ { - InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ + Properties: &armnetwork.InterfaceIPConfigurationPropertiesFormat{ Primary: ptr.To(true), PrivateIPAddress: ptr.To(nicName + "testPrivateIP"), - LoadBalancerBackendAddressPools: &[]network.BackendAddressPool{ + LoadBalancerBackendAddressPools: []*armnetwork.BackendAddressPool{ { ID: ptr.To(testBackendPoolID0), }, @@ -100,13 +103,13 @@ func generateTestNic(nicName string, isIPConfigurationsNil bool, provisioningSta }, }, ProvisioningState: provisioningState, - VirtualMachine: &network.SubResource{ + VirtualMachine: &armnetwork.SubResource{ ID: ptr.To(vmID), }, }, } if isIPConfigurationsNil { - result.InterfacePropertiesFormat.IPConfigurations = nil + result.Properties.IPConfigurations = nil } return result } @@ -141,51 +144,51 @@ func TestGetNodeVMSetNameVmssFlex(t *testing.T) { } func TestGetAgentPoolVMSetNamesVmssFlex(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string nodes []*v1.Node - expectedAgentPoolVMSetNames *[]string + expectedAgentPoolVMSetNames []string expectedErr error }{ { description: "GetNodeVMSetName should return the correct VMSetName of the node", nodes: []*v1.Node{testNode1, testNode2}, - expectedAgentPoolVMSetNames: &[]string{"vmssflex1", "vmssflex2"}, + expectedAgentPoolVMSetNames: []string{"vmssflex1", "vmssflex2"}, expectedErr: nil, }, } for _, tc := range testCases { - fs, err := NewTestFlexScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - fs.vmssFlexVMNameToVmssID.Store(testNodeName1, testVmssFlexID1) - fs.vmssFlexVMNameToVmssID.Store(testNodeName2, testVmssFlexID2) + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + fs, err := NewTestFlexScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") + fs.vmssFlexVMNameToVmssID.Store(testNodeName1, testVmssFlexID1) + fs.vmssFlexVMNameToVmssID.Store(testNodeName2, testVmssFlexID2) - agentPoolVMSetNames, err := fs.GetAgentPoolVMSetNames(context.TODO(), tc.nodes) - assert.Equal(t, tc.expectedAgentPoolVMSetNames, agentPoolVMSetNames, tc.description) - assert.Equal(t, tc.expectedErr, err, tc.description) + agentPoolVMSetNames, err := fs.GetAgentPoolVMSetNames(context.TODO(), tc.nodes) + assert.Equal(t, tc.expectedAgentPoolVMSetNames, lo.FromSlicePtr(agentPoolVMSetNames), tc.description) + assert.Equal(t, tc.expectedErr, err, tc.description) + }) } } func TestGetVMSetNamesVmssFlex(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - testCases := []struct { description string service *v1.Service nodes []*v1.Node useSingleSLB bool - expectedVMSetNames *[]string + expectedVMSetNames []string expectedErr error }{ { description: "GetVMSetNames should return the primary vm set name if the service has no mode annotation", service: &v1.Service{}, - expectedVMSetNames: &[]string{"vmss"}, + expectedVMSetNames: []string{"vmss"}, }, { description: "GetVMSetNames should return the primary vm set name when using the single SLB", @@ -193,7 +196,7 @@ func TestGetVMSetNamesVmssFlex(t *testing.T) { ObjectMeta: metav1.ObjectMeta{Annotations: map[string]string{consts.ServiceAnnotationLoadBalancerMode: consts.ServiceAnnotationLoadBalancerAutoModeValue}}, }, useSingleSLB: true, - expectedVMSetNames: &[]string{"vmss"}, + expectedVMSetNames: []string{"vmss"}, }, { description: "GetVMSetNames should return all scale sets if the service has auto mode annotation", @@ -201,7 +204,7 @@ func TestGetVMSetNamesVmssFlex(t *testing.T) { ObjectMeta: metav1.ObjectMeta{Annotations: map[string]string{consts.ServiceAnnotationLoadBalancerMode: consts.ServiceAnnotationLoadBalancerAutoModeValue}}, }, nodes: []*v1.Node{testNode1, testNode2}, - expectedVMSetNames: &[]string{"vmssflex1", "vmssflex2"}, + expectedVMSetNames: []string{"vmssflex1", "vmssflex2"}, }, { description: "GetVMSetNames should report the error if there's no such vmss", @@ -217,35 +220,43 @@ func TestGetVMSetNamesVmssFlex(t *testing.T) { ObjectMeta: metav1.ObjectMeta{Annotations: map[string]string{consts.ServiceAnnotationLoadBalancerMode: "vmssflex1"}}, }, nodes: []*v1.Node{testNode1, testNode2}, - expectedVMSetNames: &[]string{"vmssflex1"}, + expectedVMSetNames: []string{"vmssflex1"}, }, } for _, tc := range testCases { - fs, err := NewTestFlexScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - fs.vmssFlexVMNameToVmssID.Store(testNodeName1, testVmssFlexID1) - fs.vmssFlexVMNameToVmssID.Store(testNodeName2, testVmssFlexID2) + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - if tc.useSingleSLB { - fs.LoadBalancerSku = consts.LoadBalancerSkuStandard - } + fs, err := NewTestFlexScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") + fs.vmssFlexVMNameToVmssID.Store(testNodeName1, testVmssFlexID1) + fs.vmssFlexVMNameToVmssID.Store(testNodeName2, testVmssFlexID2) - vmSetNames, err := fs.GetVMSetNames(context.TODO(), tc.service, tc.nodes) - assert.Equal(t, tc.expectedVMSetNames, vmSetNames, tc.description) - assert.Equal(t, tc.expectedErr, err, tc.description) + if tc.useSingleSLB { + fs.LoadBalancerSKU = consts.LoadBalancerSKUStandard + } + + vmSetNames, err := fs.GetVMSetNames(context.TODO(), tc.service, tc.nodes) + if len(tc.expectedVMSetNames) == 0 { + assert.Nil(t, vmSetNames, tc.description) + } else { + assert.Equal(t, tc.expectedVMSetNames, lo.FromSlicePtr(vmSetNames), tc.description) + } + assert.Equal(t, tc.expectedErr, err, tc.description) + }) } } func TestGetNodeNameByProviderIDVmssFlex(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string providerID string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error expectedNodeName types.NodeName expectedErr error @@ -271,32 +282,36 @@ func TestGetNodeNameByProviderIDVmssFlex(t *testing.T) { } for _, tc := range testCases { - fs, err := NewTestFlexScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() + fs, err := NewTestFlexScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - nodeName, err := fs.GetNodeNameByProviderID(context.TODO(), tc.providerID) - assert.Equal(t, tc.expectedNodeName, nodeName) - assert.Equal(t, tc.expectedErr, err) + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + + nodeName, err := fs.GetNodeNameByProviderID(context.TODO(), tc.providerID) + assert.Equal(t, tc.expectedNodeName, nodeName) + assert.Equal(t, tc.expectedErr, err) + }) } } func TestGetInstanceIDByNodeNameVmssFlex(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string nodeName string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error expectedInstanceID string expectedErr error @@ -322,19 +337,25 @@ func TestGetInstanceIDByNodeNameVmssFlex(t *testing.T) { } for _, tc := range testCases { - fs, err := NewTestFlexScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() + fs, err := NewTestFlexScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - instanceID, err := fs.GetInstanceIDByNodeName(context.Background(), tc.nodeName) - assert.Equal(t, tc.expectedInstanceID, instanceID) - assert.Equal(t, tc.expectedErr, err) + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + + instanceID, err := fs.GetInstanceIDByNodeName(context.Background(), tc.nodeName) + assert.Equal(t, tc.expectedInstanceID, instanceID) + assert.Equal(t, tc.expectedErr, err) + }) } } @@ -345,8 +366,8 @@ func TestGetInstanceTypeByNodeNameVmssFlex(t *testing.T) { testCases := []struct { description string nodeName string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error expectedInstanceType string expectedErr error @@ -375,12 +396,12 @@ func TestGetInstanceTypeByNodeNameVmssFlex(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() instanceType, err := fs.GetInstanceTypeByNodeName(context.Background(), tc.nodeName) assert.Equal(t, tc.expectedInstanceType, instanceType) @@ -395,8 +416,8 @@ func TestGetZoneByNodeNameVmssFlex(t *testing.T) { testCases := []struct { description string nodeName string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error expectedZone cloudprovider.Zone expectedErr error @@ -449,12 +470,12 @@ func TestGetZoneByNodeNameVmssFlex(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() zone, err := fs.GetZoneByNodeName(context.TODO(), tc.nodeName) assert.Equal(t, tc.expectedZone, zone) @@ -470,8 +491,8 @@ func TestGetProvisioningStateByNodeNameVmssFlex(t *testing.T) { testCases := []struct { description string nodeName string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error expectedProvisioningState string expectedErr error @@ -509,12 +530,12 @@ func TestGetProvisioningStateByNodeNameVmssFlex(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() provisioningState, err := fs.GetProvisioningStateByNodeName(context.TODO(), tc.nodeName) assert.Equal(t, tc.expectedProvisioningState, provisioningState) @@ -530,8 +551,8 @@ func TestGetPowerStatusByNodeNameVmssFlex(t *testing.T) { testCases := []struct { description string nodeName string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error expectedPowerStatus string expectedErr error @@ -569,12 +590,12 @@ func TestGetPowerStatusByNodeNameVmssFlex(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() powerStatus, err := fs.GetPowerStatusByNodeName(context.TODO(), tc.nodeName) assert.Equal(t, tc.expectedPowerStatus, powerStatus) @@ -584,18 +605,16 @@ func TestGetPowerStatusByNodeNameVmssFlex(t *testing.T) { } func TestGetPrimaryInterfaceVmssFlex(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string nodeName string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error - nic network.Interface - nicGetErr *retry.Error - expectedNeworkInterface network.Interface + nic *armnetwork.Interface + nicGetErr error + expectedNeworkInterface *armnetwork.Interface expectedErr error }{ { @@ -615,9 +634,9 @@ func TestGetPrimaryInterfaceVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - nic: network.Interface{}, + nic: &armnetwork.Interface{}, nicGetErr: nil, - expectedNeworkInterface: network.Interface{}, + expectedNeworkInterface: &armnetwork.Interface{}, expectedErr: cloudprovider.InstanceNotFound, }, { @@ -626,32 +645,41 @@ func TestGetPrimaryInterfaceVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - nic: network.Interface{}, - nicGetErr: &retry.Error{RawError: fmt.Errorf("NIC not found")}, - expectedNeworkInterface: network.Interface{}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: NIC not found"), + nic: &armnetwork.Interface{}, + nicGetErr: &azcore.ResponseError{ErrorCode: "NIC not found"}, + expectedNeworkInterface: &armnetwork.Interface{}, + expectedErr: fmt.Errorf("NIC not found"), }, } for _, tc := range testCases { - fs, err := NewTestFlexScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + fs, err := NewTestFlexScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() - mockInterfacesClient := fs.InterfacesClient.(*mockinterfaceclient.MockInterface) - mockInterfacesClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.nic, tc.nicGetErr).AnyTimes() + mockInterfacesClient := fs.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) + mockInterfacesClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.nic, tc.nicGetErr).AnyTimes() - nic, err := fs.GetPrimaryInterface(context.Background(), tc.nodeName) - assert.Equal(t, tc.expectedNeworkInterface, nic, tc.description) - if tc.expectedErr != nil { - assert.EqualError(t, err, tc.expectedErr.Error(), tc.description) - } + nic, err := fs.GetPrimaryInterface(context.Background(), tc.nodeName) + if tc.expectedErr != nil { + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) + } else if tc.expectedNeworkInterface == nil { + assert.Nil(t, nic, tc.description) + } else { + assert.Equal(t, *tc.expectedNeworkInterface, *nic, tc.description) + } + + }) } } @@ -662,11 +690,11 @@ func TestGetIPByNodeNameVmssFlex(t *testing.T) { testCases := []struct { description string nodeName string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error - nic network.Interface - nicGetErr *retry.Error + nic *armnetwork.Interface + nicGetErr error expectedPrivateIP string expectedPublicIP string expectedErr error @@ -689,14 +717,14 @@ func TestGetIPByNodeNameVmssFlex(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() - mockInterfacesClient := fs.InterfacesClient.(*mockinterfaceclient.MockInterface) + mockInterfacesClient := fs.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) mockInterfacesClient.EXPECT().Get(gomock.Any(), gomock.Any(), "testvm1-nic", gomock.Any()).Return(tc.nic, tc.nicGetErr).AnyTimes() privateIP, publicIP, err := fs.GetIPByNodeName(context.Background(), tc.nodeName) @@ -714,11 +742,11 @@ func TestGetPrivateIPsByNodeNameVmssFlex(t *testing.T) { testCases := []struct { description string nodeName string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error - nic network.Interface - nicGetErr *retry.Error + nic *armnetwork.Interface + nicGetErr error expectedPrivateIPs []string expectedErr error }{ @@ -742,7 +770,7 @@ func TestGetPrivateIPsByNodeNameVmssFlex(t *testing.T) { nic: testNic2, nicGetErr: nil, expectedPrivateIPs: []string{}, - expectedErr: fmt.Errorf("nic.IPConfigurations for nic (nicname=testvm2-nic) is nil"), + expectedErr: fmt.Errorf("nic.Properties.IPConfigurations for nic (nicname=testvm2-nic) is nil"), }, } @@ -750,14 +778,14 @@ func TestGetPrivateIPsByNodeNameVmssFlex(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() - mockInterfacesClient := fs.InterfacesClient.(*mockinterfaceclient.MockInterface) + mockInterfacesClient := fs.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) mockInterfacesClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.nic, tc.nicGetErr).AnyTimes() ips, err := fs.GetPrivateIPsByNodeName(context.Background(), tc.nodeName) @@ -774,10 +802,10 @@ func TestGetNodeNameByIPConfigurationIDVmssFlex(t *testing.T) { testCases := []struct { description string ipConfigurationID string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error - nic network.Interface + nic *armnetwork.Interface expectedNodeName string expectedVMSetName string expectedErr error @@ -788,7 +816,7 @@ func TestGetNodeNameByIPConfigurationIDVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - nic: generateTestNic("testvm1-nic", false, network.ProvisioningStateSucceeded, "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), + nic: generateTestNic("testvm1-nic", false, to.Ptr(armnetwork.ProvisioningStateSucceeded), "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), expectedNodeName: "vmssflex1000001", expectedVMSetName: "vmssflex1", expectedErr: nil, @@ -799,7 +827,7 @@ func TestGetNodeNameByIPConfigurationIDVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - nic: generateTestNic("testvm1-nic", false, network.ProvisioningStateSucceeded, fmt.Sprintf("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/%s", nonExistingNodeName)), + nic: generateTestNic("testvm1-nic", false, to.Ptr(armnetwork.ProvisioningStateSucceeded), fmt.Sprintf("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/%s", nonExistingNodeName)), expectedNodeName: "", expectedVMSetName: "", expectedErr: fmt.Errorf("failed to map VM Name to NodeName: VM Name NonExistingNodeName: %w", cloudprovider.InstanceNotFound), @@ -820,14 +848,14 @@ func TestGetNodeNameByIPConfigurationIDVmssFlex(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() - mockInterfacesClient := fs.InterfacesClient.(*mockinterfaceclient.MockInterface) + mockInterfacesClient := fs.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) mockInterfacesClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.nic, nil).AnyTimes() nodeName, vmSetName, err := fs.GetNodeNameByIPConfigurationID(context.TODO(), tc.ipConfigurationID) @@ -844,8 +872,8 @@ func TestGetNodeCIDRMasksByProviderIDVmssFlex(t *testing.T) { testCases := []struct { description string providerID string - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error tags map[string]*string expectedNodeMaskCIDRIPv4 int @@ -918,12 +946,12 @@ func TestGetNodeCIDRMasksByProviderIDVmssFlex(t *testing.T) { if tc.tags != nil { testVmssFlexList[0].Tags = tc.tags } - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() nodeMaskCIDRIPv4, nodeMaskCIDRIPv6, err := fs.GetNodeCIDRMasksByProviderID(context.TODO(), tc.providerID) assert.Equal(t, tc.expectedNodeMaskCIDRIPv4, nodeMaskCIDRIPv4) @@ -934,8 +962,6 @@ func TestGetNodeCIDRMasksByProviderIDVmssFlex(t *testing.T) { } func TestEnsureHostInPoolVmssFlex(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() testCases := []struct { description string @@ -944,12 +970,12 @@ func TestEnsureHostInPoolVmssFlex(t *testing.T) { vmSetNameOfLB string backendPoolID string isStandardLB bool - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error - nic network.Interface - nicGetErr *retry.Error - nicPutErr *retry.Error + nic *armnetwork.Interface + nicGetErr error + nicPutErr error expectedNodeResourceGroup string expectedVMSetName string expectedNodeName string @@ -982,7 +1008,7 @@ func TestEnsureHostInPoolVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - nic: network.Interface{}, + nic: &armnetwork.Interface{}, nicGetErr: nil, expectedNodeResourceGroup: "", expectedVMSetName: "", @@ -1004,7 +1030,7 @@ func TestEnsureHostInPoolVmssFlex(t *testing.T) { expectedNodeResourceGroup: "", expectedVMSetName: "", expectedNodeName: "", - expectedErr: fmt.Errorf("nic.IPConfigurations for nic (nicname=\"testvm2-nic\") is nil"), + expectedErr: fmt.Errorf("nic.Properties.IPConfigurations for nic (nicname=\"testvm2-nic\") is nil"), }, { description: "EnsureHostInPool should skip the current node if failing to get the PrimaryInterface", @@ -1016,12 +1042,12 @@ func TestEnsureHostInPoolVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - nic: network.Interface{}, - nicGetErr: &retry.Error{RawError: fmt.Errorf("failed to get nic for node: vmssflex1000001")}, + nic: &armnetwork.Interface{}, + nicGetErr: &azcore.ResponseError{ErrorCode: "failed to get nic for node: vmssflex1000001"}, expectedNodeResourceGroup: "", expectedVMSetName: "", expectedNodeName: "", - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: failed to get nic for node: vmssflex1000001"), + expectedErr: fmt.Errorf("failed to get nic for node: vmssflex1000001"), }, { description: "EnsureHostInPool should return error if the nic update fails", @@ -1033,13 +1059,13 @@ func TestEnsureHostInPoolVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - nic: generateTestNic("testvm1-nic", false, network.ProvisioningStateSucceeded, "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), + nic: generateTestNic("testvm1-nic", false, to.Ptr(armnetwork.ProvisioningStateSucceeded), "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), nicGetErr: nil, - nicPutErr: &retry.Error{RawError: fmt.Errorf("failed to update nic")}, + nicPutErr: &azcore.ResponseError{ErrorCode: "failed to update nic"}, expectedNodeResourceGroup: "", expectedVMSetName: "", expectedNodeName: "", - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: failed to update nic"), + expectedErr: fmt.Errorf("failed to update nic"), }, { description: "EnsureHostInPool should skip the node if primary nic is in Failed state", @@ -1051,7 +1077,7 @@ func TestEnsureHostInPoolVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - nic: generateTestNic("testvm1-nic", false, network.ProvisioningStateFailed, "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), + nic: generateTestNic("testvm1-nic", false, to.Ptr(armnetwork.ProvisioningStateFailed), "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), nicGetErr: nil, nicPutErr: nil, expectedNodeResourceGroup: "", @@ -1096,31 +1122,36 @@ func TestEnsureHostInPoolVmssFlex(t *testing.T) { } for _, tc := range testCases { - fs, err := NewTestFlexScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - if tc.isStandardLB { - fs.Config.LoadBalancerSku = consts.LoadBalancerSkuStandard - } + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() + fs, err := NewTestFlexScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") + if tc.isStandardLB { + fs.Config.LoadBalancerSKU = consts.LoadBalancerSKUStandard + } - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(testVmssFlexList, nil).AnyTimes() - mockInterfacesClient := fs.InterfacesClient.(*mockinterfaceclient.MockInterface) - mockInterfacesClient.EXPECT().Get(gomock.Any(), gomock.Any(), "testvm1-nic", gomock.Any()).Return(tc.nic, tc.nicGetErr).AnyTimes() - mockInterfacesClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.nicPutErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() - rg, vmSetName, nodeName, _, err := fs.EnsureHostInPool(context.Background(), tc.service, tc.nodeName, tc.backendPoolID, tc.vmSetNameOfLB) - assert.Equal(t, tc.expectedNodeResourceGroup, rg, tc.description) - assert.Equal(t, tc.expectedVMSetName, vmSetName, tc.description) - assert.Equal(t, tc.expectedNodeName, nodeName, tc.description) - if tc.expectedErr != nil { - assert.EqualError(t, err, tc.expectedErr.Error(), tc.description) - } + mockInterfacesClient := fs.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) + mockInterfacesClient.EXPECT().Get(gomock.Any(), gomock.Any(), "testvm1-nic", gomock.Any()).Return(tc.nic, tc.nicGetErr).AnyTimes() + mockInterfacesClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, tc.nicPutErr).AnyTimes() + rg, vmSetName, nodeName, _, err := fs.EnsureHostInPool(context.Background(), tc.service, tc.nodeName, tc.backendPoolID, tc.vmSetNameOfLB) + assert.Equal(t, tc.expectedNodeResourceGroup, rg, tc.description) + assert.Equal(t, tc.expectedVMSetName, vmSetName, tc.description) + assert.Equal(t, tc.expectedNodeName, nodeName, tc.description) + if tc.expectedErr != nil { + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) + } + }) } } @@ -1138,10 +1169,10 @@ func TestEnsureVMSSFlexInPool(t *testing.T) { isStandardLB bool isVMSSDeallocating bool hasDefaultVMProfile bool - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error - vmssPutErr *retry.Error + vmssPutErr error expectedErr error }{ { @@ -1246,27 +1277,27 @@ func TestEnsureVMSSFlexInPool(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") if tc.isStandardLB { - fs.Config.LoadBalancerSku = consts.LoadBalancerSkuStandard + fs.Config.LoadBalancerSKU = consts.LoadBalancerSKUStandard } testVmssFlex := genreteTestVmssFlex("vmssflex1", testVmssFlex1ID) if tc.isVMSSDeallocating { - testVmssFlex.ProvisioningState = ptr.To(consts.ProvisionStateDeleting) + testVmssFlex.Properties.ProvisioningState = ptr.To(consts.ProvisionStateDeleting) } if !tc.hasDefaultVMProfile { - testVmssFlex.VirtualMachineProfile = nil + testVmssFlex.Properties.VirtualMachineProfile = nil } - expectedestVmssFlexList := []compute.VirtualMachineScaleSet{testVmssFlex} + expectedestVmssFlexList := []*armcompute.VirtualMachineScaleSet{testVmssFlex} - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(expectedestVmssFlexList, nil).AnyTimes() - mockVMSSClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any()).Return(testVmssFlex1, nil).AnyTimes() - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.vmssPutErr).AnyTimes() + mockVMSSClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(testVmssFlex1, nil).AnyTimes() + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, tc.vmssPutErr).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() err = fs.ensureVMSSFlexInPool(context.TODO(), tc.service, tc.nodes, tc.backendPoolID, tc.vmSetNameOfLB) @@ -1288,12 +1319,12 @@ func TestEnsureHostsInPoolVmssFlex(t *testing.T) { vmSetNameOfLB string backendPoolID string isStandardLB bool - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error - nic network.Interface - nicGetErr *retry.Error - vmssPutErr *retry.Error + nic *armnetwork.Interface + nicGetErr error + vmssPutErr error expectedErr error }{ { @@ -1354,8 +1385,8 @@ func TestEnsureHostsInPoolVmssFlex(t *testing.T) { vmListErr: nil, nic: testNic1, nicGetErr: nil, - vmssPutErr: &retry.Error{RawError: fmt.Errorf("failed to update nic")}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: failed to update nic"), + vmssPutErr: &azcore.ResponseError{ErrorCode: "failed to update nic"}, + expectedErr: fmt.Errorf("failed to update nic"), }, } @@ -1363,26 +1394,26 @@ func TestEnsureHostsInPoolVmssFlex(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") if tc.isStandardLB { - fs.Config.LoadBalancerSku = consts.LoadBalancerSkuStandard + fs.Config.LoadBalancerSKU = consts.LoadBalancerSKUStandard } - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{genreteTestVmssFlex("vmssflex1", testVmssFlex1ID)}, nil).AnyTimes() - mockVMSSClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any()).Return(testVmssFlex1, nil).AnyTimes() - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.vmssPutErr).AnyTimes() + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*armcompute.VirtualMachineScaleSet{genreteTestVmssFlex("vmssflex1", testVmssFlex1ID)}, nil).AnyTimes() + mockVMSSClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(testVmssFlex1, nil).AnyTimes() + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, tc.vmssPutErr).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() - mockInterfacesClient := fs.InterfacesClient.(*mockinterfaceclient.MockInterface) + mockInterfacesClient := fs.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) mockInterfacesClient.EXPECT().Get(gomock.Any(), gomock.Any(), "testvm1-nic", gomock.Any()).Return(tc.nic, tc.nicGetErr).AnyTimes() - mockInterfacesClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + mockInterfacesClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() err = fs.EnsureHostsInPool(context.Background(), tc.service, tc.nodes, tc.backendPoolID, tc.vmSetNameOfLB) if tc.expectedErr != nil { - assert.EqualError(t, err, tc.expectedErr.Error(), tc.description) + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) } } @@ -1401,7 +1432,7 @@ func TestEnsureBackendPoolDeletedFromVMSetsVmssFlex(t *testing.T) { isNicConfigEmpty bool isIPConfigEmpty bool vmssListCallingTimes int - vmssPutErr *retry.Error + vmssPutErr error expectedErr error }{ { @@ -1488,9 +1519,9 @@ func TestEnsureBackendPoolDeletedFromVMSetsVmssFlex(t *testing.T) { }, backendPoolID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/backendAddressPools/backendpool-0", hasDefaultVMProfile: true, - vmssPutErr: &retry.Error{RawError: fmt.Errorf("failed to update nic")}, + vmssPutErr: &azcore.ResponseError{ErrorCode: "failed to update nic"}, vmssListCallingTimes: 2, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: failed to update nic"), + expectedErr: fmt.Errorf("failed to update nic"), }, } @@ -1502,30 +1533,30 @@ func TestEnsureBackendPoolDeletedFromVMSetsVmssFlex(t *testing.T) { testVmssFlex := genreteTestVmssFlex("vmssflex1", testVmssFlex1ID) if tc.isVMSSDeallocating { - testVmssFlex.ProvisioningState = ptr.To(consts.ProvisionStateDeleting) + testVmssFlex.Properties.ProvisioningState = ptr.To(consts.ProvisionStateDeleting) } if !tc.hasDefaultVMProfile { - testVmssFlex.VirtualMachineProfile = nil + testVmssFlex.Properties.VirtualMachineProfile = nil } if tc.isNicConfigEmpty { - testVmssFlex.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = &[]compute.VirtualMachineScaleSetNetworkConfiguration{} + testVmssFlex.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = []*armcompute.VirtualMachineScaleSetNetworkConfiguration{} } if tc.isIPConfigEmpty { - (*testVmssFlex.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations)[0].IPConfigurations = &[]compute.VirtualMachineScaleSetIPConfiguration{} + (testVmssFlex.Properties.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations)[0].Properties.IPConfigurations = []*armcompute.VirtualMachineScaleSetIPConfiguration{} } - vmssFlexList := []compute.VirtualMachineScaleSet{testVmssFlex} + vmssFlexList := []*armcompute.VirtualMachineScaleSet{testVmssFlex} - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(vmssFlexList, nil).Times(tc.vmssListCallingTimes) - mockVMSSClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any()).Return(testVmssFlex1, nil).AnyTimes() - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.vmssPutErr).AnyTimes() + mockVMSSClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(testVmssFlex1, nil).AnyTimes() + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, tc.vmssPutErr).AnyTimes() err = fs.EnsureBackendPoolDeletedFromVMSets(context.TODO(), tc.vmssNamesMap, []string{tc.backendPoolID}) _, _ = fs.getVmssFlexByName(context.TODO(), "vmssflex1") if tc.expectedErr != nil { - assert.EqualError(t, err, tc.expectedErr.Error()) + assert.Contains(t, err.Error(), tc.expectedErr.Error()) } else { assert.NoError(t, err) } @@ -1541,10 +1572,10 @@ func TestEnsureBackendPoolDeletedFromNodeVmssFlex(t *testing.T) { description string vmssFlexVMNameMap map[string]string backendPoolID string - nics []network.Interface + nics []*armnetwork.Interface expectedPutNICTimes int - nicGetErr *retry.Error - nicPutErr *retry.Error + nicGetErr error + nicPutErr error expectedErr error }{ { @@ -1554,9 +1585,9 @@ func TestEnsureBackendPoolDeletedFromNodeVmssFlex(t *testing.T) { "vmssflex1000002": "testvm2-nic", }, backendPoolID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/backendAddressPools/backendpool-0", - nics: []network.Interface{ - generateTestNic("testvm1-nic", false, network.ProvisioningStateSucceeded, "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), - generateTestNic("testvm2-nic", false, network.ProvisioningStateSucceeded, "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm2"), + nics: []*armnetwork.Interface{ + generateTestNic("testvm1-nic", false, to.Ptr(armnetwork.ProvisioningStateSucceeded), "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), + generateTestNic("testvm2-nic", false, to.Ptr(armnetwork.ProvisioningStateSucceeded), "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm2"), }, expectedPutNICTimes: 1, nicGetErr: nil, @@ -1568,9 +1599,9 @@ func TestEnsureBackendPoolDeletedFromNodeVmssFlex(t *testing.T) { "vmssflex1000001": "testvm1-nic", }, backendPoolID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/backendAddressPools/backendpool-0", - nics: []network.Interface{generateTestNic("testvm1-nic", false, network.ProvisioningStateSucceeded, "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1")}, - nicGetErr: &retry.Error{RawError: fmt.Errorf("failed to get nic")}, - expectedErr: fmt.Errorf("ensureBackendPoolDeletedFromNode: failed to get interface of name testvm1-nic: Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: failed to get nic"), + nics: []*armnetwork.Interface{generateTestNic("testvm1-nic", false, to.Ptr(armnetwork.ProvisioningStateSucceeded), "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1")}, + nicGetErr: &azcore.ResponseError{ErrorCode: "failed to get nic"}, + expectedErr: fmt.Errorf("failed to get nic"), }, { description: "EnsureBackendPoolDeletedFromNode should skip the node if the NIC is in failed state", @@ -1578,7 +1609,7 @@ func TestEnsureBackendPoolDeletedFromNodeVmssFlex(t *testing.T) { "vmssflex1000001": "testvm1-nic", }, backendPoolID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/backendAddressPools/backendpool-0", - nics: []network.Interface{generateTestNic("testvm1-nic", false, network.ProvisioningStateFailed, "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1")}, + nics: []*armnetwork.Interface{generateTestNic("testvm1-nic", false, to.Ptr(armnetwork.ProvisioningStateFailed), "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1")}, nicGetErr: nil, expectedErr: nil, }, @@ -1588,11 +1619,11 @@ func TestEnsureBackendPoolDeletedFromNodeVmssFlex(t *testing.T) { "vmssflex1000001": "testvm1-nic", }, backendPoolID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/backendAddressPools/backendpool-0", - nics: []network.Interface{generateTestNic("testvm1-nic", false, network.ProvisioningStateSucceeded, "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1")}, + nics: []*armnetwork.Interface{generateTestNic("testvm1-nic", false, to.Ptr(armnetwork.ProvisioningStateSucceeded), "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1")}, expectedPutNICTimes: 1, nicGetErr: nil, - nicPutErr: &retry.Error{RawError: fmt.Errorf("failed to update nic")}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: failed to update nic"), + nicPutErr: &azcore.ResponseError{ErrorCode: "failed to update nic"}, + expectedErr: fmt.Errorf("failed to update nic"), }, } @@ -1601,17 +1632,17 @@ func TestEnsureBackendPoolDeletedFromNodeVmssFlex(t *testing.T) { fs, err := NewTestFlexScaleSet(ctrl) assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - mockInterfacesClient := fs.InterfacesClient.(*mockinterfaceclient.MockInterface) + mockInterfacesClient := fs.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) for i := range tc.nics { nic := tc.nics[i] mockInterfacesClient.EXPECT().Get(gomock.Any(), gomock.Any(), *nic.Name, gomock.Any()).Return(nic, tc.nicGetErr).AnyTimes() - mockInterfacesClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), *nic.Name, gomock.Any()).Return(tc.nicPutErr).Times(tc.expectedPutNICTimes) + mockInterfacesClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), *nic.Name, gomock.Any()).Return(nil, tc.nicPutErr).Times(tc.expectedPutNICTimes) } updated, err := fs.ensureBackendPoolDeletedFromNode(context.TODO(), tc.vmssFlexVMNameMap, []string{tc.backendPoolID}) if tc.expectedErr != nil { - assert.EqualError(t, err, tc.expectedErr.Error()) + assert.Contains(t, err.Error(), tc.expectedErr.Error()) } else { assert.NoError(t, err) if tc.expectedPutNICTimes > 0 { @@ -1624,25 +1655,22 @@ func TestEnsureBackendPoolDeletedFromNodeVmssFlex(t *testing.T) { func TestEnsureBackendPoolDeletedVmssFlex(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - testCases := []struct { description string service *v1.Service vmSetName string backendPoolID string - backendAddressPools *[]network.BackendAddressPool + backendAddressPools []*armnetwork.BackendAddressPool deleteFromVMSet bool isStandardLB bool - testVMListWithoutInstanceView []compute.VirtualMachine - testVMListWithOnlyInstanceView []compute.VirtualMachine + testVMListWithoutInstanceView []*armcompute.VirtualMachine + testVMListWithOnlyInstanceView []*armcompute.VirtualMachine vmListErr error - nic network.Interface - nicGetErr *retry.Error - nicPutErr *retry.Error - vmssPutErr *retry.Error + nic *armnetwork.Interface + nicGetErr error + nicPutErr error + vmssPutErr error expectedErr error }{ @@ -1657,7 +1685,7 @@ func TestEnsureBackendPoolDeletedVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - nic: generateTestNic("testvm1-nic", false, network.ProvisioningStateSucceeded, "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), + nic: generateTestNic("testvm1-nic", false, to.Ptr(armnetwork.ProvisioningStateSucceeded), "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), nicGetErr: nil, expectedErr: nil, }, @@ -1672,7 +1700,7 @@ func TestEnsureBackendPoolDeletedVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - nic: generateTestNic("testvm1-nic", false, network.ProvisioningStateSucceeded, "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), + nic: generateTestNic("testvm1-nic", false, to.Ptr(armnetwork.ProvisioningStateSucceeded), "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), nicGetErr: nil, expectedErr: nil, }, @@ -1687,43 +1715,48 @@ func TestEnsureBackendPoolDeletedVmssFlex(t *testing.T) { testVMListWithoutInstanceView: testVMListWithoutInstanceView, testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, - nic: generateTestNic("testvm1-nic", false, network.ProvisioningStateSucceeded, "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), + nic: generateTestNic("testvm1-nic", false, to.Ptr(armnetwork.ProvisioningStateSucceeded), "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1"), nicGetErr: nil, - nicPutErr: &retry.Error{RawError: fmt.Errorf("failed to update nic")}, - expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: failed to update nic"), + nicPutErr: &azcore.ResponseError{ErrorCode: "failed to update nic"}, + expectedErr: fmt.Errorf("failed to update nic"), }, } for _, tc := range testCases { - fs, err := NewTestFlexScaleSet(ctrl) - assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") - if tc.isStandardLB { - fs.Config.LoadBalancerSku = consts.LoadBalancerSkuStandard - } + tc := tc + t.Run(tc.description, func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + fs, err := NewTestFlexScaleSet(ctrl) + assert.NoError(t, err, "unexpected error when creating test FlexScaleSet") + if tc.isStandardLB { + fs.Config.LoadBalancerSKU = consts.LoadBalancerSKUStandard + } - testVmssFlex := genreteTestVmssFlex("vmssflex1", testVmssFlex1ID) - vmssFlexList := []compute.VirtualMachineScaleSet{testVmssFlex, genreteTestVmssFlex("vmssflex2", testVmssFlex2ID)} + testVmssFlex := genreteTestVmssFlex("vmssflex1", testVmssFlex1ID) + vmssFlexList := []*armcompute.VirtualMachineScaleSet{testVmssFlex, genreteTestVmssFlex("vmssflex2", testVmssFlex2ID)} - mockVMSSClient := fs.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) - mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(vmssFlexList, nil).AnyTimes() - mockVMSSClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any()).Return(testVmssFlex1, nil).AnyTimes() - mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.vmssPutErr).AnyTimes() + mockVMSSClient := fs.ComputeClientFactory.GetVirtualMachineScaleSetClient().(*mock_virtualmachinescalesetclient.MockInterface) + mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(vmssFlexList, nil).AnyTimes() + mockVMSSClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(testVmssFlex1, nil).AnyTimes() + mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, tc.vmssPutErr).AnyTimes() - mockVMClient := fs.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() - mockVMClient.EXPECT().ListVmssFlexVMsWithOnlyInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() + mockVMClient := fs.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().List(gomock.Any(), gomock.Any()).Return(tc.testVMListWithoutInstanceView, tc.vmListErr).AnyTimes() + mockVMClient.EXPECT().ListVMInstanceView(gomock.Any(), gomock.Any()).Return(tc.testVMListWithOnlyInstanceView, tc.vmListErr).AnyTimes() - mockInterfacesClient := fs.InterfacesClient.(*mockinterfaceclient.MockInterface) - mockInterfacesClient.EXPECT().Get(gomock.Any(), gomock.Any(), "testvm1-nic", gomock.Any()).Return(tc.nic, tc.nicGetErr).AnyTimes() - mockInterfacesClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(tc.nicPutErr).AnyTimes() + mockInterfacesClient := fs.NetworkClientFactory.GetInterfaceClient().(*mock_interfaceclient.MockInterface) + mockInterfacesClient.EXPECT().Get(gomock.Any(), gomock.Any(), "testvm1-nic", gomock.Any()).Return(tc.nic, tc.nicGetErr).AnyTimes() + mockInterfacesClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, tc.nicPutErr).AnyTimes() - _, err = fs.EnsureBackendPoolDeleted(context.TODO(), tc.service, []string{tc.backendPoolID}, tc.vmSetName, tc.backendAddressPools, tc.deleteFromVMSet) + _, err = fs.EnsureBackendPoolDeleted(context.TODO(), tc.service, []string{tc.backendPoolID}, tc.vmSetName, tc.backendAddressPools, tc.deleteFromVMSet) - if tc.expectedErr != nil { - assert.EqualError(t, err, tc.expectedErr.Error(), tc.description) - } else { - assert.NoError(t, err, tc.description) - } - } + if tc.expectedErr != nil { + assert.Contains(t, err.Error(), tc.expectedErr.Error(), tc.description) + } else { + assert.NoError(t, err, tc.description) + } + }) + } } diff --git a/pkg/provider/azure_wrap.go b/pkg/provider/azure_wrap.go index 054fd24faf..133e877727 100644 --- a/pkg/provider/azure_wrap.go +++ b/pkg/provider/azure_wrap.go @@ -17,13 +17,15 @@ limitations under the License. package provider import ( + "errors" "fmt" "net/http" "regexp" "strings" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) var ( @@ -38,13 +40,15 @@ var ( // checkExistsFromError inspects an error and returns a true if err is nil, // false if error is an autorest.Error with StatusCode=404 and will return the // error back if error is another status code or another type of error. -func checkResourceExistsFromError(err *retry.Error) (bool, *retry.Error) { +func checkResourceExistsFromError(err error) (bool, error) { if err == nil { return true, nil } - - if err.HTTPStatusCode == http.StatusNotFound { - return false, nil + var rerr *azcore.ResponseError + if errors.As(err, &rerr) { + if rerr.StatusCode == http.StatusNotFound { + return false, nil + } } return false, err diff --git a/pkg/provider/azure_wrap_test.go b/pkg/provider/azure_wrap_test.go index 3ce33f7cfc..3f8b340365 100644 --- a/pkg/provider/azure_wrap_test.go +++ b/pkg/provider/azure_wrap_test.go @@ -21,22 +21,22 @@ import ( "reflect" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" ) func TestExtractNotFound(t *testing.T) { - notFound := &retry.Error{HTTPStatusCode: http.StatusNotFound} - otherHTTP := &retry.Error{HTTPStatusCode: http.StatusForbidden} - otherErr := &retry.Error{HTTPStatusCode: http.StatusTooManyRequests} + notFound := &azcore.ResponseError{StatusCode: http.StatusNotFound} + otherHTTP := &azcore.ResponseError{StatusCode: http.StatusForbidden} + otherErr := &azcore.ResponseError{StatusCode: http.StatusTooManyRequests} tests := []struct { - err *retry.Error - expectedErr *retry.Error + err error + expectedErr error exists bool }{ {nil, nil, true}, diff --git a/pkg/provider/azure_zones.go b/pkg/provider/azure_zones.go index b5f0306138..c9de849d70 100644 --- a/pkg/provider/azure_zones.go +++ b/pkg/provider/azure_zones.go @@ -23,6 +23,7 @@ import ( "strconv" "strings" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" cloudprovider "k8s.io/cloud-provider" @@ -72,19 +73,19 @@ func (az *Cloud) updateRegionZonesMap(zones map[string][]string) { } } -func (az *Cloud) getRegionZonesBackoff(ctx context.Context, region string) ([]string, error) { +func (az *Cloud) getRegionZonesBackoff(ctx context.Context, region string) ([]*string, error) { if az.IsStackCloud() { // Azure Stack does not support zone at the moment // https://docs.microsoft.com/en-us/azure-stack/user/azure-stack-network-differences?view=azs-2102 klog.V(3).Infof("getRegionZonesMapWrapper: Azure Stack does not support Zones at the moment, skipping") - return az.regionZonesMap[region], nil + return to.SliceOfPtrs(az.regionZonesMap[region]...), nil } if len(az.regionZonesMap) != 0 { az.refreshZonesLock.RLock() defer az.refreshZonesLock.RUnlock() - return az.regionZonesMap[region], nil + return to.SliceOfPtrs(az.regionZonesMap[region]...), nil } klog.V(2).Infof("getRegionZonesMapWrapper: the region-zones map is not initialized successfully, retrying immediately") @@ -104,7 +105,7 @@ func (az *Cloud) getRegionZonesBackoff(ctx context.Context, region string) ([]st }) if wait.Interrupted(err) { - return []string{}, innerErr + return []*string{}, innerErr } az.updateRegionZonesMap(zones) @@ -113,10 +114,10 @@ func (az *Cloud) getRegionZonesBackoff(ctx context.Context, region string) ([]st az.refreshZonesLock.RLock() defer az.refreshZonesLock.RUnlock() - return az.regionZonesMap[region], nil + return to.SliceOfPtrs(az.regionZonesMap[region]...), nil } - return []string{}, nil + return []*string{}, nil } // makeZone returns the zone value in format of -. diff --git a/pkg/provider/azure_zones_test.go b/pkg/provider/azure_zones_test.go index 7c160c0a00..85d10635ab 100644 --- a/pkg/provider/azure_zones_test.go +++ b/pkg/provider/azure_zones_test.go @@ -24,7 +24,8 @@ import ( "testing" "time" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" @@ -32,7 +33,7 @@ import ( cloudprovider "k8s.io/cloud-provider" "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualmachineclient/mock_virtualmachineclient" "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" "sigs.k8s.io/cloud-provider-azure/pkg/provider/zone" utilsets "sigs.k8s.io/cloud-provider-azure/pkg/util/sets" @@ -211,9 +212,9 @@ func TestGetZoneByProviderID(t *testing.T) { assert.NoError(t, err) assert.Equal(t, cloudprovider.Zone{}, zone) - mockVMClient := az.VirtualMachinesClient.(*mockvmclient.MockInterface) - mockVMClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "vm-0", gomock.Any()).Return(compute.VirtualMachine{ - Zones: &[]string{"1"}, + mockVMClient := az.ComputeClientFactory.GetVirtualMachineClient().(*mock_virtualmachineclient.MockInterface) + mockVMClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "vm-0", gomock.Any()).Return(&armcompute.VirtualMachine{ + Zones: to.SliceOfPtrs("1"), Location: ptr.To("eastus"), }, nil) zone, err = az.GetZoneByProviderID(context.Background(), testAvailabilitySetNodeProviderID) diff --git a/pkg/provider/config/azure.go b/pkg/provider/config/azure.go index c643234da7..8cdf73f0b6 100644 --- a/pkg/provider/config/azure.go +++ b/pkg/provider/config/azure.go @@ -89,7 +89,7 @@ type Config struct { SystemTags string `json:"systemTags,omitempty" yaml:"systemTags,omitempty"` // Sku of Load Balancer and Public IP. Candidate values are: basic and standard. // If not set, it will be default to basic. - LoadBalancerSku string `json:"loadBalancerSku,omitempty" yaml:"loadBalancerSku,omitempty"` + LoadBalancerSKU string `json:"loadBalancerSku,omitempty" yaml:"loadBalancerSku,omitempty"` // LoadBalancerName determines the specific name of the load balancer user want to use, working with // LoadBalancerResourceGroup LoadBalancerName string `json:"loadBalancerName,omitempty" yaml:"loadBalancerName,omitempty"` @@ -188,7 +188,7 @@ func (az *Config) GetPutVMSSVMBatchSize() int { } func (az *Config) UseStandardLoadBalancer() bool { - return strings.EqualFold(az.LoadBalancerSku, consts.LoadBalancerSkuStandard) + return strings.EqualFold(az.LoadBalancerSKU, consts.LoadBalancerSKUStandard) } func (az *Config) ExcludeMasterNodesFromStandardLB() bool { diff --git a/pkg/provider/config/azure_auth.go b/pkg/provider/config/azure_auth.go index 8ad090e0cb..a9bcbc3c2a 100644 --- a/pkg/provider/config/azure_auth.go +++ b/pkg/provider/config/azure_auth.go @@ -17,24 +17,17 @@ limitations under the License. package config import ( - "crypto/rsa" - "crypto/x509" "errors" "fmt" "io" - "os" "strings" "k8s.io/klog/v2" "sigs.k8s.io/yaml" - "github.com/Azure/azure-sdk-for-go/sdk/azcore" - "github.com/Azure/azure-sdk-for-go/sdk/azidentity" - "github.com/Azure/go-autorest/autorest/adal" "github.com/Azure/go-autorest/autorest/azure" "sigs.k8s.io/cloud-provider-azure/pkg/azclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armauth" "sigs.k8s.io/cloud-provider-azure/pkg/consts" ) @@ -68,240 +61,6 @@ type AzureClientConfig struct { NetworkResourceSubscriptionID string `json:"networkResourceSubscriptionID,omitempty" yaml:"networkResourceSubscriptionID,omitempty"` } -// GetServicePrincipalToken creates a new service principal token based on the configuration. -// -// By default, the cluster and its network resources are deployed in the same AAD Tenant and Subscription, -// and all azure clients use this method to fetch Service Principal Token. -// -// If NetworkResourceTenantID and NetworkResourceSubscriptionID are specified to have different values than TenantID and SubscriptionID, network resources are deployed in different AAD Tenant and Subscription than those for the cluster, -// than only azure clients except VM/VMSS and network resource ones use this method to fetch Token. -// For tokens for VM/VMSS and network resource ones, please check GetMultiTenantServicePrincipalToken and GetNetworkResourceServicePrincipalToken. -func GetServicePrincipalToken(config *AzureClientConfig, env *azure.Environment, resource string) (*adal.ServicePrincipalToken, error) { - logger := klog.Background().WithName("GetServicePrincipalToken") - var tenantID string - if strings.EqualFold(config.IdentitySystem, consts.ADFSIdentitySystem) { - tenantID = consts.ADFSIdentitySystem - } else { - tenantID = config.TenantID - } - - if resource == "" { - resource = env.ServiceManagementEndpoint - } - - if config.UseFederatedWorkloadIdentityExtension { - logger.V(2).Info("Setup ARM general resource token provider", "method", "workload_identity") - oauthConfig, err := adal.NewOAuthConfigWithAPIVersion(env.ActiveDirectoryEndpoint, config.TenantID, nil) - if err != nil { - return nil, fmt.Errorf("failed to create the OAuth config: %w", err) - } - - jwtCallback := func() (string, error) { - jwt, err := os.ReadFile(config.AADFederatedTokenFile) - if err != nil { - return "", fmt.Errorf("failed to read a file with a federated token: %w", err) - } - return string(jwt), nil - } - - token, err := adal.NewServicePrincipalTokenFromFederatedTokenCallback(*oauthConfig, config.AADClientID, jwtCallback, env.ResourceManagerEndpoint) - if err != nil { - return nil, fmt.Errorf("failed to create a workload identity token: %w", err) - } - return token, nil - } - - if config.UseManagedIdentityExtension { - logger.V(2).Info("Setup ARM general resource token provider", "method", "msi") - msiEndpoint, err := adal.GetMSIVMEndpoint() - if err != nil { - return nil, fmt.Errorf("error getting the managed service identity endpoint: %w", err) - } - if len(config.UserAssignedIdentityID) > 0 { - logger.V(2).Info("Parsing user assigned managed identity") - resourceID, err := azure.ParseResourceID(config.UserAssignedIdentityID) - if err == nil && - strings.EqualFold(resourceID.Provider, "Microsoft.ManagedIdentity") && - strings.EqualFold(resourceID.ResourceType, "userAssignedIdentities") { - logger.V(2).Info("Setup with user assigned managed identity", "id-type", "resource_id") - return adal.NewServicePrincipalTokenFromMSIWithIdentityResourceID(msiEndpoint, - resource, - config.UserAssignedIdentityID) - } - - logger.V(2).Info("Setup with user assigned managed identity", "id-type", "client_id") - return adal.NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, - resource, - config.UserAssignedIdentityID) - } - logger.V(2).Info("Setup with system assigned managed identity") - return adal.NewServicePrincipalTokenFromMSI( - msiEndpoint, - resource) - } - - oauthConfig, err := adal.NewOAuthConfigWithAPIVersion(env.ActiveDirectoryEndpoint, tenantID, nil) - if err != nil { - return nil, fmt.Errorf("error creating the OAuth config: %w", err) - } - - if len(config.AADClientSecret) > 0 { - logger.V(2).Info("Setup ARM general resource token provider", "method", "sp_with_password") - return adal.NewServicePrincipalToken( - *oauthConfig, - config.AADClientID, - config.AADClientSecret, - resource) - } - - if len(config.AADClientCertPath) > 0 { - logger.V(2).Info("Setup ARM general resource token provider", "method", "sp_with_certificate") - certData, err := os.ReadFile(config.AADClientCertPath) - if err != nil { - return nil, fmt.Errorf("reading the client certificate from file %s: %w", config.AADClientCertPath, err) - } - certificate, privateKey, err := parseCertificate(certData, config.AADClientCertPassword) - if err != nil { - return nil, fmt.Errorf("decoding the client certificate: %w", err) - } - return adal.NewServicePrincipalTokenFromCertificate( - *oauthConfig, - config.AADClientID, - certificate, - privateKey, - resource) - } - - logger.V(2).Info("No valid auth method found") - - return nil, ErrorNoAuth -} - -// GetMultiTenantServicePrincipalToken is used when (and only when) NetworkResourceTenantID and NetworkResourceSubscriptionID are specified to have different values than TenantID and SubscriptionID. -// -// In that scenario, network resources are deployed in different AAD Tenant and Subscription than those for the cluster, -// and this method creates a new multi-tenant service principal token based on the configuration. -// -// PrimaryToken of the returned multi-tenant token is for the AAD Tenant specified by TenantID, and AuxiliaryToken of the returned multi-tenant token is for the AAD Tenant specified by NetworkResourceTenantID. -// -// Azure VM/VMSS clients use this multi-tenant token, in order to operate those VM/VMSS in AAD Tenant specified by TenantID, and meanwhile in their payload they are referencing network resources (e.g. Load Balancer, Network Security Group, etc.) in AAD Tenant specified by NetworkResourceTenantID. -func GetMultiTenantServicePrincipalToken(config *AzureClientConfig, env *azure.Environment, authProvider *azclient.AuthProvider) (adal.MultitenantOAuthTokenProvider, error) { - logger := klog.Background().WithName("GetMultiTenantServicePrincipalToken") - - err := config.ValidateForMultiTenant() - if err != nil { - return nil, fmt.Errorf("got error getting multi-tenant service principal token: %w", err) - } - - multiTenantOAuthConfig, err := adal.NewMultiTenantOAuthConfig( - env.ActiveDirectoryEndpoint, config.TenantID, []string{config.NetworkResourceTenantID}, adal.OAuthOptions{}) - if err != nil { - return nil, fmt.Errorf("creating the multi-tenant OAuth config: %w", err) - } - - if len(config.AADClientSecret) > 0 && !strings.EqualFold(config.AADClientSecret, "msi") { - logger.V(2).Info("Setup ARM multi-tenant token provider", "method", "sp_with_password") - return adal.NewMultiTenantServicePrincipalToken( - multiTenantOAuthConfig, - config.AADClientID, - config.AADClientSecret, - env.ServiceManagementEndpoint) - } - - if len(config.AADClientCertPath) > 0 { - logger.V(2).Info("Setup ARM multi-tenant token provider", "method", "sp_with_certificate") - certData, err := os.ReadFile(config.AADClientCertPath) - if err != nil { - return nil, fmt.Errorf("reading the client certificate from file %s: %w", config.AADClientCertPath, err) - } - certificate, privateKey, err := parseCertificate(certData, config.AADClientCertPassword) - if err != nil { - return nil, fmt.Errorf("decoding the client certificate: %w", err) - } - return adal.NewMultiTenantServicePrincipalTokenFromCertificate( - multiTenantOAuthConfig, - config.AADClientID, - certificate, - privateKey, - env.ServiceManagementEndpoint) - } - - if authProvider.ComputeCredential != nil && authProvider.NetworkCredential != nil { - logger.V(2).Info("Setup ARM multi-tenant token provider", "method", "msi_with_auxiliary_token") - return armauth.NewMultiTenantTokenProvider( - klog.Background().WithName("multi-tenant-resource-token-provider"), - authProvider.ComputeCredential, - []azcore.TokenCredential{authProvider.NetworkCredential}, - authProvider.DefaultTokenScope(), - ) - } - - logger.V(2).Info("No valid auth method found") - - return nil, ErrorNoAuth -} - -// GetNetworkResourceServicePrincipalToken is used when (and only when) NetworkResourceTenantID and NetworkResourceSubscriptionID are specified to have different values than TenantID and SubscriptionID. -// -// In that scenario, network resources are deployed in different AAD Tenant and Subscription than those for the cluster, -// and this method creates a new service principal token for network resources tenant based on the configuration. -// -// Azure network resource (Load Balancer, Public IP, Route Table, Network Security Group and their sub level resources) clients use this multi-tenant token, in order to operate resources in AAD Tenant specified by NetworkResourceTenantID. -func GetNetworkResourceServicePrincipalToken(config *AzureClientConfig, env *azure.Environment, authProvider *azclient.AuthProvider) (adal.OAuthTokenProvider, error) { - logger := klog.Background().WithName("GetNetworkResourceServicePrincipalToken") - - err := config.ValidateForMultiTenant() - if err != nil { - return nil, fmt.Errorf("got error(%w) in getting network resources service principal token", err) - } - - oauthConfig, err := adal.NewOAuthConfigWithAPIVersion(env.ActiveDirectoryEndpoint, config.NetworkResourceTenantID, nil) - if err != nil { - return nil, fmt.Errorf("creating the OAuth config for network resources tenant: %w", err) - } - - if len(config.AADClientSecret) > 0 && !strings.EqualFold(config.AADClientSecret, "msi") { - logger.V(2).Info("Setup ARM network resource token provider", "method", "sp_with_password") - return adal.NewServicePrincipalToken( - *oauthConfig, - config.AADClientID, - config.AADClientSecret, - env.ServiceManagementEndpoint) - } - - if len(config.AADClientCertPath) > 0 { - logger.V(2).Info("Setup ARM network resource token provider", "method", "sp_with_certificate") - certData, err := os.ReadFile(config.AADClientCertPath) - if err != nil { - return nil, fmt.Errorf("reading the client certificate from file %s: %w", config.AADClientCertPath, err) - } - certificate, privateKey, err := parseCertificate(certData, config.AADClientCertPassword) - if err != nil { - return nil, fmt.Errorf("decoding the client certificate: %w", err) - } - return adal.NewServicePrincipalTokenFromCertificate( - *oauthConfig, - config.AADClientID, - certificate, - privateKey, - env.ServiceManagementEndpoint) - } - - if authProvider.ComputeCredential != nil && authProvider.NetworkCredential != nil { - logger.V(2).Info("Setup ARM network resource token provider", "method", "msi_with_auxiliary_token") - - return armauth.NewTokenProvider( - klog.Background().WithName("network-resource-token-provider"), - authProvider.NetworkCredential, - authProvider.DefaultTokenScope(), - ) - } - - logger.V(2).Info("No valid auth method found") - - return nil, ErrorNoAuth -} - // ParseAzureEnvironment returns the azure environment. // If 'resourceManagerEndpoint' is set, the environment is computed by querying the cloud's resource manager endpoint. // Otherwise, a pre-defined Environment is looked up by name. @@ -392,32 +151,3 @@ func (config *AzureClientConfig) ValidateForMultiTenant() error { return nil } - -// parseCertificate extracts the x509 certificate and RSA private key from the provided PFX or PEM data. -// The cert data must contain a private key along with a certificate whose public key matches that of the -// private key or an error is returned. -func parseCertificate(certData []byte, password string) (*x509.Certificate, *rsa.PrivateKey, error) { - certificates, privateKey, err := azidentity.ParseCertificates(certData, []byte(password)) - if err != nil { - return nil, nil, err - } - - rsaPrivateKey, ok := privateKey.(*rsa.PrivateKey) - if !ok { - return nil, nil, fmt.Errorf("failed to parse certificate: private key is not RSA") - } - - // find the certificate with the matching public key of private key - for _, cert := range certificates { - certKey, ok := cert.PublicKey.(*rsa.PublicKey) - if !ok { - continue - } - if rsaPrivateKey.E == certKey.E && rsaPrivateKey.N.Cmp(certKey.N) == 0 { - // found a match - return cert, rsaPrivateKey, nil - } - } - - return nil, nil, fmt.Errorf("failed to parse certificate: cannot find public key for private key") -} diff --git a/pkg/provider/config/azure_auth_test.go b/pkg/provider/config/azure_auth_test.go index bd4676a475..b52226a920 100644 --- a/pkg/provider/config/azure_auth_test.go +++ b/pkg/provider/config/azure_auth_test.go @@ -17,16 +17,8 @@ limitations under the License. package config import ( - "crypto/rsa" - "fmt" - "net/http" - "net/http/httptest" - "os" "testing" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" - "github.com/Azure/azure-sdk-for-go/sdk/azidentity" - "github.com/Azure/go-autorest/autorest/adal" "github.com/Azure/go-autorest/autorest/azure" "github.com/stretchr/testify/assert" @@ -61,558 +53,6 @@ var ( } ) -const ( - // envMSIEndpoint is the environment variable used to store the endpoint in go-autorest/adal library. - envMSIEndpoint = "MSI_ENDPOINT" - // envMSISecret is the environment variable used to store the request secret in go-autorest/adal library. - envMSISecret = "MSI_SECRET" -) - -func TestGetServicePrincipalToken(t *testing.T) { - env := &azure.PublicCloud - setupLocalMSIServer := func(t *testing.T) (*httptest.Server, func()) { - t.Helper() - var ( - server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodGet, r.Method) - w.WriteHeader(http.StatusOK) - _, err := w.Write([]byte("{}")) - assert.NoError(t, err) - })) - originalEnv = os.Getenv(envMSIEndpoint) - originalSecret = os.Getenv(envMSISecret) - - cleanUp = func() { - server.Close() - _ = os.Setenv(envMSIEndpoint, originalEnv) - _ = os.Setenv(envMSISecret, originalSecret) - } - ) - - _ = os.Setenv(envMSIEndpoint, server.URL) - _ = os.Setenv(envMSISecret, "secret") - - return server, cleanUp - } - - t.Run("setup with MSI (user assigned managed identity)", func(t *testing.T) { - type IDType int - const ( - ResourceID IDType = iota - ClientID - ) - - tests := []struct { - Name string - Type IDType - Config *AzureClientConfig - }{ - { - Name: "client id", - Type: ClientID, - Config: &AzureClientConfig{ - AzureAuthConfig: azclient.AzureAuthConfig{ - UseManagedIdentityExtension: true, - UserAssignedIdentityID: "00000000-0000-0000-0000-000000000000", - }, - }, - }, - { - Name: "client id with SP (SP config should be ignored)", - Type: ClientID, - Config: &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - UseManagedIdentityExtension: true, - UserAssignedIdentityID: "00000000-0000-0000-0000-000000000000", - AADClientID: "AADClientID", - AADClientSecret: "AADClientSecret", - }, - }, - }, - { - Name: "resource id", - Type: ResourceID, - Config: &AzureClientConfig{ - AzureAuthConfig: azclient.AzureAuthConfig{ - UseManagedIdentityExtension: true, - UserAssignedIdentityID: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/ua", - }, - }, - }, - { - Name: "resource id with SP (SP config should be ignored)", - Type: ResourceID, - Config: &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - UseManagedIdentityExtension: true, - UserAssignedIdentityID: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/ua", - AADClientID: "AADClientID", - AADClientSecret: "AADClientSecret", - }, - }, - }, - } - - for _, tt := range tests { - t.Run(tt.Name, func(t *testing.T) { - _, cleanUp := setupLocalMSIServer(t) - defer cleanUp() - - token, err := GetServicePrincipalToken(tt.Config, env, "") - assert.NoError(t, err) - - msiEndpoint, err := adal.GetMSIVMEndpoint() - assert.NoError(t, err) - - switch tt.Type { - case ClientID: - spt, err := adal.NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, - env.ServiceManagementEndpoint, tt.Config.UserAssignedIdentityID) - assert.NoError(t, err) - assert.Equal(t, token, spt) - case ResourceID: - spt, err := adal.NewServicePrincipalTokenFromMSIWithIdentityResourceID(msiEndpoint, - env.ServiceManagementEndpoint, tt.Config.UserAssignedIdentityID) - assert.NoError(t, err) - assert.Equal(t, token, spt) - } - }) - } - }) - - t.Run("setup with MSI (system managed identity)", func(t *testing.T) { - tests := []struct { - Name string - Config *AzureClientConfig - }{ - { - Name: "default", - Config: &AzureClientConfig{ - AzureAuthConfig: azclient.AzureAuthConfig{ - UseManagedIdentityExtension: true, - }, - }, - }, - { - Name: "with SP (SP config should be ignored", - Config: &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - UseManagedIdentityExtension: true, - AADClientID: "AADClientID", - AADClientSecret: "AADClientSecret", - }, - }, - }, - } - - for _, tt := range tests { - t.Run(tt.Name, func(t *testing.T) { - _, cleanUp := setupLocalMSIServer(t) - defer cleanUp() - - token, err := GetServicePrincipalToken(tt.Config, env, "") - assert.NoError(t, err) - - msiEndpoint, err := adal.GetMSIVMEndpoint() - assert.NoError(t, err) - - spt, err := adal.NewServicePrincipalTokenFromMSI(msiEndpoint, env.ServiceManagementEndpoint) - assert.NoError(t, err) - assert.Equal(t, token, spt) - - }) - } - }) - - t.Run("setup with workload identity", func(t *testing.T) { - config := &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - AADClientID: "AADClientID", - AADFederatedTokenFile: "/tmp/federated-token", - UseFederatedWorkloadIdentityExtension: true, - }, - } - env := &azure.PublicCloud - - token, err := GetServicePrincipalToken(config, env, "") - assert.NoError(t, err) - marshalToken, _ := token.MarshalJSON() - - oauthConfig, err := adal.NewOAuthConfigWithAPIVersion(env.ActiveDirectoryEndpoint, config.TenantID, nil) - assert.NoError(t, err) - - jwtCallback := func() (string, error) { - jwt, err := os.ReadFile(config.AADFederatedTokenFile) - if err != nil { - return "", fmt.Errorf("failed to read a file with a federated token: %w", err) - } - return string(jwt), nil - } - - spt, err := adal.NewServicePrincipalTokenFromFederatedTokenCallback(*oauthConfig, config.AADClientID, jwtCallback, env.ResourceManagerEndpoint) - assert.NoError(t, err) - - marshalSpt, _ := spt.MarshalJSON() - - assert.Equal(t, marshalToken, marshalSpt) - }) - - t.Run("setup with SP with password", func(t *testing.T) { - config := &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - AADClientID: "AADClientID", - AADClientSecret: "AADClientSecret", - }, - } - env := &azure.PublicCloud - - token, err := GetServicePrincipalToken(config, env, "") - assert.NoError(t, err) - - oauthConfig, err := adal.NewOAuthConfigWithAPIVersion(env.ActiveDirectoryEndpoint, config.TenantID, nil) - assert.NoError(t, err) - - spt, err := adal.NewServicePrincipalToken(*oauthConfig, config.AADClientID, config.AADClientSecret, env.ServiceManagementEndpoint) - assert.NoError(t, err) - - assert.Equal(t, token, spt) - }) - - t.Run("setup with SP with certificate", func(t *testing.T) { - config := &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - AADClientID: "AADClientID", - AADClientCertPath: "./testdata/test.pfx", - AADClientCertPassword: "id", - }, - } - env := &azure.PublicCloud - token, err := GetServicePrincipalToken(config, env, "") - assert.NoError(t, err) - - oauthConfig, err := adal.NewOAuthConfigWithAPIVersion(env.ActiveDirectoryEndpoint, config.TenantID, nil) - assert.NoError(t, err) - pfxContent, err := os.ReadFile("./testdata/test.pfx") - assert.NoError(t, err) - certificates, privateKey, err := azidentity.ParseCertificates(pfxContent, []byte("id")) - assert.NoError(t, err) - spt, err := adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, config.AADClientID, certificates[0], privateKey.(*rsa.PrivateKey), env.ServiceManagementEndpoint) - assert.NoError(t, err) - assert.Equal(t, token, spt) - }) - - t.Run("setup with SP with certificate has no password", func(t *testing.T) { - config := &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - AADClientID: "AADClientID", - AADClientCertPath: "./testdata/testnopassword.pfx", - }, - } - env := &azure.PublicCloud - token, err := GetServicePrincipalToken(config, env, "") - assert.NoError(t, err) - - oauthConfig, err := adal.NewOAuthConfigWithAPIVersion(env.ActiveDirectoryEndpoint, config.TenantID, nil) - assert.NoError(t, err) - pfxContent, err := os.ReadFile("./testdata/testnopassword.pfx") - assert.NoError(t, err) - certificates, privateKey, err := azidentity.ParseCertificates(pfxContent, nil) - assert.NoError(t, err) - spt, err := adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, config.AADClientID, certificates[0], privateKey.(*rsa.PrivateKey), env.ServiceManagementEndpoint) - assert.NoError(t, err) - assert.Equal(t, token, spt) - }) - - t.Run("setup with SP with certificate has multi public key", func(t *testing.T) { - config := &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - AADClientID: "AADClientID", - AADClientCertPath: "./testdata/testmultipublickey.pem", - }, - } - env := &azure.PublicCloud - token, err := GetServicePrincipalToken(config, env, "") - assert.NoError(t, err) - - oauthConfig, err := adal.NewOAuthConfigWithAPIVersion(env.ActiveDirectoryEndpoint, config.TenantID, nil) - assert.NoError(t, err) - pfxContent, err := os.ReadFile("./testdata/testmultipublickey.pem") - assert.NoError(t, err) - certificates, privateKey, err := azidentity.ParseCertificates(pfxContent, nil) - assert.NoError(t, err) - // expected public key is in second bag - certificate := certificates[1] - spt, err := adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, config.AADClientID, certificate, privateKey.(*rsa.PrivateKey), env.ServiceManagementEndpoint) - assert.NoError(t, err) - assert.Equal(t, token, spt) - }) - - t.Run("setup with SP with certificate has no public key", func(t *testing.T) { - config := &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - AADClientID: "AADClientID", - AADClientCertPath: "./testdata/testnopublickey.pem", - }, - } - env := &azure.PublicCloud - _, err := GetServicePrincipalToken(config, env, "") - assert.Error(t, err) - }) -} - -func TestGetMultiTenantServicePrincipalToken(t *testing.T) { - t.Run("setup with SP with password", func(t *testing.T) { - config := &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - NetworkResourceTenantID: "NetworkResourceTenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - AADClientID: "AADClientID", - AADClientSecret: "AADClientSecret", - }, - NetworkResourceSubscriptionID: "NetworkResourceSubscriptionID", - } - env := &azure.PublicCloud - - multiTenantToken, err := GetMultiTenantServicePrincipalToken(config, env, nil) - assert.NoError(t, err) - - multiTenantOAuthConfig, err := adal.NewMultiTenantOAuthConfig(env.ActiveDirectoryEndpoint, config.TenantID, []string{config.NetworkResourceTenantID}, adal.OAuthOptions{}) - assert.NoError(t, err) - - spt, err := adal.NewMultiTenantServicePrincipalToken(multiTenantOAuthConfig, config.AADClientID, config.AADClientSecret, env.ServiceManagementEndpoint) - assert.NoError(t, err) - - assert.Equal(t, multiTenantToken, spt) - }) - - t.Run("setup with SP with certificate", func(t *testing.T) { - config := &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - NetworkResourceTenantID: "NetworkResourceTenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - AADClientID: "AADClientID", - AADClientCertPath: "./testdata/testnopassword.pfx", - }, - NetworkResourceSubscriptionID: "NetworkResourceSubscriptionID", - } - env := &azure.PublicCloud - - multiTenantToken, err := GetMultiTenantServicePrincipalToken(config, env, nil) - assert.NoError(t, err) - - multiTenantOAuthConfig, err := adal.NewMultiTenantOAuthConfig(env.ActiveDirectoryEndpoint, config.TenantID, []string{config.NetworkResourceTenantID}, adal.OAuthOptions{}) - assert.NoError(t, err) - - pfxContent, err := os.ReadFile("./testdata/testnopassword.pfx") - assert.NoError(t, err) - certificates, privateKey, err := azidentity.ParseCertificates(pfxContent, nil) - assert.NoError(t, err) - spt, err := adal.NewMultiTenantServicePrincipalTokenFromCertificate(multiTenantOAuthConfig, config.AADClientID, certificates[0], privateKey.(*rsa.PrivateKey), env.ServiceManagementEndpoint) - assert.NoError(t, err) - - assert.Equal(t, multiTenantToken, spt) - }) - - t.Run("setup with SP with certificate has no public key", func(t *testing.T) { - config := &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - NetworkResourceTenantID: "NetworkResourceTenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - AADClientID: "AADClientID", - AADClientCertPath: "./testdata/testnopublickey.pem", - }, - NetworkResourceSubscriptionID: "NetworkResourceSubscriptionID", - } - env := &azure.PublicCloud - _, err := GetMultiTenantServicePrincipalToken(config, env, nil) - assert.Error(t, err) - }) - - t.Run("setup with MSI and auxiliary token provider", func(t *testing.T) { - const ( - managedIdentityToken = "managed-identity-token" - networkToken = "network-token" - ) - var ( - cfg = &AzureClientConfig{ - AzureAuthConfig: azclient.AzureAuthConfig{ - UseManagedIdentityExtension: true, - }, - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - NetworkResourceTenantID: "NetworkResourceTenantID", - }, - } - authProvider = &azclient.AuthProvider{ - ComputeCredential: NewDummyTokenCredential(managedIdentityToken), - NetworkCredential: NewDummyTokenCredential(networkToken), - CloudConfig: cloud.AzurePublic, - } - ) - - token, err := GetMultiTenantServicePrincipalToken(cfg, &azure.PublicCloud, authProvider) - assert.NoError(t, err) - - assert.Equal(t, managedIdentityToken, token.PrimaryOAuthToken()) - auxTokens := token.AuxiliaryOAuthTokens() - assert.Len(t, auxTokens, 1) - assert.Equal(t, networkToken, auxTokens[0]) - }) - - t.Run("invalid config", func(t *testing.T) { - env := &azure.PublicCloud - for _, config := range CrossTenantNetworkResourceNegativeConfig { - _, err := GetMultiTenantServicePrincipalToken(config, env, nil) - assert.Error(t, err) - } - }) -} - -func TestGetNetworkResourceServicePrincipalToken(t *testing.T) { - - t.Run("setup with SP with password", func(t *testing.T) { - config := &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - NetworkResourceTenantID: "NetworkResourceTenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - AADClientID: "AADClientID", - AADClientSecret: "AADClientSecret", - }, - NetworkResourceSubscriptionID: "NetworkResourceSubscriptionID", - } - env := &azure.PublicCloud - - token, err := GetNetworkResourceServicePrincipalToken(config, env, nil) - assert.NoError(t, err) - - oauthConfig, err := adal.NewOAuthConfigWithAPIVersion(env.ActiveDirectoryEndpoint, config.NetworkResourceTenantID, nil) - assert.NoError(t, err) - - spt, err := adal.NewServicePrincipalToken(*oauthConfig, config.AADClientID, config.AADClientSecret, env.ServiceManagementEndpoint) - assert.NoError(t, err) - - assert.Equal(t, token, spt) - }) - - t.Run("setup with SP with certificate", func(t *testing.T) { - config := &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - NetworkResourceTenantID: "NetworkResourceTenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - AADClientID: "AADClientID", - AADClientCertPath: "./testdata/testnopassword.pfx", - }, - NetworkResourceSubscriptionID: "NetworkResourceSubscriptionID", - } - env := &azure.PublicCloud - - token, err := GetNetworkResourceServicePrincipalToken(config, env, nil) - assert.NoError(t, err) - - oauthConfig, err := adal.NewOAuthConfigWithAPIVersion(env.ActiveDirectoryEndpoint, config.NetworkResourceTenantID, nil) - assert.NoError(t, err) - - pfxContent, err := os.ReadFile("./testdata/testnopassword.pfx") - assert.NoError(t, err) - certificates, privateKey, err := azidentity.ParseCertificates(pfxContent, nil) - assert.NoError(t, err) - spt, err := adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, config.AADClientID, certificates[0], privateKey.(*rsa.PrivateKey), env.ServiceManagementEndpoint) - assert.NoError(t, err) - - assert.Equal(t, token, spt) - }) - - t.Run("setup with SP with certificate has no public key", func(t *testing.T) { - config := &AzureClientConfig{ - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - NetworkResourceTenantID: "NetworkResourceTenantID", - }, - AzureAuthConfig: azclient.AzureAuthConfig{ - AADClientID: "AADClientID", - AADClientCertPath: "./testdata/testnopublickey.pem", - }, - NetworkResourceSubscriptionID: "NetworkResourceSubscriptionID", - } - env := &azure.PublicCloud - - _, err := GetNetworkResourceServicePrincipalToken(config, env, nil) - assert.Error(t, err) - }) - - t.Run("setup with MSI and auxiliary token provider", func(t *testing.T) { - const ( - managedIdentityToken = "managed-identity-token" - networkToken = "network-token" - ) - var ( - cfg = &AzureClientConfig{ - AzureAuthConfig: azclient.AzureAuthConfig{ - UseManagedIdentityExtension: true, - }, - ARMClientConfig: azclient.ARMClientConfig{ - TenantID: "TenantID", - NetworkResourceTenantID: "NetworkResourceTenantID", - }, - } - authProvider = &azclient.AuthProvider{ - ComputeCredential: NewDummyTokenCredential(managedIdentityToken), - NetworkCredential: NewDummyTokenCredential(networkToken), - CloudConfig: cloud.AzurePublic, - } - ) - - token, err := GetNetworkResourceServicePrincipalToken(cfg, &azure.PublicCloud, authProvider) - assert.NoError(t, err) - assert.Equal(t, networkToken, token.OAuthToken()) - }) - - t.Run("invalid config", func(t *testing.T) { - env := &azure.PublicCloud - for _, config := range CrossTenantNetworkResourceNegativeConfig { - _, err := GetNetworkResourceServicePrincipalToken(config, env, nil) - assert.Error(t, err) - } - }) -} - func TestParseAzureEnvironment(t *testing.T) { cases := []struct { cloudName string diff --git a/pkg/provider/loadbalancer/accesscontrol.go b/pkg/provider/loadbalancer/accesscontrol.go index 71c1ad72f9..259edd5665 100644 --- a/pkg/provider/loadbalancer/accesscontrol.go +++ b/pkg/provider/loadbalancer/accesscontrol.go @@ -98,7 +98,7 @@ func NewAccessControl(logger logr.Logger, svc *v1.Service, sg *armnetwork.Securi allowedServiceTags := AllowedServiceTags(svc) securityRuleDestinationPortsByProtocol, err := SecurityRuleDestinationPortsByProtocol(svc) if err != nil { - logger.Error(err, "Failed to parse service spec.Ports") + logger.Error(err, "Failed to parse service Spec.Ports") return nil, err } if len(sourceRanges) > 0 && len(allowedIPRanges) > 0 { diff --git a/pkg/provider/securitygroup/securitygroup.go b/pkg/provider/securitygroup/securitygroup.go index 7ed4be70ff..f2d579b42a 100644 --- a/pkg/provider/securitygroup/securitygroup.go +++ b/pkg/provider/securitygroup/securitygroup.go @@ -326,8 +326,7 @@ func (helper *RuleHelper) RemoveDestinationFromRules( } func (helper *RuleHelper) removeDestinationFromRule(rule *armnetwork.SecurityRule, prefixes []string, retainDstPorts []int32) error { - logger := helper.logger.WithName("removeDestinationFromRule"). - WithValues("security-rule-name", rule.Name) + logger := helper.logger.WithName("removeDestinationFromRule").WithValues("security-rule-name", rule.Name) var ( prefixIndex = fnutil.IndexSet(prefixes) // Used to check whether the prefix should be removed. diff --git a/pkg/provider/virtualmachine/virtualmachine.go b/pkg/provider/virtualmachine/virtualmachine.go index f9b482298f..9ba8b39091 100644 --- a/pkg/provider/virtualmachine/virtualmachine.go +++ b/pkg/provider/virtualmachine/virtualmachine.go @@ -17,8 +17,7 @@ limitations under the License. package virtualmachine import ( - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -50,8 +49,8 @@ func ByVMSS(vmssName string) ManageOption { type VirtualMachine struct { Variant Variant - vm *compute.VirtualMachine - vmssVM *compute.VirtualMachineScaleSetVM + vm *armcompute.VirtualMachine + vmssVM *armcompute.VirtualMachineScaleSetVM Manage Manage VMSSName string @@ -62,22 +61,22 @@ type VirtualMachine struct { Name string Location string Tags map[string]string - Zones []string + Zones []*string Type string - Plan *compute.Plan - Resources *[]compute.VirtualMachineExtension + Plan *armcompute.Plan + Resources []*armcompute.VirtualMachineExtension // fields of VirtualMachine - Identity *compute.VirtualMachineIdentity - VirtualMachineProperties *compute.VirtualMachineProperties + Identity *armcompute.VirtualMachineIdentity + VirtualMachineProperties *armcompute.VirtualMachineProperties // fields of VirtualMachineScaleSetVM InstanceID string - SKU *compute.Sku - VirtualMachineScaleSetVMProperties *compute.VirtualMachineScaleSetVMProperties + SKU *armcompute.SKU + VirtualMachineScaleSetVMProperties *armcompute.VirtualMachineScaleSetVMProperties } -func FromVirtualMachine(vm *compute.VirtualMachine, opt ...ManageOption) *VirtualMachine { +func FromVirtualMachine(vm *armcompute.VirtualMachine, opt ...ManageOption) *VirtualMachine { v := &VirtualMachine{ vm: vm, Variant: VariantVirtualMachine, @@ -87,12 +86,12 @@ func FromVirtualMachine(vm *compute.VirtualMachine, opt ...ManageOption) *Virtua Type: ptr.Deref(vm.Type, ""), Location: ptr.Deref(vm.Location, ""), Tags: stringMap(vm.Tags), - Zones: stringSlice(vm.Zones), + Zones: vm.Zones, Plan: vm.Plan, Resources: vm.Resources, Identity: vm.Identity, - VirtualMachineProperties: vm.VirtualMachineProperties, + VirtualMachineProperties: vm.Properties, } for _, opt := range opt { @@ -102,7 +101,7 @@ func FromVirtualMachine(vm *compute.VirtualMachine, opt ...ManageOption) *Virtua return v } -func FromVirtualMachineScaleSetVM(vm *compute.VirtualMachineScaleSetVM, opt ManageOption) *VirtualMachine { +func FromVirtualMachineScaleSetVM(vm *armcompute.VirtualMachineScaleSetVM, opt ManageOption) *VirtualMachine { v := &VirtualMachine{ Variant: VariantVirtualMachineScaleSetVM, vmssVM: vm, @@ -112,13 +111,13 @@ func FromVirtualMachineScaleSetVM(vm *compute.VirtualMachineScaleSetVM, opt Mana Type: ptr.Deref(vm.Type, ""), Location: ptr.Deref(vm.Location, ""), Tags: stringMap(vm.Tags), - Zones: stringSlice(vm.Zones), + Zones: vm.Zones, Plan: vm.Plan, Resources: vm.Resources, - SKU: vm.Sku, + SKU: vm.SKU, InstanceID: ptr.Deref(vm.InstanceID, ""), - VirtualMachineScaleSetVMProperties: vm.VirtualMachineScaleSetVMProperties, + VirtualMachineScaleSetVMProperties: vm.Properties, } // TODO: should validate manage option @@ -140,40 +139,40 @@ func (vm *VirtualMachine) ManagedByVMSS() bool { return vm.Manage == VMSS } -func (vm *VirtualMachine) AsVirtualMachine() *compute.VirtualMachine { +func (vm *VirtualMachine) AsVirtualMachine() *armcompute.VirtualMachine { return vm.vm } -func (vm *VirtualMachine) AsVirtualMachineScaleSetVM() *compute.VirtualMachineScaleSetVM { +func (vm *VirtualMachine) AsVirtualMachineScaleSetVM() *armcompute.VirtualMachineScaleSetVM { return vm.vmssVM } -func (vm *VirtualMachine) GetInstanceViewStatus() *[]compute.InstanceViewStatus { +func (vm *VirtualMachine) GetInstanceViewStatus() []*armcompute.InstanceViewStatus { if vm.IsVirtualMachine() && vm.vm != nil && - vm.vm.VirtualMachineProperties != nil && - vm.vm.VirtualMachineProperties.InstanceView != nil { - return vm.vm.VirtualMachineProperties.InstanceView.Statuses + vm.vm.Properties != nil && + vm.vm.Properties.InstanceView != nil { + return vm.vm.Properties.InstanceView.Statuses } if vm.IsVirtualMachineScaleSetVM() && vm.vmssVM != nil && - vm.vmssVM.VirtualMachineScaleSetVMProperties != nil && - vm.vmssVM.VirtualMachineScaleSetVMProperties.InstanceView != nil { - return vm.vmssVM.VirtualMachineScaleSetVMProperties.InstanceView.Statuses + vm.vmssVM.Properties != nil && + vm.vmssVM.Properties.InstanceView != nil { + return vm.vmssVM.Properties.InstanceView.Statuses } return nil } func (vm *VirtualMachine) GetProvisioningState() string { if vm.IsVirtualMachine() && vm.vm != nil && - vm.vm.VirtualMachineProperties != nil && - vm.vm.VirtualMachineProperties.ProvisioningState != nil { - return *vm.vm.VirtualMachineProperties.ProvisioningState + vm.vm.Properties != nil && + vm.vm.Properties.ProvisioningState != nil { + return *vm.vm.Properties.ProvisioningState } if vm.IsVirtualMachineScaleSetVM() && vm.vmssVM != nil && - vm.vmssVM.VirtualMachineScaleSetVMProperties != nil && - vm.vmssVM.VirtualMachineScaleSetVMProperties.ProvisioningState != nil { - return *vm.vmssVM.VirtualMachineScaleSetVMProperties.ProvisioningState + vm.vmssVM.Properties != nil && + vm.vmssVM.Properties.ProvisioningState != nil { + return *vm.vmssVM.Properties.ProvisioningState } return consts.ProvisioningStateUnknown } @@ -191,12 +190,3 @@ func stringMap(msp map[string]*string) map[string]string { } return ms } - -// stringSlice returns a string slice value for the passed string slice pointer. It returns a nil -// slice if the pointer is nil. -func stringSlice(s *[]string) []string { - if s != nil { - return *s - } - return nil -} diff --git a/pkg/retry/azure_error.go b/pkg/retry/azure_error.go deleted file mode 100644 index 923e33de0d..0000000000 --- a/pkg/retry/azure_error.go +++ /dev/null @@ -1,433 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package retry - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - "regexp" - "strconv" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest/azure" - - "k8s.io/klog/v2" - - "sigs.k8s.io/cloud-provider-azure/pkg/consts" -) - -// RateLimited error string -const RateLimited = "rate limited" - -var ( - // The function to get current time. - now = time.Now - - // StatusCodesForRetry are a defined group of status code for which the client will retry. - StatusCodesForRetry = []int{ - http.StatusRequestTimeout, // 408 - http.StatusInternalServerError, // 500 - http.StatusBadGateway, // 502 - http.StatusServiceUnavailable, // 503 - http.StatusGatewayTimeout, // 504 - } -) - -// Error indicates an error returned by Azure APIs. -type Error struct { - // Retriable indicates whether the request is retriable. - Retriable bool - // HTTPStatusCode indicates the response HTTP status code. - HTTPStatusCode int - // RetryAfter indicates the time when the request should retry after throttling. - // A throttled request is retriable. - RetryAfter time.Time - // RetryAfter indicates the raw error from API. - RawError error -} - -// Error returns the error. -// Note that Error doesn't implement error interface because (nil *Error) != (nil error). -func (err *Error) Error() error { - if err == nil { - return nil - } - - // Convert time to seconds for better logging. - retryAfterSeconds := 0 - curTime := now() - if err.RetryAfter.After(curTime) { - retryAfterSeconds = int(err.RetryAfter.Sub(curTime) / time.Second) - } - - return fmt.Errorf("Retriable: %v, RetryAfter: %ds, HTTPStatusCode: %d, RawError: %w", - err.Retriable, retryAfterSeconds, err.HTTPStatusCode, err.RawError) -} - -// IsThrottled returns true the if the request is being throttled. -func (err *Error) IsThrottled() bool { - if err == nil { - return false - } - - return err.HTTPStatusCode == http.StatusTooManyRequests || err.RetryAfter.After(now()) -} - -// IsNotFound returns true the if the requested object wasn't found -func (err *Error) IsNotFound() bool { - if err == nil { - return false - } - - return err.HTTPStatusCode == http.StatusNotFound -} - -// NewError creates a new Error. -func NewError(retriable bool, err error) *Error { - return &Error{ - Retriable: retriable, - RawError: err, - } -} - -// NewError creates a new Error. Returns nil if err is nil -func NewErrorOrNil(retriable bool, err error) *Error { - if err == nil { - return nil - } - return NewError(retriable, err) -} - -// GetRetriableError gets new retriable Error. -func GetRetriableError(err error) *Error { - return &Error{ - Retriable: true, - RawError: err, - } -} - -// GetRateLimitError creates a new error for rate limiting. -func GetRateLimitError(isWrite bool, opName string) *Error { - opType := "read" - if isWrite { - opType = "write" - } - return GetRetriableError(fmt.Errorf("azure cloud provider %s(%s) for operation %q", RateLimited, opType, opName)) -} - -// GetThrottlingError creates a new error for throttling. -func GetThrottlingError(operation, reason string, retryAfter time.Time) *Error { - rawError := fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", operation, reason) - return &Error{ - Retriable: true, - RawError: rawError, - RetryAfter: retryAfter, - } -} - -// GetError gets a new Error based on resp and error. -func GetError(resp *http.Response, err error) *Error { - if err == nil && resp == nil { - return nil - } - - if err == nil && resp != nil && IsSuccessHTTPResponse(resp) { - // HTTP 2xx suggests a successful response - return nil - } - - retryAfter := time.Time{} - if retryAfterDuration := getRetryAfter(resp); retryAfterDuration != 0 { - retryAfter = now().Add(retryAfterDuration) - } - return &Error{ - RawError: getRawError(resp, err), - RetryAfter: retryAfter, - Retriable: shouldRetryHTTPRequest(resp, err), - HTTPStatusCode: getHTTPStatusCode(resp), - } -} - -// IsSuccessHTTPResponse determines if the response from an HTTP request suggests success -func IsSuccessHTTPResponse(resp *http.Response) bool { - if resp == nil { - return false - } - - // HTTP 2xx suggests a successful response - if 199 < resp.StatusCode && resp.StatusCode < 300 { - return true - } - - return false -} - -func getRawError(resp *http.Response, err error) error { - if err != nil { - return err - } - - if resp == nil || resp.Body == nil { - return fmt.Errorf("empty HTTP response") - } - - // return the http status if it is unable to get response body. - defer resp.Body.Close() - respBody, _ := io.ReadAll(resp.Body) - resp.Body = io.NopCloser(bytes.NewReader(respBody)) - if len(respBody) == 0 { - return fmt.Errorf("HTTP status code (%d)", resp.StatusCode) - } - - // return the raw response body. - return fmt.Errorf("%s", string(respBody)) -} - -func getHTTPStatusCode(resp *http.Response) int { - if resp == nil { - return -1 - } - - return resp.StatusCode -} - -// shouldRetryHTTPRequest determines if the request is retriable. -func shouldRetryHTTPRequest(resp *http.Response, err error) bool { - if resp != nil { - for _, code := range StatusCodesForRetry { - if resp.StatusCode == code { - return true - } - } - - // should retry on <200, error>. - if IsSuccessHTTPResponse(resp) && err != nil { - return true - } - - return false - } - - // should retry when error is not nil and no http.Response. - if err != nil { - return true - } - - return false -} - -// getRetryAfter gets the retryAfter from http response. -// The value of Retry-After can be either the number of seconds or a date in RFC1123 format. -func getRetryAfter(resp *http.Response) time.Duration { - if resp == nil { - return 0 - } - - ra := resp.Header.Get(consts.RetryAfterHeaderKey) - if ra == "" { - return 0 - } - - var dur time.Duration - if retryAfter, _ := strconv.Atoi(ra); retryAfter > 0 { - dur = time.Duration(retryAfter) * time.Second - } else if t, err := time.Parse(time.RFC1123, ra); err == nil { - dur = t.Sub(now()) - } - return dur -} - -// IsInHTTPStatusCodeSet return true when status code falls in the status code list -// It is used with doBackoffRetry to retry on some HTTPStatusCodes. -func IsInHTTPStatusCodeSet(rerr *Error, httpStatusCodes []int) bool { - if rerr == nil { - return false - } - for _, code := range httpStatusCodes { - if rerr.HTTPStatusCode == code { - return true - } - } - - return false -} - -// isInErrorsSet return true when error message falls in the error message set -// It is used with doBackoffRetry to retry on some errors. -func isInErrorsSet(rerr *Error, errorMsgs []string) bool { - - if rerr == nil { - return false - } - - for _, err := range errorMsgs { - if strings.Contains(rerr.RawError.Error(), err) { - return true - } - } - return false -} - -// GetStatusNotFoundAndForbiddenIgnoredError gets an error with StatusNotFound and StatusForbidden ignored. -// It is only used in DELETE operations. -func GetStatusNotFoundAndForbiddenIgnoredError(resp *http.Response, err error) *Error { - rerr := GetError(resp, err) - if rerr == nil { - return nil - } - - // Returns nil when it is StatusNotFound error. - if rerr.HTTPStatusCode == http.StatusNotFound { - klog.V(3).Infof("Ignoring StatusNotFound error: %+v", rerr) - return nil - } - - // Returns nil if the status code is StatusForbidden. - // This happens when AuthorizationFailed is reported from Azure API. - if rerr.HTTPStatusCode == http.StatusForbidden { - klog.V(3).Infof("Ignoring StatusForbidden error: %+v", rerr) - return nil - } - - return rerr -} - -// IsErrorRetriable returns true if the error is retriable. -func IsErrorRetriable(err error) bool { - if err == nil { - return false - } - - return strings.Contains(err.Error(), "Retriable: true") -} - -// HasStatusForbiddenOrIgnoredError return true if the given error code is part of the error message -// This should only be used when trying to delete resources -func HasStatusForbiddenOrIgnoredError(err error) bool { - if err == nil { - return false - } - - if strings.Contains(err.Error(), fmt.Sprintf("HTTPStatusCode: %d", http.StatusNotFound)) { - return true - } - - if strings.Contains(err.Error(), fmt.Sprintf("HTTPStatusCode: %d", http.StatusForbidden)) { - return true - } - return false -} - -// GetVMSSMetadataByRawError gets the vmss name by parsing the error message -func GetVMSSMetadataByRawError(err *Error) (string, string, error) { - if err == nil || !isErrorLoadBalancerInUseByVirtualMachineScaleSet(err.RawError.Error()) { - return "", "", nil - } - - reg := regexp.MustCompile(`.*/subscriptions/(?:.*)/resourceGroups/(.*)/providers/Microsoft.Compute/virtualMachineScaleSets/(.+).`) - matches := reg.FindStringSubmatch(err.ServiceErrorMessage()) - if len(matches) != 3 { - return "", "", fmt.Errorf("GetVMSSMetadataByRawError: couldn't find a VMSS resource Id from error message %w", err.RawError) - } - - return matches[1], matches[2], nil -} - -// isErrorLoadBalancerInUseByVirtualMachineScaleSet determines if the Error is -// LoadBalancerInUseByVirtualMachineScaleSet -func isErrorLoadBalancerInUseByVirtualMachineScaleSet(rawError string) bool { - return strings.Contains(rawError, "LoadBalancerInUseByVirtualMachineScaleSet") -} - -const ( - // OperationNotAllowed is an umbrella errrfor a lot of errors - OperationNotAllowed string = "OperationNotAllowed" - // QuotaExceeded falls under OperationNotAllowed error code but we make it more specific here - QuotaExceeded string = "QuotaExceeded" -) - -// ServiceRawError wraps the RawError field satisfying autorest.ServiceError -type ServiceRawError struct { - ServiceError *azure.ServiceError `json:"error,omitempty"` -} - -// ServiceErrorMessage returns the message associated with the autorest.ServiceError body -func (err *Error) ServiceErrorMessage() string { - if err == nil || err.RawError == nil { - return "" - } - - sre := ServiceRawError{} - marshalErr := json.Unmarshal([]byte(err.RawError.Error()), &sre) - if marshalErr != nil { - return "" - } - if sre.ServiceError == nil { - return "" - } - return sre.ServiceError.Message -} - -// ServiceErrorCode returns the code associated with the autorest.ServiceError body -func (err *Error) ServiceErrorCode() string { - if err == nil || err.RawError == nil { - return "" - } - - sre := ServiceRawError{} - marshalErr := json.Unmarshal([]byte(err.RawError.Error()), &sre) - if marshalErr != nil { - return "" - } - if sre.ServiceError == nil { - return "" - } - return classifyErrorCode(*sre.ServiceError) -} - -func classifyErrorCode(sre azure.ServiceError) string { - if sre.Code == OperationNotAllowed { - return getOperationNotAllowedReason(sre.Message) - } - return sre.Code -} - -// getOperationNotAllowedReason attempts to better classify OperationNotAllowed errors -// by looking at the message -func getOperationNotAllowedReason(msg string) string { - if strings.Contains(strings.ToLower(msg), strings.ToLower("Quota increase")) { - return QuotaExceeded - } - return OperationNotAllowed -} - -// PartialUpdateError implements error interface. It is meant to be returned for errors with http status code of 2xx -type PartialUpdateError struct { - message string -} - -func NewPartialUpdateError(msg string) *PartialUpdateError { - return &PartialUpdateError{message: msg} -} - -func (e *PartialUpdateError) Error() string { - return e.message -} diff --git a/pkg/retry/azure_error_test.go b/pkg/retry/azure_error_test.go deleted file mode 100644 index 9fa91d334a..0000000000 --- a/pkg/retry/azure_error_test.go +++ /dev/null @@ -1,481 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package retry - -import ( - "bytes" - "errors" - "fmt" - "io" - "net/http" - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -// LBInUseRawError is the LoadBalancerInUseByVirtualMachineScaleSet raw error -const LBInUseRawError = `{ - "error": { - "code": "LoadBalancerInUseByVirtualMachineScaleSet", - "message": "Cannot delete load balancer /subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb since its child resources lb are in use by virtual machine scale set /subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss.", - "details": [] - } -}` - -func TestNewError(t *testing.T) { - rawErr := fmt.Errorf("HTTP status code (404)") - newErr := NewError(true, rawErr) - assert.Equal(t, true, newErr.Retriable) - assert.Equal(t, rawErr, newErr.RawError) -} - -func TestGetRetriableError(t *testing.T) { - rawErr := fmt.Errorf("HTTP status code (404)") - newErr := GetRetriableError(rawErr) - assert.Equal(t, true, newErr.Retriable) - assert.Equal(t, rawErr, newErr.RawError) -} - -func TestGetRateLimitError(t *testing.T) { - opType := "write" - opName := "opNameTest" - rawErr := fmt.Errorf("azure cloud provider rate limited(%s) for operation %q", opType, opName) - newErr := GetRateLimitError(true, opName) - assert.Equal(t, true, newErr.Retriable) - assert.Equal(t, rawErr, newErr.RawError) -} - -func TestGetThrottlingError(t *testing.T) { - operation := "operationtest" - reason := "reasontest" - rawErr := fmt.Errorf("azure cloud provider throttled for operation %s with reason %q", operation, reason) - onehourlater := time.Now().Add(time.Hour * 1) - newErr := GetThrottlingError(operation, reason, onehourlater) - assert.Equal(t, true, newErr.Retriable) - assert.Equal(t, rawErr, newErr.RawError) - assert.Equal(t, onehourlater, newErr.RetryAfter) -} - -func TestGetError(t *testing.T) { - now = func() time.Time { - return time.Time{} - } - - tests := []struct { - code int - retryAfter int - err error - expected *Error - }{ - { - code: http.StatusOK, - expected: nil, - }, - { - code: http.StatusOK, - err: fmt.Errorf("unknown error"), - expected: &Error{ - Retriable: true, - HTTPStatusCode: http.StatusOK, - RawError: fmt.Errorf("unknown error"), - }, - }, - { - code: http.StatusBadRequest, - expected: &Error{ - Retriable: false, - HTTPStatusCode: http.StatusBadRequest, - RawError: fmt.Errorf("some error"), - }, - }, - { - code: http.StatusInternalServerError, - expected: &Error{ - Retriable: true, - HTTPStatusCode: http.StatusInternalServerError, - RawError: fmt.Errorf("some error"), - }, - }, - { - code: http.StatusSeeOther, - err: fmt.Errorf("some error"), - expected: &Error{ - Retriable: false, - HTTPStatusCode: http.StatusSeeOther, - RawError: fmt.Errorf("some error"), - }, - }, - { - code: http.StatusTooManyRequests, - retryAfter: 100, - expected: &Error{ - Retriable: false, - HTTPStatusCode: http.StatusTooManyRequests, - RetryAfter: now().Add(100 * time.Second), - RawError: fmt.Errorf("some error"), - }, - }, - } - - for _, test := range tests { - resp := &http.Response{ - StatusCode: test.code, - Header: http.Header{}, - Body: io.NopCloser(bytes.NewReader([]byte("some error"))), - } - if test.retryAfter != 0 { - resp.Header.Add("Retry-After", fmt.Sprintf("%d", test.retryAfter)) - } - rerr := GetError(resp, test.err) - assert.Equal(t, test.expected, rerr) - } -} - -func TestGetErrorNil(t *testing.T) { - rerr := GetError(nil, nil) - assert.Nil(t, rerr) - - // null body - resp := &http.Response{ - StatusCode: http.StatusBadRequest, - Body: nil, - } - rerr = GetError(resp, nil) - assert.Equal(t, fmt.Errorf("empty HTTP response"), rerr.RawError) -} - -func TestGetStatusNotFoundAndForbiddenIgnoredError(t *testing.T) { - now = func() time.Time { - return time.Time{} - } - - tests := []struct { - code int - retryAfter int - err error - expected *Error - }{ - { - code: http.StatusOK, - expected: nil, - }, - { - code: http.StatusNotFound, - expected: nil, - }, - { - code: http.StatusForbidden, - expected: nil, - }, - { - code: http.StatusOK, - err: fmt.Errorf("some error"), - expected: &Error{ - Retriable: true, - HTTPStatusCode: http.StatusOK, - RawError: fmt.Errorf("some error"), - }, - }, - { - code: http.StatusBadRequest, - expected: &Error{ - Retriable: false, - HTTPStatusCode: http.StatusBadRequest, - RawError: fmt.Errorf("some error"), - }, - }, - { - code: http.StatusInternalServerError, - expected: &Error{ - Retriable: true, - HTTPStatusCode: http.StatusInternalServerError, - RawError: fmt.Errorf("some error"), - }, - }, - { - code: http.StatusSeeOther, - err: fmt.Errorf("some error"), - expected: &Error{ - Retriable: false, - HTTPStatusCode: http.StatusSeeOther, - RawError: fmt.Errorf("some error"), - }, - }, - { - code: http.StatusTooManyRequests, - retryAfter: 100, - expected: &Error{ - Retriable: false, - HTTPStatusCode: http.StatusTooManyRequests, - RetryAfter: now().Add(100 * time.Second), - RawError: fmt.Errorf("some error"), - }, - }, - } - - for _, test := range tests { - resp := &http.Response{ - StatusCode: test.code, - Header: http.Header{}, - Body: io.NopCloser(bytes.NewReader([]byte("some error"))), - } - if test.retryAfter != 0 { - resp.Header.Add("Retry-After", fmt.Sprintf("%d", test.retryAfter)) - } - rerr := GetStatusNotFoundAndForbiddenIgnoredError(resp, test.err) - assert.Equal(t, test.expected, rerr) - } -} - -func TestShouldRetryHTTPRequest(t *testing.T) { - tests := []struct { - code int - err error - expected bool - }{ - { - code: http.StatusBadRequest, - expected: false, - }, - { - code: http.StatusInternalServerError, - expected: true, - }, - { - code: http.StatusOK, - err: fmt.Errorf("some error"), - expected: true, - }, - { - code: http.StatusOK, - expected: false, - }, - { - code: 399, - expected: false, - }, - } - for _, test := range tests { - resp := &http.Response{ - StatusCode: test.code, - } - res := shouldRetryHTTPRequest(resp, test.err) - if res != test.expected { - t.Errorf("expected: %v, saw: %v", test.expected, res) - } - } -} - -func TestIsSuccessResponse(t *testing.T) { - tests := []struct { - code int - expected bool - }{ - { - code: http.StatusNotFound, - expected: false, - }, - { - code: http.StatusInternalServerError, - expected: false, - }, - { - code: http.StatusOK, - expected: true, - }, - } - - for _, test := range tests { - resp := http.Response{ - StatusCode: test.code, - } - res := IsSuccessHTTPResponse(&resp) - if res != test.expected { - t.Errorf("expected: %v, saw: %v", test.expected, res) - } - } -} - -func TestIsSuccessResponseNil(t *testing.T) { - res := IsSuccessHTTPResponse(nil) - assert.Equal(t, false, res) -} - -func TestIsThrottled(t *testing.T) { - tests := []struct { - err *Error - expected bool - }{ - { - err: nil, - expected: false, - }, - { - err: &Error{ - HTTPStatusCode: http.StatusOK, - }, - expected: false, - }, - { - err: &Error{ - HTTPStatusCode: http.StatusTooManyRequests, - }, - expected: true, - }, - { - err: &Error{ - RetryAfter: time.Now().Add(time.Hour), - }, - expected: true, - }, - { - err: &Error{ - RetryAfter: time.Now().Add(0), - }, - expected: true, - }, - } - - for _, test := range tests { - realValue := test.err.IsThrottled() - assert.Equal(t, test.expected, realValue) - } -} - -func TestIsErrorRetriable(t *testing.T) { - // false case - result := IsErrorRetriable(nil) - assert.Equal(t, false, result) - - // true case - result = IsErrorRetriable(fmt.Errorf("Retriable: true")) - assert.Equal(t, true, result) -} - -func TestHasErrorCode(t *testing.T) { - // false case - result := HasStatusForbiddenOrIgnoredError(fmt.Errorf("HTTPStatusCode: 408")) - assert.False(t, result) - - // true case 404 - result = HasStatusForbiddenOrIgnoredError(fmt.Errorf("HTTPStatusCode: %d", http.StatusNotFound)) - assert.True(t, result) - - // true case 403 - result = HasStatusForbiddenOrIgnoredError(fmt.Errorf("HTTPStatusCode: %d", http.StatusForbidden)) - assert.True(t, result) -} - -func TestGetVMSSNameByRawError(t *testing.T) { - rgName, vmssName, err := GetVMSSMetadataByRawError(&Error{RawError: errors.New(LBInUseRawError)}) - assert.NoError(t, err) - assert.Equal(t, "rg", rgName) - assert.Equal(t, "vmss", vmssName) -} - -func TestServiceServiceErrorMessage(t *testing.T) { - now = func() time.Time { - return time.Time{} - } - - tests := []struct { - err *Error - expected string - }{ - { - err: nil, - expected: "", - }, - { - err: &Error{ - Retriable: true, - HTTPStatusCode: http.StatusOK, - RawError: nil, - }, - expected: "", - }, - { - err: &Error{ - RawError: fmt.Errorf("%s", "{\"error\":{\"message\": \"\"}}"), - }, - expected: "", - }, - { - err: &Error{ - RawError: fmt.Errorf("%s", "{\"error\":{\"message\": \"Some error message\"}}"), - }, - expected: "Some error message", - }, - } - - for _, test := range tests { - assert.Equal(t, test.expected, test.err.ServiceErrorMessage()) - } -} - -func TestServiceErrorCode(t *testing.T) { - now = func() time.Time { - return time.Time{} - } - - tests := []struct { - err *Error - expected string - }{ - { - err: nil, - expected: "", - }, - { - err: &Error{ - Retriable: true, - HTTPStatusCode: http.StatusOK, - RawError: nil, - }, - expected: "", - }, - { - err: &Error{ - RawError: fmt.Errorf("%s", "{\"error\":{\"code\": \"\",\"message\": \"Some error message\"}}"), - }, - expected: "", - }, - { - err: &Error{ - RawError: fmt.Errorf("%s", "{\"error\":{\"code\": \"ReadOnlyDisabledSubscription\",\"message\": \"Some error message\"}}"), - }, - expected: "ReadOnlyDisabledSubscription", - }, - { - err: &Error{ - RawError: fmt.Errorf("%s", "{\"error\":{\"code\": \"OperationNotAllowed\",\"message\": \"Another operation is in progress\"}}"), - }, - expected: "OperationNotAllowed", - }, - { - err: &Error{ - RawError: fmt.Errorf("%s", "{\"error\":{\"code\": \"OperationNotAllowed\",\"message\": \"Submit a request for Quota increase at\"}}"), - }, - expected: "QuotaExceeded", - }, - } - - for _, test := range tests { - assert.Equal(t, test.expected, test.err.ServiceErrorCode()) - } -} diff --git a/pkg/retry/azure_retry.go b/pkg/retry/azure_retry.go deleted file mode 100644 index 81eb23a58b..0000000000 --- a/pkg/retry/azure_retry.go +++ /dev/null @@ -1,217 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package retry - -import ( - "html" - "math/rand" - "net/http" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/mocks" - "k8s.io/klog/v2" -) - -// Ensure package autorest/mocks is imported and vendored. -var _ autorest.Sender = mocks.NewSender() - -// Backoff holds parameters applied to a Backoff function. -type Backoff struct { - // The initial duration. - Duration time.Duration - // Duration is multiplied by factor each iteration, if factor is not zero - // and the limits imposed by Steps and Cap have not been reached. - // Should not be negative. - // The jitter does not contribute to the updates to the duration parameter. - Factor float64 - // The sleep at each iteration is the duration plus an additional - // amount chosen uniformly at random from the interval between - // zero and `jitter*duration`. - Jitter float64 - // The remaining number of iterations in which the duration - // parameter may change (but progress can be stopped earlier by - // hitting the cap). If not positive, the duration is not - // changed. Used for exponential backoff in combination with - // Factor and Cap. - Steps int - // A limit on revised values of the duration parameter. If a - // multiplication by the factor parameter would make the duration - // exceed the cap then the duration is set to the cap and the - // steps parameter is set to zero. - Cap time.Duration - // The errors indicate that the request shouldn't do more retrying. - NonRetriableErrors []string - // The RetriableHTTPStatusCodes indicates that the HTTPStatusCode should do more retrying. - RetriableHTTPStatusCodes []int -} - -// NewBackoff creates a new Backoff. -func NewBackoff(duration time.Duration, factor float64, jitter float64, steps int, cap time.Duration) *Backoff { - return &Backoff{ - Duration: duration, - Factor: factor, - Jitter: jitter, - Steps: steps, - Cap: cap, - } -} - -// WithNonRetriableErrors returns a new *Backoff with NonRetriableErrors assigned. -func (b *Backoff) WithNonRetriableErrors(errs []string) *Backoff { - newBackoff := *b - newBackoff.NonRetriableErrors = errs - return &newBackoff -} - -// WithRetriableHTTPStatusCodes returns a new *Backoff with RetriableHTTPStatusCode assigned. -func (b *Backoff) WithRetriableHTTPStatusCodes(httpStatusCodes []int) *Backoff { - newBackoff := *b - newBackoff.RetriableHTTPStatusCodes = httpStatusCodes - return &newBackoff -} - -// Step (1) returns an amount of time to sleep determined by the -// original Duration and Jitter and (2) mutates the provided Backoff -// to update its Steps and Duration. -func (b *Backoff) Step() time.Duration { - if b.Steps < 1 { - if b.Jitter > 0 { - return jitter(b.Duration, b.Jitter) - } - return b.Duration - } - b.Steps-- - - duration := b.Duration - - // calculate the next step - if b.Factor != 0 { - b.Duration = time.Duration(float64(b.Duration) * b.Factor) - if b.Cap > 0 && b.Duration > b.Cap { - b.Duration = b.Cap - b.Steps = 0 - } - } - - if b.Jitter > 0 { - duration = jitter(duration, b.Jitter) - } - return duration -} - -// Jitter returns a time.Duration between duration and duration + maxFactor * -// duration. -// -// This allows clients to avoid converging on periodic behavior. If maxFactor -// is 0.0, a suggested default value will be chosen. -func jitter(duration time.Duration, maxFactor float64) time.Duration { - if maxFactor <= 0.0 { - maxFactor = 1.0 - } - wait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration)) // #nosec G404 - return wait -} - -// DoExponentialBackoffRetry represents an autorest.SendDecorator with backoff retry. -func DoExponentialBackoffRetry(backoff *Backoff) autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - return doBackoffRetry(s, r, *backoff) - }) - } -} - -// doBackoffRetry does the backoff retries for the request. -// backoff is a retry policy here we implicitly copy the backoff policy when args is passed to function. - -func doBackoffRetry(s autorest.Sender, r *http.Request, backoff Backoff) (resp *http.Response, err error) { - rr := autorest.NewRetriableRequest(r) - // Increment to add the first call (attempts denotes number of retries) - for backoff.Steps > 0 { - err = rr.Prepare() - if err != nil { - return resp, err - } - resp, err = s.Do(rr.Request()) - rerr := GetError(resp, err) - // Abort retries in the following scenarios: - // 1) request succeed - // 2) request has been throttled - // 3) request is not retriable or contains non-retriable errors - // 4) request has completed all the retry steps - if rerr == nil { - return resp, nil - } - - if rerr.IsThrottled() { - return resp, rerr.RawError - } - - if !rerr.Retriable { - if IsInHTTPStatusCodeSet(rerr, backoff.RetriableHTTPStatusCodes) || isInErrorsSet(rerr, backoff.NonRetriableErrors) { - rerr.Retriable = true - } else { - return resp, rerr.RawError - } - } - - if backoff.Steps == 1 { - return resp, rerr.RawError - } - - if !delayForBackOff(&backoff, r.Context().Done()) { - if r.Context().Err() != nil { - return resp, r.Context().Err() - } - return resp, rerr.RawError - } - drainErr := autorest.DrainResponseBody(resp) - if drainErr != nil { - klog.V(3).ErrorS(drainErr, "Failed to drain response body") - } - klog.V(3).Infof("Backoff retrying %s %q with error %v", r.Method, html.EscapeString(r.URL.String()), err) - } - - return resp, err -} - -// delayForBackOff invokes time.After for the supplied backoff duration. -// The delay may be canceled by closing the passed channel. If terminated early, returns false. -func delayForBackOff(backoff *Backoff, cancel <-chan struct{}) bool { - d := backoff.Step() - select { - case <-time.After(d): - return true - case <-cancel: - return false - } -} - -// DoFilterOutNonRetriableError decorator works with autorest.DoRetryForAttempts -func DoFilterOutNonRetriableError(shouldRetry func(rerr *Error) bool) autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - rerr := GetError(resp, err) - if rerr != nil && shouldRetry != nil && shouldRetry(rerr) { - return resp, rerr.RawError - } - return resp, nil - }) - } -} diff --git a/pkg/retry/azure_retry_test.go b/pkg/retry/azure_retry_test.go deleted file mode 100644 index 09ce812e04..0000000000 --- a/pkg/retry/azure_retry_test.go +++ /dev/null @@ -1,239 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -package retry - -import ( - "fmt" - "math/rand" - "net/http" - "net/url" - "testing" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/mocks" - "github.com/stretchr/testify/assert" -) - -func TestNewBackoff(t *testing.T) { - expected := &Backoff{Duration: time.Second, Factor: 2, Steps: 0, Cap: 3 * time.Second, Jitter: 0.5} - result := NewBackoff(time.Second, 2, 0.5, 0, 3*time.Second) - assert.Equal(t, expected, result) -} - -func TestWithNonRetriableErrors(t *testing.T) { - bo := &Backoff{Duration: time.Second, Factor: 2, Steps: 0, Cap: 3 * time.Second, Jitter: 0.5} - errs := []string{"error1", "error2"} - expected := bo - expected.NonRetriableErrors = errs - result := bo.WithNonRetriableErrors(errs) - assert.Equal(t, expected, result) -} - -func TestWithRetriableHTTPStatusCodes(t *testing.T) { - bo := &Backoff{Duration: time.Second, Factor: 2, Steps: 0, Cap: 3 * time.Second, Jitter: 0.5} - httpStatusCodes := []int{http.StatusOK, http.StatusTooManyRequests} - expected := bo - expected.RetriableHTTPStatusCodes = httpStatusCodes - result := bo.WithRetriableHTTPStatusCodes(httpStatusCodes) - assert.Equal(t, expected, result) -} - -func TestJitterWithNegativeMaxFactor(t *testing.T) { - // jitter := duration + time.Duration(rand.Float64()*maxFactor*float64(duration)) - // If maxFactor is 0.0 or less than 0.0, a suggested default value will be chosen. - // rand.Float64() returns, as a float64, a pseudo-random number in [0.0,1.0). - duration := time.Second - maxFactor := -3.0 - res := jitter(duration, maxFactor) - defaultMaxFactor := 1.0 - expected := jitter(duration, defaultMaxFactor) - gap := expected - res - assert.Lessf(t, gap.Abs(), time.Duration(1.0*float64(duration)), "expected %v, result %v", expected, res) -} - -func TestDoExponentialBackoffRetry(t *testing.T) { - client := mocks.NewSender() - bo := &Backoff{Duration: time.Second, Factor: 2, Steps: 0, Cap: 3 * time.Second, Jitter: 0.5} - sender := autorest.DecorateSender( - client, - DoExponentialBackoffRetry(bo), - ) - - req := &http.Request{ - Method: "GET", - } - - result, err := sender.Do(req) - assert.Nil(t, result) - assert.NoError(t, err) -} - -func TestStep(t *testing.T) { - tests := []struct { - initial *Backoff - want []time.Duration - }{ - {initial: &Backoff{Duration: time.Second, Steps: 0}, want: []time.Duration{time.Second, time.Second, time.Second}}, - {initial: &Backoff{Duration: time.Second, Steps: 1}, want: []time.Duration{time.Second, time.Second, time.Second}}, - {initial: &Backoff{Duration: time.Second, Factor: 1.0, Steps: 1}, want: []time.Duration{time.Second, time.Second, time.Second}}, - {initial: &Backoff{Duration: time.Second, Factor: 2, Steps: 3}, want: []time.Duration{1 * time.Second, 2 * time.Second, 4 * time.Second}}, - {initial: &Backoff{Duration: time.Second, Factor: 2, Steps: 3, Cap: 3 * time.Second}, want: []time.Duration{1 * time.Second, 2 * time.Second, 3 * time.Second}}, - {initial: &Backoff{Duration: time.Second, Factor: 2, Steps: 2, Cap: 3 * time.Second, Jitter: 0.5}, want: []time.Duration{2 * time.Second, 3 * time.Second, 3 * time.Second}}, - {initial: &Backoff{Duration: time.Second, Factor: 2, Steps: 6, Jitter: 4}, want: []time.Duration{1 * time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second, 32 * time.Second}}, - } - for seed := int64(0); seed < 5; seed++ { - for _, tt := range tests { - initial := *tt.initial - t.Run(fmt.Sprintf("%#v seed=%d", initial, seed), func(t *testing.T) { - rand.Seed(seed) - for i := 0; i < len(tt.want); i++ { - got := initial.Step() - t.Logf("[%d]=%s", i, got) - if initial.Jitter > 0 { - if got == tt.want[i] { - // this is statistically unlikely to happen by chance - t.Errorf("Backoff.Step(%d) = %v, no jitter", i, got) - continue - } - diff := float64(tt.want[i]-got) / float64(tt.want[i]) - if diff > initial.Jitter { - t.Errorf("Backoff.Step(%d) = %v, want %v, outside range", i, got, tt.want) - continue - } - } else { - if got != tt.want[i] { - t.Errorf("Backoff.Step(%d) = %v, want %v", i, got, tt.want) - continue - } - } - } - }) - } - } -} - -func TestDoBackoffRetry(t *testing.T) { - fakeRequest := &http.Request{ - URL: &url.URL{ - Host: "localhost", - Path: "/api", - }, - } - r := mocks.NewResponseWithStatus("500 InternalServerError", http.StatusInternalServerError) - client := mocks.NewSender() - client.AppendAndRepeatResponse(r, 3) - - // retries up to steps on errors - expectedErr := &Error{ - Retriable: true, - HTTPStatusCode: 500, - RawError: fmt.Errorf("HTTP status code (500)"), - } - resp, err := doBackoffRetry(client, fakeRequest, Backoff{Factor: 1.0, Steps: 3}) - assert.NotNil(t, resp) - assert.Equal(t, 500, resp.StatusCode) - assert.Equal(t, expectedErr.RawError, err) - assert.Equal(t, 3, client.Attempts()) - - // retries with 0 steps - respSteps0, errSteps0 := doBackoffRetry(client, fakeRequest, Backoff{Factor: 1.0, Steps: 0}) - assert.Nil(t, respSteps0) - assert.Nil(t, errSteps0) - - // backoff with NonRetriableErrors and RetriableHTTPStatusCodes - r = mocks.NewResponseWithStatus("404 StatusNotFound", http.StatusNotFound) - client = mocks.NewSender() - client.AppendAndRepeatResponseWithDelay(r, time.Second, 1) - client.AppendError(fmt.Errorf("HTTP status code (404)")) - bo := Backoff{Factor: 1.0, Steps: 3} - bo.NonRetriableErrors = []string{"404 StatusNotFound"} - bo.RetriableHTTPStatusCodes = []int{http.StatusNotFound} - expectedResp := &http.Response{ - Status: "200 OK", - StatusCode: 200, - Proto: "HTTP/1.0", - ProtoMajor: 1, - ProtoMinor: 0, - Body: mocks.NewBody(""), - Request: fakeRequest, - } - - resp, err = doBackoffRetry(client, fakeRequest, bo) - assert.NoError(t, err) - assert.Equal(t, 3, client.Attempts()) - assert.Equal(t, expectedResp, resp) - - // returns immediately on succeed - r = mocks.NewResponseWithStatus("200 OK", http.StatusOK) - client = mocks.NewSender() - client.AppendAndRepeatResponse(r, 1) - resp, err = doBackoffRetry(client, fakeRequest, Backoff{Factor: 1.0, Steps: 3}) - assert.NoError(t, err) - assert.Equal(t, 1, client.Attempts()) - assert.NotNil(t, resp) - assert.Equal(t, 200, resp.StatusCode) - - // returns immediately on throttling - r = mocks.NewResponseWithStatus("429 TooManyRequests", http.StatusTooManyRequests) - client = mocks.NewSender() - client.AppendAndRepeatResponse(r, 1) - expectedErr = &Error{ - Retriable: false, - HTTPStatusCode: 429, - RawError: fmt.Errorf("HTTP status code (429)"), - } - resp, err = doBackoffRetry(client, fakeRequest, Backoff{Factor: 1.0, Steps: 3}) - assert.Equal(t, expectedErr.RawError, err) - assert.Equal(t, 1, client.Attempts()) - assert.NotNil(t, resp) - assert.Equal(t, 429, resp.StatusCode) - - // don't retry on non retriable error - r = mocks.NewResponseWithStatus("404 StatusNotFound", http.StatusNotFound) - client = mocks.NewSender() - client.AppendAndRepeatResponse(r, 1) - expectedErr = &Error{ - Retriable: false, - HTTPStatusCode: 404, - RawError: fmt.Errorf("HTTP status code (404)"), - } - resp, err = doBackoffRetry(client, fakeRequest, Backoff{Factor: 1.0, Steps: 3}) - assert.NotNil(t, resp) - assert.Equal(t, 404, resp.StatusCode) - assert.Equal(t, expectedErr.RawError, err) - assert.Equal(t, 1, client.Attempts()) - - // retry on RetriableHTTPStatusCodes - r = mocks.NewResponseWithStatus("102 StatusProcessing", http.StatusProcessing) - client = mocks.NewSender() - client.AppendAndRepeatResponse(r, 3) - expectedErr = &Error{ - Retriable: true, - HTTPStatusCode: 102, - RawError: fmt.Errorf("HTTP status code (102)"), - } - resp, err = doBackoffRetry(client, fakeRequest, Backoff{ - Factor: 1.0, - Steps: 3, - RetriableHTTPStatusCodes: []int{http.StatusProcessing}, - }) - assert.NotNil(t, resp) - assert.Equal(t, 102, resp.StatusCode) - assert.Equal(t, expectedErr.RawError, err) - assert.Equal(t, 3, client.Attempts()) -} diff --git a/pkg/retry/doc.go b/pkg/retry/doc.go deleted file mode 100644 index 70fe35b9bb..0000000000 --- a/pkg/retry/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -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. -*/ - -// Package retry defines a general library to handle errors and retries for various -// Azure clients. -package retry // import "sigs.k8s.io/cloud-provider-azure/pkg/retry" diff --git a/pkg/util/deepcopy/deepcopy_test.go b/pkg/util/deepcopy/deepcopy_test.go index 6723ccef54..9f7a95b2fa 100644 --- a/pkg/util/deepcopy/deepcopy_test.go +++ b/pkg/util/deepcopy/deepcopy_test.go @@ -20,7 +20,8 @@ import ( "sync" "testing" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/stretchr/testify/assert" "k8s.io/utils/ptr" @@ -40,21 +41,21 @@ func (f fakeStruct) Get() string { // TestCopyBasic tests object with pointer, struct, map, slice, interface. func TestCopyBasic(t *testing.T) { - zones := []string{"zone0", "zone1"} - var vmOriginal *compute.VirtualMachine = &compute.VirtualMachine{ - VirtualMachineProperties: &compute.VirtualMachineProperties{ + zones := to.SliceOfPtrs("zone0", "zone1") + var vmOriginal *armcompute.VirtualMachine = &armcompute.VirtualMachine{ + Properties: &armcompute.VirtualMachineProperties{ ProvisioningState: ptr.To("Failed"), }, Name: ptr.To("vmOriginal"), - Zones: &zones, + Zones: zones, Tags: map[string]*string{ "tag0": ptr.To("tagVal0"), }, } - vmCopied := Copy(vmOriginal).(*compute.VirtualMachine) + vmCopied := Copy(vmOriginal).(*armcompute.VirtualMachine) - psOriginal := vmOriginal.VirtualMachineProperties.ProvisioningState - psCopied := vmCopied.VirtualMachineProperties.ProvisioningState + psOriginal := vmOriginal.Properties.ProvisioningState + psCopied := vmCopied.Properties.ProvisioningState assert.Equal(t, psOriginal, psCopied) assert.Equal(t, vmOriginal.Name, vmCopied.Name) assert.Equal(t, vmOriginal.Zones, vmCopied.Zones) @@ -65,10 +66,10 @@ func TestCopyBasic(t *testing.T) { assert.Equal(t, fakeOriginal.Get(), fakeCopied.Get()) } -// TestCopyVMInSyncMap tests object like compute.VirtualMachine in a sync.Map. +// TestCopyVMInSyncMap tests object like armcompute.VirtualMachine in a sync.Map. func TestCopyVMInSyncMap(t *testing.T) { - var vmOriginal *compute.VirtualMachine = &compute.VirtualMachine{ - VirtualMachineProperties: &compute.VirtualMachineProperties{ + var vmOriginal *armcompute.VirtualMachine = &armcompute.VirtualMachine{ + Properties: &armcompute.VirtualMachineProperties{ ProvisioningState: ptr.To("Failed"), }, Name: ptr.To("vmOriginal"), @@ -77,17 +78,17 @@ func TestCopyVMInSyncMap(t *testing.T) { vmCacheOriginal.Store("vmOriginal", vmOriginal) vmCacheCopied := Copy(vmCacheOriginal).(*sync.Map) - psOriginal := vmOriginal.VirtualMachineProperties.ProvisioningState + psOriginal := vmOriginal.Properties.ProvisioningState vCopied, ok := vmCacheCopied.Load("vmOriginal") assert.True(t, ok) - vmCopied := vCopied.(*compute.VirtualMachine) - psCopied := vmCopied.VirtualMachineProperties.ProvisioningState + vmCopied := vCopied.(*armcompute.VirtualMachine) + psCopied := vmCopied.Properties.ProvisioningState assert.Equal(t, psOriginal, psCopied) assert.Equal(t, vmOriginal.Name, vmCopied.Name) } type vmssEntry struct { - *compute.VirtualMachineScaleSet + *armcompute.VirtualMachineScaleSet Name *string } @@ -95,7 +96,7 @@ type vmssEntry struct { func TestCopyVMSSEntryInSyncMap(t *testing.T) { vmssEntryOriginal := &vmssEntry{ Name: ptr.To("vmssEntryName"), - VirtualMachineScaleSet: &compute.VirtualMachineScaleSet{ + VirtualMachineScaleSet: &armcompute.VirtualMachineScaleSet{ Name: ptr.To("vmssOriginal"), }, } diff --git a/pkg/util/errutils/err.go b/pkg/util/errutils/err.go index 477b816e40..78963b530a 100644 --- a/pkg/util/errutils/err.go +++ b/pkg/util/errutils/err.go @@ -18,7 +18,10 @@ package errutils import ( "errors" + "fmt" "net/http" + "regexp" + "strings" "github.com/Azure/azure-sdk-for-go/sdk/azcore" ) @@ -35,3 +38,48 @@ func CheckResourceExistsFromAzcoreError(err error) (bool, error) { } return false, err } + +// HasStatusForbiddenOrIgnoredError return true if the given error code is part of the error message +// This should only be used when trying to delete resources +func HasStatusForbiddenOrIgnoredError(err error) bool { + if err == nil { + return false + } + var respError *azcore.ResponseError + if !errors.As(err, &respError) { + return false + } + if respError == nil { + return false + } + + if respError.StatusCode == http.StatusNotFound { + return true + } + + if respError.StatusCode == http.StatusForbidden { + return true + } + return false +} + +// GetVMSSMetadataByRawError gets the vmss name by parsing the error message +func GetVMSSMetadataByRawError(err error) (string, string, error) { + if err == nil || !isErrorLoadBalancerInUseByVirtualMachineScaleSet(err.Error()) { + return "", "", nil + } + + reg := regexp.MustCompile(`.*/subscriptions/(?:.*)/resourceGroups/(.*)/providers/Microsoft.Compute/virtualMachineScaleSets/(.+)\.`) + matches := reg.FindStringSubmatch(err.Error()) + if len(matches) != 3 { + return "", "", fmt.Errorf("GetVMSSMetadataByRawError: couldn't find a VMSS resource Id from error message %w", err) + } + + return matches[1], matches[2], nil +} + +// isErrorLoadBalancerInUseByVirtualMachineScaleSet determines if the Error is +// LoadBalancerInUseByVirtualMachineScaleSet +func isErrorLoadBalancerInUseByVirtualMachineScaleSet(rawError string) bool { + return strings.Contains(rawError, "LoadBalancerInUseByVirtualMachineScaleSet") +} diff --git a/pkg/util/vm/vm.go b/pkg/util/vm/vm.go index a5084f30b9..39bf62cd0e 100644 --- a/pkg/util/vm/vm.go +++ b/pkg/util/vm/vm.go @@ -19,8 +19,7 @@ package vm import ( "strings" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "k8s.io/klog/v2" "k8s.io/utils/ptr" @@ -29,16 +28,15 @@ import ( ) // GetVMPowerState returns the power state of the VM -func GetVMPowerState(vmName string, vmStatuses *[]compute.InstanceViewStatus) string { +func GetVMPowerState(vmName string, vmStatuses []*armcompute.InstanceViewStatus) string { logger := klog.Background().WithName("getVMSSVMPowerState").WithValues("vmName", vmName) - if vmStatuses != nil { - for _, status := range *vmStatuses { - state := ptr.Deref(status.Code, "") - if stringutils.HasPrefixCaseInsensitive(state, consts.VMPowerStatePrefix) { - return strings.TrimPrefix(state, consts.VMPowerStatePrefix) - } + for _, status := range vmStatuses { + state := ptr.Deref(status.Code, "") + if stringutils.HasPrefixCaseInsensitive(state, consts.VMPowerStatePrefix) { + return strings.TrimPrefix(state, consts.VMPowerStatePrefix) } } + logger.V(3).Info("vm status is nil in the instance view or there is no power state in the status") return consts.VMPowerStateUnknown } diff --git a/pkg/util/vm/vm_test.go b/pkg/util/vm/vm_test.go index ec1cd97083..b9502511c1 100644 --- a/pkg/util/vm/vm_test.go +++ b/pkg/util/vm/vm_test.go @@ -21,21 +21,21 @@ import ( "k8s.io/utils/ptr" - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/stretchr/testify/assert" ) func TestGetVMPowerState(t *testing.T) { type testCase struct { name string - vmStatuses *[]compute.InstanceViewStatus + vmStatuses []*armcompute.InstanceViewStatus expected string } tests := []testCase{ { name: "should return power state when there is power state status", - vmStatuses: &[]compute.InstanceViewStatus{ + vmStatuses: []*armcompute.InstanceViewStatus{ {Code: ptr.To("foo")}, {Code: ptr.To("PowerState/Running")}, }, @@ -43,7 +43,7 @@ func TestGetVMPowerState(t *testing.T) { }, { name: "should return unknown when there is no power state status", - vmStatuses: &[]compute.InstanceViewStatus{ + vmStatuses: []*armcompute.InstanceViewStatus{ {Code: ptr.To("foo")}, }, expected: "unknown", @@ -55,7 +55,7 @@ func TestGetVMPowerState(t *testing.T) { }, { name: "should return unknown when vmStatuses is empty", - vmStatuses: &[]compute.InstanceViewStatus{}, + vmStatuses: []*armcompute.InstanceViewStatus{}, expected: "unknown", }, } diff --git a/tests/e2e/autoscaling/autoscaler.go b/tests/e2e/autoscaling/autoscaler.go index fc7e56aea9..d73896825d 100644 --- a/tests/e2e/autoscaling/autoscaler.go +++ b/tests/e2e/autoscaling/autoscaler.go @@ -95,7 +95,7 @@ var _ = Describe("Cluster size autoscaler", Label(utils.TestSuiteLabelFeatureAut } utils.Logf("Initial schedulable nodes (%d): %q", initNodeCount, nodeNames) - initNodepoolNodeMap = utils.GetNodepoolNodeMap(&nodes) + initNodepoolNodeMap = utils.GetNodepoolNodeMap(nodes) utils.Logf("found %d node pools", len(initNodepoolNodeMap)) // TODO: @@ -262,7 +262,7 @@ var _ = Describe("Cluster size autoscaler", Label(utils.TestSuiteLabelFeatureAut nodes, err = utils.GetAgentNodes(cs) Expect(err).NotTo(HaveOccurred()) - isBalance := checkNodeGroupsBalance(&nodes) + isBalance := checkNodeGroupsBalance(nodes) Expect(isBalance).To(BeTrue()) waitForScaleDownToComplete(cs, ns, initNodeCount, scaleUpDeployment) @@ -616,7 +616,7 @@ func calculateNewPodCountOnNode(cs clientset.Interface, node *v1.Node) int32 { return podCountOnNode } -func checkNodeGroupsBalance(nodes *[]v1.Node) bool { +func checkNodeGroupsBalance(nodes []v1.Node) bool { nodepoolSizeMap := utils.GetNodepoolNodeMap(nodes) min, max := math.MaxInt32, math.MinInt32 for _, nodes := range nodepoolSizeMap { diff --git a/tests/e2e/network/ensureloadbalancer.go b/tests/e2e/network/ensureloadbalancer.go index 9968d374aa..2456e3e127 100644 --- a/tests/e2e/network/ensureloadbalancer.go +++ b/tests/e2e/network/ensureloadbalancer.go @@ -27,7 +27,7 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" - aznetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" @@ -168,7 +168,7 @@ var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelLB), func() { expectedTags := map[string]*string{ "foo": ptr.To("bar"), } - pips := []*aznetwork.PublicIPAddress{} + pips := []*armnetwork.PublicIPAddress{} targetIPs := []*string{} ipNames := []string{} deleteFuncs := []func(){} @@ -681,7 +681,7 @@ var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelLB), func() { Expect(err).NotTo(HaveOccurred()) if os.Getenv(utils.AKSTestCCM) != "" { // AKS - initNodepoolNodeMap := utils.GetNodepoolNodeMap(&nodes) + initNodepoolNodeMap := utils.GetNodepoolNodeMap(nodes) if len(initNodepoolNodeMap) != 1 { Skip("single node pool is needed in this scenario") } @@ -702,7 +702,7 @@ var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelLB), func() { By("Checking the initial node number in the LB backend pool") lb := getAzureLoadBalancerFromPIP(tc, publicIP, tc.GetResourceGroup(), "") - if lb.SKU != nil && *lb.SKU.Name == aznetwork.LoadBalancerSKUNameBasic { + if lb.SKU != nil && *lb.SKU.Name == armnetwork.LoadBalancerSKUNameBasic { // For a basic lb, not autoscaling pipeline idxes := getLBBackendPoolIndex(lb) Expect(idxes).NotTo(BeZero()) @@ -890,7 +890,7 @@ var _ = Describe("EnsureLoadBalancer should not update any resources when servic consts.ServiceAnnotationLoadBalancerHealthProbeNumOfProbe: "8", } - if strings.EqualFold(os.Getenv(utils.LoadBalancerSkuEnv), string(aznetwork.LoadBalancerSKUNameStandard)) && + if strings.EqualFold(os.Getenv(utils.LoadBalancerSKUEnv), string(armnetwork.LoadBalancerSKUNameStandard)) && tc.IPFamily == utils.IPv4 { // Routing preference is only supported in standard public IPs annotation[consts.ServiceAnnotationIPTagsForPublicIP] = "RoutingPreference=Internet" @@ -977,7 +977,7 @@ var _ = Describe("EnsureLoadBalancer should not update any resources when servic }) It("should respect service with BYO public IP prefix with various configurations", func() { - if !strings.EqualFold(os.Getenv(utils.LoadBalancerSkuEnv), string(aznetwork.LoadBalancerSKUNameStandard)) { + if !strings.EqualFold(os.Getenv(utils.LoadBalancerSKUEnv), string(armnetwork.LoadBalancerSKUNameStandard)) { Skip("pip-prefix-id only work with Standard Load Balancer") } @@ -1119,11 +1119,11 @@ func updateServiceAndCompareEtags(tc *utils.AzureTestClient, cs clientset.Interf Expect(pipEtag).To(Equal(newPipEtag), "pip etag") } -func createNewSubnet(tc *utils.AzureTestClient, subnetName string) (*aznetwork.Subnet, bool) { +func createNewSubnet(tc *utils.AzureTestClient, subnetName string) (*armnetwork.Subnet, bool) { vNet, err := tc.GetClusterVirtualNetwork() Expect(err).NotTo(HaveOccurred()) - var subnetToReturn *aznetwork.Subnet + var subnetToReturn *armnetwork.Subnet isNew := false for i := range vNet.Properties.Subnets { existingSubnet := (vNet.Properties.Subnets)[i] @@ -1182,7 +1182,7 @@ func getResourceEtags(tc *utils.AzureTestClient, ip *string, nsgRulePrefix strin return } -func getAzureInternalLoadBalancerFromPrivateIP(tc *utils.AzureTestClient, ip *string, lbResourceGroup string) *aznetwork.LoadBalancer { +func getAzureInternalLoadBalancerFromPrivateIP(tc *utils.AzureTestClient, ip *string, lbResourceGroup string) *armnetwork.LoadBalancer { if lbResourceGroup == "" { lbResourceGroup = tc.GetResourceGroup() } @@ -1190,7 +1190,7 @@ func getAzureInternalLoadBalancerFromPrivateIP(tc *utils.AzureTestClient, ip *st lbList, err := tc.ListLoadBalancers(lbResourceGroup) Expect(err).NotTo(HaveOccurred()) - var ilb *aznetwork.LoadBalancer + var ilb *armnetwork.LoadBalancer utils.Logf("Looking for internal load balancer frontend config ID with private ip as frontend") for i := range lbList { lb := lbList[i] @@ -1209,7 +1209,7 @@ func getAzureInternalLoadBalancerFromPrivateIP(tc *utils.AzureTestClient, ip *st func waitForNodesInLBBackendPool(tc *utils.AzureTestClient, ip *string, expectedNum int) error { return wait.PollImmediate(10*time.Second, 10*time.Minute, func() (done bool, err error) { lb := getAzureLoadBalancerFromPIP(tc, ip, tc.GetResourceGroup(), "") - if lb.SKU != nil && *lb.SKU.Name == aznetwork.LoadBalancerSKUNameBasic { + if lb.SKU != nil && *lb.SKU.Name == armnetwork.LoadBalancerSKUNameBasic { // basic lb idxes := getLBBackendPoolIndex(lb) if len(idxes) == 0 { @@ -1280,7 +1280,7 @@ func judgeInternal(service v1.Service) bool { return service.Annotations[consts.ServiceAnnotationLoadBalancerInternal] == utils.TrueValue } -func getLBBackendPoolIndex(lb *aznetwork.LoadBalancer) []int { +func getLBBackendPoolIndex(lb *armnetwork.LoadBalancer) []int { idxes := []int{} for index, backendPool := range lb.Properties.BackendAddressPools { if !strings.Contains(strings.ToLower(*backendPool.Name), "outboundbackendpool") { @@ -1331,44 +1331,44 @@ func updateServicePIPNames(ipFamily utils.IPFamily, service *v1.Service, pipName return service } -func defaultPublicIPAddress(ipName string, isIPv6 bool) *aznetwork.PublicIPAddress { +func defaultPublicIPAddress(ipName string, isIPv6 bool) *armnetwork.PublicIPAddress { // The default sku for LoadBalancer and PublicIP is basic. - skuName := aznetwork.PublicIPAddressSKUNameBasic - if skuEnv := os.Getenv(utils.LoadBalancerSkuEnv); skuEnv != "" { - if strings.EqualFold(skuEnv, string(aznetwork.PublicIPAddressSKUNameStandard)) { - skuName = aznetwork.PublicIPAddressSKUNameStandard + skuName := armnetwork.PublicIPAddressSKUNameBasic + if skuEnv := os.Getenv(utils.LoadBalancerSKUEnv); skuEnv != "" { + if strings.EqualFold(skuEnv, string(armnetwork.PublicIPAddressSKUNameStandard)) { + skuName = armnetwork.PublicIPAddressSKUNameStandard } } - pip := &aznetwork.PublicIPAddress{ + pip := &armnetwork.PublicIPAddress{ Name: ptr.To(ipName), Location: ptr.To(os.Getenv(utils.ClusterLocationEnv)), - SKU: &aznetwork.PublicIPAddressSKU{ + SKU: &armnetwork.PublicIPAddressSKU{ Name: to.Ptr(skuName), }, - Properties: &aznetwork.PublicIPAddressPropertiesFormat{ - PublicIPAllocationMethod: to.Ptr(aznetwork.IPAllocationMethodStatic), + Properties: &armnetwork.PublicIPAddressPropertiesFormat{ + PublicIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), }, } if isIPv6 { - pip.Properties.PublicIPAddressVersion = to.Ptr(aznetwork.IPVersionIPv6) + pip.Properties.PublicIPAddressVersion = to.Ptr(armnetwork.IPVersionIPv6) } return pip } -func defaultPublicIPPrefix(name string, isIPv6 bool) aznetwork.PublicIPPrefix { - pipAddrVersion := aznetwork.IPVersionIPv4 +func defaultPublicIPPrefix(name string, isIPv6 bool) armnetwork.PublicIPPrefix { + pipAddrVersion := armnetwork.IPVersionIPv4 var prefixLen int32 = 28 if isIPv6 { - pipAddrVersion = aznetwork.IPVersionIPv6 + pipAddrVersion = armnetwork.IPVersionIPv6 prefixLen = 124 } - return aznetwork.PublicIPPrefix{ + return armnetwork.PublicIPPrefix{ Name: ptr.To(name), Location: ptr.To(os.Getenv(utils.ClusterLocationEnv)), - SKU: &aznetwork.PublicIPPrefixSKU{ - Name: to.Ptr(aznetwork.PublicIPPrefixSKUNameStandard), + SKU: &armnetwork.PublicIPPrefixSKU{ + Name: to.Ptr(armnetwork.PublicIPPrefixSKUNameStandard), }, - Properties: &aznetwork.PublicIPPrefixPropertiesFormat{ + Properties: &armnetwork.PublicIPPrefixPropertiesFormat{ PrefixLength: ptr.To(prefixLen), PublicIPAddressVersion: to.Ptr(pipAddrVersion), }, diff --git a/tests/e2e/network/network_security_group.go b/tests/e2e/network/network_security_group.go index 491afd025d..d39d03cf24 100644 --- a/tests/e2e/network/network_security_group.go +++ b/tests/e2e/network/network_security_group.go @@ -23,11 +23,9 @@ import ( "strconv" "strings" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - aznetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" @@ -160,7 +158,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( By("Checking if the rule for allowing traffic from Internet exists", func() { var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedSrcPrefixes = []string{"Internet"} expectedDstPorts []string ) @@ -289,7 +287,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( By("Checking if the rule for allowing traffic from allowed-IPs exists", func() { var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedDstPorts = []string{strconv.FormatInt(int64(serverPort), 10)} ) @@ -361,7 +359,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( By("Checking if the rule for allowing traffic from allowed-IPs exists", func() { var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedDstPorts = []string{strconv.FormatInt(int64(serverPort), 10)} ) @@ -434,7 +432,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( Expect(validator.NotHasRuleForDestination(serviceIPv6s)).To(BeTrue()) var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedSrcPrefixes = []string{"Internet"} expectedDstPorts = []string{strconv.FormatInt(int64(svcNodePort), 10)} ) @@ -537,7 +535,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( Expect(validator.NotHasRuleForDestination(svc1IPv6s)).To(BeTrue()) var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedSrcPrefixes = []string{"Internet"} expectedDstPorts = []string{strconv.FormatInt(int64(app1NodePort), 10)} ) @@ -550,7 +548,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( Expect(validator.NotHasRuleForDestination(svc2IPv6s)).To(BeTrue()) var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedSrcPrefixes = []string{"Internet"} expectedDstPorts = []string{strconv.FormatInt(int64(app2NodePort), 10)} ) @@ -606,7 +604,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( By("Checking if the rule for allowing traffic from Internet exists", func() { var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedSrcPrefixes = []string{"Internet"} expectedDstPorts = []string{strconv.FormatInt(int64(serverPort), 10)} additionalIPv4s, additionalIPv6s = groupIPsByFamily(mustParseIPs(additionalPublicIPs)) @@ -691,7 +689,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( By("Checking if the rule for allowing traffic from allowed-IPs exists", func() { var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedDstPorts = []string{strconv.FormatInt(int64(serverPort), 10)} ) @@ -760,7 +758,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( By("Checking if the rule for allowing traffic from allowed-service-tags exists", func() { var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedDstPorts = []string{strconv.FormatInt(int64(serverPort), 10)} ) @@ -844,7 +842,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( By("Checking if the rule for allowing traffic from allowed-service-tags exists", func() { var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedDstPorts = []string{strconv.FormatInt(int64(serverPort), 10)} ) @@ -983,7 +981,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( By("Checking if the rule for allowing traffic for app 01", func() { var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedDstPorts = []string{strconv.FormatInt(int64(app1Port), 10)} ) @@ -1004,7 +1002,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( By("Checking if the rule for allowing traffic for app 02", func() { var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedDstPorts = []string{strconv.FormatInt(int64(app2Port), 10)} ) By("Checking if the rule for allowing traffic from Internet exists") @@ -1142,7 +1140,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( By("Checking if the rule for allowing traffic for app 01", func() { var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedDstPorts = []string{strconv.FormatInt(int64(app1Port), 10)} ) @@ -1163,7 +1161,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( By("Checking if the rule for allowing traffic for app 02", func() { var ( - expectedProtocol = aznetwork.SecurityRuleProtocolTCP + expectedProtocol = armnetwork.SecurityRuleProtocolTCP expectedDstPorts = []string{strconv.FormatInt(int64(app2Port), 10)} ) By("Checking if the rule for allowing traffic from Internet exists") @@ -1184,10 +1182,10 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( }) type SecurityGroupValidator struct { - nsgs []*aznetwork.SecurityGroup + nsgs []*armnetwork.SecurityGroup } -func NewSecurityGroupValidator(nsgs []*aznetwork.SecurityGroup) *SecurityGroupValidator { +func NewSecurityGroupValidator(nsgs []*armnetwork.SecurityGroup) *SecurityGroupValidator { // FIXME: should get the exact Security Group by virtual network subnets instead of listing all return &SecurityGroupValidator{ nsgs: nsgs, @@ -1196,7 +1194,7 @@ func NewSecurityGroupValidator(nsgs []*aznetwork.SecurityGroup) *SecurityGroupVa // HasExactAllowRule checks if the security group has a rule that allows traffic from the given source prefixes to the given destination addresses and ports. func (v *SecurityGroupValidator) HasExactAllowRule( - protocol aznetwork.SecurityRuleProtocol, + protocol armnetwork.SecurityRuleProtocol, srcPrefixes []string, dstAddresses []netip.Addr, dstPorts []string, @@ -1229,7 +1227,7 @@ func (v *SecurityGroupValidator) HasDenyAllRuleForDestination(dstAddresses []net return false } -func SecurityGroupNotHasRuleForDestination(nsg *aznetwork.SecurityGroup, dstAddresses []netip.Addr) bool { +func SecurityGroupNotHasRuleForDestination(nsg *armnetwork.SecurityGroup, dstAddresses []netip.Addr) bool { logger := GinkgoLogr.WithName("SecurityGroupNotHasRuleForDestination"). WithValues("nsg-name", nsg.Name). WithValues("dst-addresses", dstAddresses) @@ -1261,8 +1259,8 @@ func SecurityGroupNotHasRuleForDestination(nsg *aznetwork.SecurityGroup, dstAddr } func SecurityGroupHasAllowRuleForDestination( - nsg *aznetwork.SecurityGroup, - protocol aznetwork.SecurityRuleProtocol, + nsg *armnetwork.SecurityGroup, + protocol armnetwork.SecurityRuleProtocol, srcPrefixes []string, dstAddresses []netip.Addr, dstPorts []string, ) bool { @@ -1291,8 +1289,8 @@ func SecurityGroupHasAllowRuleForDestination( } for _, rule := range nsg.Properties.SecurityRules { - if *rule.Properties.Access != aznetwork.SecurityRuleAccessAllow || - *rule.Properties.Direction != aznetwork.SecurityRuleDirectionInbound || + if *rule.Properties.Access != armnetwork.SecurityRuleAccessAllow || + *rule.Properties.Direction != armnetwork.SecurityRuleDirectionInbound || *rule.Properties.Protocol != protocol || ptr.Deref(rule.Properties.SourcePortRange, "") != "*" || len(rule.Properties.DestinationPortRanges) != len(dstPorts) { @@ -1353,7 +1351,7 @@ func SecurityGroupHasAllowRuleForDestination( return true } -func SecurityGroupHasDenyAllRuleForDestination(nsg *aznetwork.SecurityGroup, dstAddresses []netip.Addr) bool { +func SecurityGroupHasDenyAllRuleForDestination(nsg *armnetwork.SecurityGroup, dstAddresses []netip.Addr) bool { logger := GinkgoLogr.WithName("HasDenyAllRuleForDestination"). WithValues("nsg-name", nsg.Name). WithValues("expected-dst-addresses", dstAddresses) @@ -1368,7 +1366,7 @@ func SecurityGroupHasDenyAllRuleForDestination(nsg *aznetwork.SecurityGroup, dst } for _, rule := range nsg.Properties.SecurityRules { - if *rule.Properties.Access != aznetwork.SecurityRuleAccessDeny || + if *rule.Properties.Access != armnetwork.SecurityRuleAccessDeny || ptr.Deref(rule.Properties.SourceAddressPrefix, "") != "*" || ptr.Deref(rule.Properties.SourcePortRange, "") != "*" || ptr.Deref(rule.Properties.DestinationPortRange, "") != "*" { diff --git a/tests/e2e/network/node.go b/tests/e2e/network/node.go index 17ff7a95a7..1802135614 100644 --- a/tests/e2e/network/node.go +++ b/tests/e2e/network/node.go @@ -25,11 +25,10 @@ import ( "strings" "time" - compute "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" - network "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" @@ -186,8 +185,8 @@ var _ = Describe("Azure node resources", Label(utils.TestSuiteLabelNode), func() Expect(err).NotTo(HaveOccurred()) utils.Logf("getting all NICs of VMSSes") - var vmssAllNics []*network.Interface - vmssVMs := make([]*compute.VirtualMachineScaleSetVM, 0) + var vmssAllNics []*armnetwork.Interface + vmssVMs := make([]*armcompute.VirtualMachineScaleSetVM, 0) for _, vmss := range vmsses { vmssVMList, err := utils.ListVMSSVMs(tc, *vmss.Name) Expect(err).NotTo(HaveOccurred()) diff --git a/tests/e2e/network/private_link_service.go b/tests/e2e/network/private_link_service.go index 43c973723d..770c2797b8 100644 --- a/tests/e2e/network/private_link_service.go +++ b/tests/e2e/network/private_link_service.go @@ -24,7 +24,7 @@ import ( "strings" "time" - network "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -57,7 +57,7 @@ var _ = Describe("Private link service", Label(utils.TestSuiteLabelPrivateLinkSe }} BeforeEach(func() { - if !strings.EqualFold(os.Getenv(utils.LoadBalancerSkuEnv), string(network.LoadBalancerSKUNameStandard)) { + if !strings.EqualFold(os.Getenv(utils.LoadBalancerSKUEnv), string(armnetwork.LoadBalancerSKUNameStandard)) { Skip("private link service only works with standard load balancer") } var err error @@ -119,7 +119,7 @@ var _ = Describe("Private link service", Label(utils.TestSuiteLabelPrivateLinkSe pls := getPrivateLinkServiceFromIP(tc, ip, "", "", "") Expect(pls.Properties.IPConfigurations).NotTo(BeNil()) Expect(len(pls.Properties.IPConfigurations)).To(Equal(1)) - Expect(*(pls.Properties.IPConfigurations)[0].Properties.PrivateIPAllocationMethod).To(Equal(network.IPAllocationMethodDynamic)) + Expect(*(pls.Properties.IPConfigurations)[0].Properties.PrivateIPAllocationMethod).To(Equal(armnetwork.IPAllocationMethodDynamic)) Expect(len(pls.Properties.Fqdns) == 0).To(BeTrue()) Expect(pls.Properties.EnableProxyProtocol == nil || !*pls.Properties.EnableProxyProtocol).To(BeTrue()) Expect(pls.Properties.Visibility == nil || len(pls.Properties.Visibility.Subscriptions) == 0).To(BeTrue()) @@ -283,7 +283,7 @@ var _ = Describe("Private link service", Label(utils.TestSuiteLabelPrivateLinkSe err = wait.PollImmediate(10*time.Second, 5*time.Minute, func() (bool, error) { pls := getPrivateLinkServiceFromIP(tc, ip, "", "", "") return len(pls.Properties.IPConfigurations) == 1 && - *(pls.Properties.IPConfigurations)[0].Properties.PrivateIPAllocationMethod == network.IPAllocationMethodStatic && + *(pls.Properties.IPConfigurations)[0].Properties.PrivateIPAllocationMethod == armnetwork.IPAllocationMethodStatic && *(pls.Properties.IPConfigurations)[0].Properties.PrivateIPAddress == *selectedIP, nil }) Expect(err).NotTo(HaveOccurred()) @@ -481,7 +481,7 @@ func updateServiceAnnotation(service *v1.Service, annotation map[string]string) return } -func getPrivateLinkServiceFromIP(tc *utils.AzureTestClient, ip *string, plsResourceGroup, lbResourceGroup, plsName string) *network.PrivateLinkService { +func getPrivateLinkServiceFromIP(tc *utils.AzureTestClient, ip *string, plsResourceGroup, lbResourceGroup, plsName string) *armnetwork.PrivateLinkService { if lbResourceGroup == "" { lbResourceGroup = tc.GetResourceGroup() } @@ -511,7 +511,7 @@ func getPrivateLinkServiceFromIP(tc *utils.AzureTestClient, ip *string, plsResou } utils.Logf("Getting private link service(%s) from rg(%s)", plsName, plsResourceGroup) - var pls *network.PrivateLinkService + var pls *armnetwork.PrivateLinkService err = wait.PollImmediate(10*time.Second, 10*time.Minute, func() (bool, error) { pls, err = tc.GetPrivateLinkService(plsResourceGroup, plsName) if err != nil { diff --git a/tests/e2e/network/service_annotations.go b/tests/e2e/network/service_annotations.go index 10f437c4b2..d28af0e77e 100644 --- a/tests/e2e/network/service_annotations.go +++ b/tests/e2e/network/service_annotations.go @@ -28,7 +28,7 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" - network "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" @@ -350,7 +350,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn }) It("should support service annotation 'service.beta.kubernetes.io/azure-load-balancer-enable-high-availability-ports'", func() { - if !strings.EqualFold(os.Getenv(utils.LoadBalancerSkuEnv), string(network.LoadBalancerSKUNameStandard)) { + if !strings.EqualFold(os.Getenv(utils.LoadBalancerSKUEnv), string(armnetwork.LoadBalancerSKUNameStandard)) { Skip("azure-load-balancer-enable-high-availability-ports only work with Standard Load Balancer") } @@ -560,7 +560,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn }) It("should support service annotation `service.beta.kubernetes.io/azure-pip-prefix-id`", func() { - if !strings.EqualFold(os.Getenv(utils.LoadBalancerSkuEnv), string(network.LoadBalancerSKUNameStandard)) { + if !strings.EqualFold(os.Getenv(utils.LoadBalancerSKUEnv), string(armnetwork.LoadBalancerSKUNameStandard)) { Skip("pip-prefix-id only work with Standard Load Balancer") } @@ -713,8 +713,8 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn } utils.Logf("PIP frontend config IDs %q", ids) - var lb *network.LoadBalancer - var targetProbes []*network.Probe + var lb *armnetwork.LoadBalancer + var targetProbes []*armnetwork.Probe expectedTargetProbesCount := 1 if tc.IPFamily == utils.DualStack { expectedTargetProbesCount = 2 @@ -722,7 +722,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn //wait for backend update err := wait.PollImmediate(5*time.Second, 60*time.Second, func() (bool, error) { lb = getAzureLoadBalancerFromPIP(tc, publicIPs[0], tc.GetResourceGroup(), "") - targetProbes = []*network.Probe{} + targetProbes = []*armnetwork.Probe{} for i := range lb.Properties.Probes { probe := (lb.Properties.Probes)[i] utils.Logf("One probe of LB is %q", *probe.Name) @@ -755,7 +755,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn Expect(*probe.Properties.IntervalInSeconds).To(Equal(int32(10))) } utils.Logf("Validating health probe config ProbeProtocolHTTP") - Expect(*probe.Properties.Protocol).To(Equal(network.ProbeProtocolHTTP)) + Expect(*probe.Properties.Protocol).To(Equal(armnetwork.ProbeProtocolHTTP)) } }) @@ -787,8 +787,8 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn } utils.Logf("PIP frontend config IDs %q", ids) - var lb *network.LoadBalancer - var targetProbes []*network.Probe + var lb *armnetwork.LoadBalancer + var targetProbes []*armnetwork.Probe expectedTargetProbesCount := 1 if tc.IPFamily == utils.DualStack { expectedTargetProbesCount = 2 @@ -796,7 +796,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn //wait for backend update err := wait.PollImmediate(5*time.Second, 60*time.Second, func() (bool, error) { lb = getAzureLoadBalancerFromPIP(tc, publicIPs[0], tc.GetResourceGroup(), "") - targetProbes = []*network.Probe{} + targetProbes = []*armnetwork.Probe{} for i := range lb.Properties.Probes { probe := (lb.Properties.Probes)[i] utils.Logf("One probe of LB is %q", *probe.Name) @@ -829,7 +829,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn Expect(*probe.Properties.IntervalInSeconds).To(Equal(int32(10))) } utils.Logf("Validating health probe config ProbeProtocolHTTP") - Expect(*probe.Properties.Protocol).To(Equal(network.ProbeProtocolHTTP)) + Expect(*probe.Properties.Protocol).To(Equal(armnetwork.ProbeProtocolHTTP)) } By("Changing ExternalTrafficPolicy of the service to Local") @@ -866,7 +866,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn err = wait.PollImmediate(5*time.Second, 300*time.Second, func() (bool, error) { lb = getAzureLoadBalancerFromPIP(tc, publicIPs[0], tc.GetResourceGroup(), "") - targetProbes = []*network.Probe{} + targetProbes = []*armnetwork.Probe{} for i := range lb.Properties.Probes { probe := (lb.Properties.Probes)[i] utils.Logf("One probe of LB is %q", *probe.Name) @@ -898,7 +898,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn return false, nil } utils.Logf("Validating health probe config ProbeProtocolHTTP") - if !strings.EqualFold(string(*probe.Properties.Protocol), string(network.ProbeProtocolHTTP)) { + if !strings.EqualFold(string(*probe.Properties.Protocol), string(armnetwork.ProbeProtocolHTTP)) { return false, nil } } @@ -939,8 +939,8 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn Expect(len(pipFrontendConfigIDSplit)).NotTo(Equal(0)) } - var lb *network.LoadBalancer - var targetProbes []*network.Probe + var lb *armnetwork.LoadBalancer + var targetProbes []*armnetwork.Probe // There should be no other Services besides the one in this test or the check below will fail. expectedTargetProbesCount := 1 if tc.IPFamily == utils.DualStack { @@ -949,7 +949,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn //wait for backend update err := wait.PollImmediate(5*time.Second, 60*time.Second, func() (bool, error) { lb = getAzureLoadBalancerFromPIP(tc, publicIPs[0], tc.GetResourceGroup(), "") - targetProbes = []*network.Probe{} + targetProbes = []*armnetwork.Probe{} for i := range lb.Properties.Probes { probe := (lb.Properties.Probes)[i] utils.Logf("One probe of LB is %q", *probe.Name) @@ -977,7 +977,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn utils.Logf("Validating health probe config protocol") Expect((len(targetProbes))).To(Equal(expectedTargetProbesCount)) for _, targetProbe := range targetProbes { - Expect(*targetProbe.Properties.Protocol).To(Equal(network.ProbeProtocolHTTP)) + Expect(*targetProbe.Properties.Protocol).To(Equal(armnetwork.ProbeProtocolHTTP)) } }) @@ -1129,7 +1129,7 @@ var _ = Describe("Multiple VMSS", Label(utils.TestSuiteLabelMultiNodePools, util }) It("should support service annotation `service.beta.kubernetes.io/azure-load-balancer-mode`", func() { - if !strings.EqualFold(os.Getenv(utils.LoadBalancerSkuEnv), string(network.LoadBalancerSKUNameStandard)) { + if !strings.EqualFold(os.Getenv(utils.LoadBalancerSKUEnv), string(armnetwork.LoadBalancerSKUNameStandard)) { Skip("service.beta.kubernetes.io/azure-load-balancer-mode only works for basic load balancer") } @@ -1319,14 +1319,14 @@ var _ = Describe("Multi-ports service", Label(utils.TestSuiteLabelMultiPorts), f ids = append(ids, pipFrontendConfigIDSplit[len(pipFrontendConfigIDSplit)-1]) } - var lb *network.LoadBalancer - var targetProbes []*network.Probe + var lb *armnetwork.LoadBalancer + var targetProbes []*armnetwork.Probe expectedTargetProbesCount := 1 if tc.IPFamily == utils.DualStack { expectedTargetProbesCount = 2 } //wait for backend update - checkPort := func(port int32, targetProbes []*network.Probe) bool { + checkPort := func(port int32, targetProbes []*armnetwork.Probe) bool { utils.Logf("Checking port %d", port) match := true for _, targetProbe := range targetProbes { @@ -1340,7 +1340,7 @@ var _ = Describe("Multi-ports service", Label(utils.TestSuiteLabelMultiPorts), f } err = wait.PollImmediate(5*time.Second, 2*time.Minute, func() (bool, error) { lb = getAzureLoadBalancerFromPIP(tc, publicIPs[0], tc.GetResourceGroup(), "") - targetProbes = []*network.Probe{} + targetProbes = []*armnetwork.Probe{} for i := range lb.Properties.Probes { probe := (lb.Properties.Probes)[i] utils.Logf("One probe of LB is %q", *probe.Name) @@ -1379,7 +1379,7 @@ var _ = Describe("Multi-ports service", Label(utils.TestSuiteLabelMultiPorts), f } err = wait.PollImmediate(5*time.Second, 2*time.Minute, func() (bool, error) { lb := getAzureLoadBalancerFromPIP(tc, publicIPs[0], tc.GetResourceGroup(), "") - targetProbes = []*network.Probe{} + targetProbes = []*armnetwork.Probe{} for i := range lb.Properties.Probes { probe := (lb.Properties.Probes)[i] utils.Logf("One probe of LB is %q", *probe.Name) @@ -1393,7 +1393,7 @@ var _ = Describe("Multi-ports service", Label(utils.TestSuiteLabelMultiPorts), f } } for _, targetProbe := range targetProbes { - if checkPort(nodeHealthCheckPort, []*network.Probe{targetProbe}) { + if checkPort(nodeHealthCheckPort, []*armnetwork.Probe{targetProbe}) { return false, nil } } @@ -1490,7 +1490,7 @@ func getFrontendConfigurationIDFromPIP(tc *utils.AzureTestClient, pip, pipResour return pipFrontendConfigurationID } -func getAzureLoadBalancerFromPIP(tc *utils.AzureTestClient, pip *string, pipResourceGroup, lbResourceGroup string) *network.LoadBalancer { +func getAzureLoadBalancerFromPIP(tc *utils.AzureTestClient, pip *string, pipResourceGroup, lbResourceGroup string) *armnetwork.LoadBalancer { pipFrontendConfigurationID := getPIPFrontendConfigurationID(tc, *pip, pipResourceGroup, true) Expect(pipFrontendConfigurationID).NotTo(Equal("")) @@ -1640,7 +1640,8 @@ func validateLoadBalancerBackendPools(tc *utils.AzureTestClient, vmssName string Expect(lb.Properties.BackendAddressPools).NotTo(BeNil()) Expect(lb.Properties.LoadBalancingRules).NotTo(BeNil()) - if lb.SKU != nil && *lb.SKU.Name == network.LoadBalancerSKUNameStandard { + if lb.SKU != nil && *lb.SKU.Name == armnetwork. + LoadBalancerSKUNameStandard { Skip("azure-load-balancer-mode is not working for standard load balancer") } @@ -1711,7 +1712,7 @@ func testPIPTagAnnotationWithTags( } pips, err := tc.ListPublicIPs(tc.GetResourceGroup()) Expect(err).NotTo(HaveOccurred()) - var targetPIPs []network.PublicIPAddress + var targetPIPs []armnetwork.PublicIPAddress for _, pip := range pips { for _, ip := range ips { if strings.EqualFold(ptr.Deref(pip.Properties.IPAddress, ""), *ip) { diff --git a/tests/e2e/network/standard_lb.go b/tests/e2e/network/standard_lb.go index b2d35983ec..3f99c7e958 100644 --- a/tests/e2e/network/standard_lb.go +++ b/tests/e2e/network/standard_lb.go @@ -21,8 +21,8 @@ import ( "os" "strings" - azcompute "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" - network "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" v1 "k8s.io/api/core/v1" @@ -87,7 +87,7 @@ var _ = Describe("[StandardLoadBalancer] Standard load balancer", func() { }) It("should add all nodes in different agent pools to backends", Label(utils.TestSuiteLabelMultiNodePools), Label(utils.TestSuiteLabelNonMultiSLB), func() { - if !strings.EqualFold(os.Getenv(utils.LoadBalancerSkuEnv), string(network.LoadBalancerSKUNameStandard)) { + if !strings.EqualFold(os.Getenv(utils.LoadBalancerSKUEnv), string(armnetwork.LoadBalancerSKUNameStandard)) { Skip("only test standard load balancer") } @@ -139,7 +139,7 @@ var _ = Describe("[StandardLoadBalancer] Standard load balancer", func() { utils.Logf("got BackendIPConfigurations IDs: %q", ipcIDs) if isVMSS { - allVMs := []*azcompute.VirtualMachineScaleSetVM{} + allVMs := []*armcompute.VirtualMachineScaleSetVM{} for _, vmss := range vmsses { if strings.Contains(*vmss.ID, "control-plane") || strings.Contains(*vmss.ID, "master") { continue @@ -192,7 +192,7 @@ var _ = Describe("[StandardLoadBalancer] Standard load balancer", func() { }) It("should make outbound IP of pod same as in SLB's outbound rules", Label(utils.TestSuiteLabelSLBOutbound), func() { - if !strings.EqualFold(os.Getenv(utils.LoadBalancerSkuEnv), string(network.LoadBalancerSKUNameStandard)) { + if !strings.EqualFold(os.Getenv(utils.LoadBalancerSKUEnv), string(armnetwork.LoadBalancerSKUNameStandard)) { Skip("only test standard load balancer") } diff --git a/tests/e2e/node/vmss.go b/tests/e2e/node/vmss.go index e4bb576595..6639710215 100644 --- a/tests/e2e/node/vmss.go +++ b/tests/e2e/node/vmss.go @@ -17,10 +17,10 @@ limitations under the License. package node import ( - compute "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" v1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" @@ -62,11 +62,11 @@ var _ = Describe("Lifecycle of VMSS", Label(utils.TestSuiteLabelVMSS, utils.Test By("fetch VMSS") vmss, err := utils.FindTestVMSS(azCli, azCli.GetResourceGroup()) Expect(err).NotTo(HaveOccurred()) - if vmss == nil || vmss.Properties == nil || vmss.Properties.OrchestrationMode == nil || *vmss.Properties.OrchestrationMode == compute.OrchestrationModeFlexible { + if vmss == nil || vmss.Properties == nil || vmss.Properties.OrchestrationMode == nil || *vmss.Properties.OrchestrationMode == armcompute.OrchestrationModeFlexible { Skip("skip non-VMSS or VMSS Flex") } numInstance := *vmss.SKU.Capacity - utils.Logf("Current VMSS %q sku capacity: %d", *vmss.Name, numInstance) + utils.Logf("Current VMSS %q SKU capacity: %d", *vmss.Name, numInstance) expectedCap := map[string]int64{*vmss.Name: numInstance} originalNodes, err := utils.GetAgentNodes(k8sCli) Expect(err).NotTo(HaveOccurred()) @@ -87,7 +87,7 @@ var _ = Describe("Lifecycle of VMSS", Label(utils.TestSuiteLabelVMSS, utils.Test vmssAfterTest, err := utils.GetVMSS(azCli, *vmss.Name) Expect(err).NotTo(HaveOccurred()) - utils.Logf("VMSS %q sku capacity after the test: %d", *vmssAfterTest.Name, *vmssAfterTest.SKU.Capacity) + utils.Logf("VMSS %q SKU capacity after the test: %d", *vmssAfterTest.Name, *vmssAfterTest.SKU.Capacity) }() err = utils.ValidateClusterNodesMatchVMSSInstances(azCli, expectedCap, originalNodes) @@ -98,11 +98,11 @@ var _ = Describe("Lifecycle of VMSS", Label(utils.TestSuiteLabelVMSS, utils.Test By("fetch VMSS") vmss, err := utils.FindTestVMSS(azCli, azCli.GetResourceGroup()) Expect(err).NotTo(HaveOccurred()) - if vmss == nil || vmss.Properties == nil || vmss.Properties.OrchestrationMode == nil || *vmss.Properties.OrchestrationMode == compute.OrchestrationModeFlexible { + if vmss == nil || vmss.Properties == nil || vmss.Properties.OrchestrationMode == nil || *vmss.Properties.OrchestrationMode == armcompute.OrchestrationModeFlexible { Skip("skip non-VMSS or VMSS Flex") } numInstance := *vmss.SKU.Capacity - utils.Logf("Current VMSS %q sku capacity: %d", *vmss.Name, numInstance) + utils.Logf("Current VMSS %q SKU capacity: %d", *vmss.Name, numInstance) expectedCap := map[string]int64{*vmss.Name: numInstance} originalNodes, err := utils.GetAgentNodes(k8sCli) Expect(err).NotTo(HaveOccurred()) @@ -123,7 +123,7 @@ var _ = Describe("Lifecycle of VMSS", Label(utils.TestSuiteLabelVMSS, utils.Test vmssAfterTest, err := utils.GetVMSS(azCli, *vmss.Name) Expect(err).NotTo(HaveOccurred()) - utils.Logf("VMSS %q sku capacity after the test: %d", *vmssAfterTest.Name, *vmssAfterTest.SKU.Capacity) + utils.Logf("VMSS %q SKU capacity after the test: %d", *vmssAfterTest.Name, *vmssAfterTest.SKU.Capacity) }() err = utils.ValidateClusterNodesMatchVMSSInstances(azCli, expectedCap, originalNodes) diff --git a/tests/e2e/utils/azure_auth.go b/tests/e2e/utils/azure_auth.go index 8fbd836c1d..34321ae0fb 100644 --- a/tests/e2e/utils/azure_auth.go +++ b/tests/e2e/utils/azure_auth.go @@ -31,7 +31,7 @@ const ( ServicePrincipleSecretEnv = "AZURE_CLIENT_SECRET" // #nosec G101 ClusterLocationEnv = "AZURE_LOCATION" ClusterEnvironment = "AZURE_ENVIRONMENT" - LoadBalancerSkuEnv = "AZURE_LOADBALANCER_SKU" + LoadBalancerSKUEnv = "AZURE_LOADBALANCER_SKU" managedIdentityClientID = "AZURE_MANAGED_IDENTITY_CLIENT_ID" federatedTokenFile = "AZURE_FEDERATED_TOKEN_FILE" managedIdentityType = "E2E_MANAGED_IDENTITY_TYPE" diff --git a/tests/e2e/utils/network_interface_utils.go b/tests/e2e/utils/network_interface_utils.go index 112d1fe70e..251f70f642 100644 --- a/tests/e2e/utils/network_interface_utils.go +++ b/tests/e2e/utils/network_interface_utils.go @@ -22,8 +22,8 @@ import ( "regexp" "strings" - compute "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" - network "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" ) var ( @@ -32,7 +32,7 @@ var ( ) // ListNICs returns the NIC list in the given resource group -func ListNICs(tc *AzureTestClient, rgName string) ([]*network.Interface, error) { +func ListNICs(tc *AzureTestClient, rgName string) ([]*armnetwork.Interface, error) { Logf("getting network interfaces list in resource group %s", rgName) ic := tc.createInterfacesClient() @@ -45,7 +45,7 @@ func ListNICs(tc *AzureTestClient, rgName string) ([]*network.Interface, error) } // ListVMSSNICs returns the NIC list in the VMSS -func ListVMSSNICs(tc *AzureTestClient, vmssName string) ([]*network.Interface, error) { +func ListVMSSNICs(tc *AzureTestClient, vmssName string) ([]*armnetwork.Interface, error) { ic := tc.createInterfacesClient() list, err := ic.ListVirtualMachineScaleSetNetworkInterfaces(context.Background(), tc.GetResourceGroup(), vmssName) @@ -69,7 +69,7 @@ func getVMNamePrefixFromNICID(nicID string) (string, error) { } // GetTargetNICFromList pick the target virtual machine's NIC from the given NIC list -func GetTargetNICFromList(list []*network.Interface, targetVMNamePrefix string) (*network.Interface, error) { +func GetTargetNICFromList(list []*armnetwork.Interface, targetVMNamePrefix string) (*armnetwork.Interface, error) { if list == nil { Logf("empty list given, skip finding target NIC") return nil, nil @@ -89,7 +89,7 @@ func GetTargetNICFromList(list []*network.Interface, targetVMNamePrefix string) } // GetNicIDsFromVM returns the NIC ID in the VM -func GetNicIDsFromVM(vm *compute.VirtualMachine) (map[string]interface{}, error) { +func GetNicIDsFromVM(vm *armcompute.VirtualMachine) (map[string]interface{}, error) { if vm.Properties.NetworkProfile == nil || vm.Properties.NetworkProfile.NetworkInterfaces == nil || len(vm.Properties.NetworkProfile.NetworkInterfaces) == 0 { return nil, fmt.Errorf("cannot obtain NIC on VM %s", *vm.Name) @@ -104,7 +104,7 @@ func GetNicIDsFromVM(vm *compute.VirtualMachine) (map[string]interface{}, error) } // GetNicIDsFromVMSSVM returns the NIC ID in the VMSS VM -func GetNicIDsFromVMSSVM(vm *compute.VirtualMachineScaleSetVM) (map[string]interface{}, error) { +func GetNicIDsFromVMSSVM(vm *armcompute.VirtualMachineScaleSetVM) (map[string]interface{}, error) { if vm.Properties.NetworkProfile == nil || vm.Properties.NetworkProfile.NetworkInterfaces == nil || len(vm.Properties.NetworkProfile.NetworkInterfaces) == 0 { return nil, fmt.Errorf("cannot obtain NIC on VMSS VM %s", *vm.Name) @@ -119,7 +119,7 @@ func GetNicIDsFromVMSSVM(vm *compute.VirtualMachineScaleSetVM) (map[string]inter } // GetNICByID returns the network interface with the input ID among the list -func GetNICByID(nicID string, nicList []*network.Interface) (*network.Interface, error) { +func GetNICByID(nicID string, nicList []*armnetwork.Interface) (*armnetwork.Interface, error) { for _, nic := range nicList { nic := nic if strings.EqualFold(*nic.ID, nicID) { diff --git a/tests/e2e/utils/network_utils.go b/tests/e2e/utils/network_utils.go index 747056003d..5bd75afd7e 100644 --- a/tests/e2e/utils/network_utils.go +++ b/tests/e2e/utils/network_utils.go @@ -26,7 +26,7 @@ import ( "strings" "time" - aznetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -52,7 +52,7 @@ var ( ) // getVirtualNetworkList returns the list of virtual networks in the cluster resource group. -func (azureTestClient *AzureTestClient) getVirtualNetworkList() (result []*aznetwork.VirtualNetwork, err error) { +func (azureTestClient *AzureTestClient) getVirtualNetworkList() (result []*armnetwork.VirtualNetwork, err error) { Logf("Getting virtual network list") vNetClient := azureTestClient.createVirtualNetworksClient() err = wait.PollImmediate(poll, singleCallTimeout, func() (bool, error) { @@ -69,8 +69,9 @@ func (azureTestClient *AzureTestClient) getVirtualNetworkList() (result []*aznet return } -// GetClusterVirtualNetwork returns the cluster's virtual network. -func (azureTestClient *AzureTestClient) GetClusterVirtualNetwork() (virtualNetwork *aznetwork.VirtualNetwork, err error) { +// GetClusterVirtualNetwork returns the cluster's virtual armnetwork. + +func (azureTestClient *AzureTestClient) GetClusterVirtualNetwork() (virtualNetwork *armnetwork.VirtualNetwork, err error) { vNetList, err := azureTestClient.getVirtualNetworkList() if err != nil { return @@ -89,8 +90,9 @@ func (azureTestClient *AzureTestClient) GetClusterVirtualNetwork() (virtualNetwo } } -// CreateSubnet creates a new subnet in the specified virtual network. -func (azureTestClient *AzureTestClient) CreateSubnet(vnet *aznetwork.VirtualNetwork, subnetName *string, prefixes []*string, waitUntilComplete bool) (*aznetwork.Subnet, error) { +// CreateSubnet creates a new subnet in the specified virtual armnetwork. + +func (azureTestClient *AzureTestClient) CreateSubnet(vnet *armnetwork.VirtualNetwork, subnetName *string, prefixes []*string, waitUntilComplete bool) (*armnetwork.Subnet, error) { Logf("creating a new subnet %s, %v", *subnetName, StrPtrSliceToStrSlice(prefixes)) subnetParameter := *vnet.Properties.Subnets[0] subnetParameter.Name = subnetName @@ -101,7 +103,7 @@ func (azureTestClient *AzureTestClient) CreateSubnet(vnet *aznetwork.VirtualNetw } subnetsClient := azureTestClient.createSubnetsClient() _, err := subnetsClient.CreateOrUpdate(context.Background(), azureTestClient.GetResourceGroup(), *vnet.Name, *subnetName, subnetParameter) - var subnet *aznetwork.Subnet + var subnet *armnetwork.Subnet if err != nil || !waitUntilComplete { return subnet, err } @@ -155,7 +157,7 @@ func (azureTestClient *AzureTestClient) DeleteSubnet(vnetName string, subnetName } // GetNextSubnetCIDRs obtains a new ip address which has no overlap with existing subnets. -func GetNextSubnetCIDRs(vnet *aznetwork.VirtualNetwork, ipFamily IPFamily) ([]*net.IPNet, error) { +func GetNextSubnetCIDRs(vnet *armnetwork.VirtualNetwork, ipFamily IPFamily) ([]*net.IPNet, error) { if len(vnet.Properties.AddressSpace.AddressPrefixes) == 0 { return nil, fmt.Errorf("vNet has no prefix") } @@ -213,7 +215,7 @@ func isCIDRIPv6(cidr *string) (bool, error) { } // getSecurityGroupList returns the list of security groups in the cluster resource group. -func (azureTestClient *AzureTestClient) getSecurityGroupList() (result []*aznetwork.SecurityGroup, err error) { +func (azureTestClient *AzureTestClient) getSecurityGroupList() (result []*armnetwork.SecurityGroup, err error) { Logf("Getting virtual network list") securityGroupsClient := azureTestClient.CreateSecurityGroupsClient() err = wait.PollImmediate(poll, singleCallTimeout, func() (bool, error) { @@ -231,7 +233,7 @@ func (azureTestClient *AzureTestClient) getSecurityGroupList() (result []*aznetw } // GetClusterSecurityGroups gets the security groups of the cluster. -func (azureTestClient *AzureTestClient) GetClusterSecurityGroups() (ret []*aznetwork.SecurityGroup, err error) { +func (azureTestClient *AzureTestClient) GetClusterSecurityGroups() (ret []*armnetwork.SecurityGroup, err error) { err = wait.PollImmediate(time.Second, time.Minute, func() (bool, error) { securityGroupsList, err := azureTestClient.getSecurityGroupList() if err != nil { @@ -272,11 +274,11 @@ func CreateLoadBalancerServiceManifest(name string, annotation map[string]string } // WaitCreatePIP waits to create a public ip resource in a specific resource group -func WaitCreatePIP(azureTestClient *AzureTestClient, ipName, rgName string, ipParameter *aznetwork.PublicIPAddress) (*aznetwork.PublicIPAddress, error) { +func WaitCreatePIP(azureTestClient *AzureTestClient, ipName, rgName string, ipParameter *armnetwork.PublicIPAddress) (*armnetwork.PublicIPAddress, error) { Logf("Creating public IP resource named %s", ipName) pipClient := azureTestClient.createPublicIPAddressesClient() _, err := pipClient.CreateOrUpdate(context.Background(), rgName, ipName, *ipParameter) - var pip *aznetwork.PublicIPAddress + var pip *armnetwork.PublicIPAddress if err != nil { return pip, err } @@ -306,8 +308,8 @@ func cleanupTags(tags map[string]*string, unwantedKeys []string) map[string]*str func WaitCreatePIPPrefix( cli *AzureTestClient, name, rgName string, - parameter aznetwork.PublicIPPrefix, -) (*aznetwork.PublicIPPrefix, error) { + parameter armnetwork.PublicIPPrefix, +) (*armnetwork.PublicIPPrefix, error) { Logf("Creating PublicIPPrefix named %s", name) resourceClient := cli.createPublicIPPrefixesClient() @@ -321,12 +323,12 @@ func WaitCreatePIPPrefix( func WaitGetPIPPrefix( cli *AzureTestClient, name string, -) (*aznetwork.PublicIPPrefix, error) { +) (*armnetwork.PublicIPPrefix, error) { Logf("Getting PublicIPPrefix named %s", name) resourceClient := cli.createPublicIPPrefixesClient() var ( - prefix *aznetwork.PublicIPPrefix + prefix *armnetwork.PublicIPPrefix err error ) err = wait.PollImmediate(poll, singleCallTimeout, func() (bool, error) { @@ -348,9 +350,9 @@ func WaitGetPIPByPrefix( cli *AzureTestClient, prefixName string, untilPIPCreated bool, -) (*aznetwork.PublicIPAddress, error) { +) (*armnetwork.PublicIPAddress, error) { - var pip *aznetwork.PublicIPAddress + var pip *armnetwork.PublicIPAddress err := wait.Poll(10*time.Second, 5*time.Minute, func() (bool, error) { prefix, err := WaitGetPIPPrefix(cli, prefixName) @@ -415,7 +417,7 @@ func DeletePIPWithRetry(azureTestClient *AzureTestClient, ipName, rgName string) } // WaitGetPIP waits to get a specific public ip resource -func WaitGetPIP(azureTestClient *AzureTestClient, ipName string) (pip *aznetwork.PublicIPAddress, err error) { +func WaitGetPIP(azureTestClient *AzureTestClient, ipName string) (pip *armnetwork.PublicIPAddress, err error) { pipClient := azureTestClient.createPublicIPAddressesClient() err = wait.PollImmediate(poll, singleCallTimeout, func() (bool, error) { pip, err = pipClient.Get(context.Background(), azureTestClient.GetResourceGroup(), ipName, nil) @@ -433,7 +435,7 @@ func WaitGetPIP(azureTestClient *AzureTestClient, ipName string) (pip *aznetwork return } -func selectSubnets(ipFamily IPFamily, vNetSubnets []*aznetwork.Subnet) ([]*string, error) { +func selectSubnets(ipFamily IPFamily, vNetSubnets []*armnetwork.Subnet) ([]*string, error) { subnets := []*string{} for _, sn := range vNetSubnets { // if there is more than one subnet (non-control-plane), select the first one we find. @@ -508,9 +510,6 @@ func SelectAvailablePrivateIPs(tc *AzureTestClient) ([]*string, error) { } vNetClient := tc.createVirtualNetworksClient() - if err != nil { - return []*string{}, err - } privateIPs := []*string{} for _, subnet := range subnets { ip, err := findIPInSubnet(vNetClient, tc.resourceGroup, *subnet, ptr.Deref(vNet.Name, "")) @@ -531,7 +530,7 @@ func SelectAvailablePrivateIPs(tc *AzureTestClient) ([]*string, error) { } // GetPublicIPFromAddress finds public ip according to ip address -func (azureTestClient *AzureTestClient) GetPublicIPFromAddress(resourceGroupName string, ipAddr *string) (pip *aznetwork.PublicIPAddress, err error) { +func (azureTestClient *AzureTestClient) GetPublicIPFromAddress(resourceGroupName string, ipAddr *string) (pip *armnetwork.PublicIPAddress, err error) { pipList, err := azureTestClient.ListPublicIPs(resourceGroupName) if err != nil { return pip, err @@ -545,7 +544,7 @@ func (azureTestClient *AzureTestClient) GetPublicIPFromAddress(resourceGroupName } // ListPublicIPs lists all the publicIP addresses active -func (azureTestClient *AzureTestClient) ListPublicIPs(resourceGroupName string) ([]*aznetwork.PublicIPAddress, error) { +func (azureTestClient *AzureTestClient) ListPublicIPs(resourceGroupName string) ([]*armnetwork.PublicIPAddress, error) { pipClient := azureTestClient.createPublicIPAddressesClient() result, err := pipClient.List(context.Background(), resourceGroupName) @@ -556,7 +555,7 @@ func (azureTestClient *AzureTestClient) ListPublicIPs(resourceGroupName string) } // ListLoadBalancers lists all the load balancers active -func (azureTestClient *AzureTestClient) ListLoadBalancers(resourceGroupName string) ([]*aznetwork.LoadBalancer, error) { +func (azureTestClient *AzureTestClient) ListLoadBalancers(resourceGroupName string) ([]*armnetwork.LoadBalancer, error) { lbClient := azureTestClient.createLoadBalancerClient() result, err := lbClient.List(context.Background(), resourceGroupName) @@ -567,20 +566,20 @@ func (azureTestClient *AzureTestClient) ListLoadBalancers(resourceGroupName stri return result, nil } -// GetLoadBalancer gets aznetwork.LoadBalancer by loadBalancer name. -func (azureTestClient *AzureTestClient) GetLoadBalancer(resourceGroupName, lbName string) (*aznetwork.LoadBalancer, error) { +// GetLoadBalancer gets armnetwork.LoadBalancer by loadBalancer name. +func (azureTestClient *AzureTestClient) GetLoadBalancer(resourceGroupName, lbName string) (*armnetwork.LoadBalancer, error) { lbClient := azureTestClient.createLoadBalancerClient() return lbClient.Get(context.Background(), resourceGroupName, lbName, nil) } -// GetPrivateLinkService gets aznetwork.PrivateLinkService by privateLinkService name. -func (azureTestClient *AzureTestClient) GetPrivateLinkService(resourceGroupName, plsName string) (*aznetwork.PrivateLinkService, error) { +// GetPrivateLinkService gets armnetwork.PrivateLinkService by privateLinkService name. +func (azureTestClient *AzureTestClient) GetPrivateLinkService(resourceGroupName, plsName string) (*armnetwork.PrivateLinkService, error) { plsClient := azureTestClient.createPrivateLinkServiceClient() return plsClient.Get(context.Background(), resourceGroupName, plsName, nil) } // ListPrivateLinkServices lists all the private link services active -func (azureTestClient *AzureTestClient) ListPrivateLinkServices(resourceGroupName string) ([]*aznetwork.PrivateLinkService, error) { +func (azureTestClient *AzureTestClient) ListPrivateLinkServices(resourceGroupName string) ([]*armnetwork.PrivateLinkService, error) { plsClient := azureTestClient.createPrivateLinkServiceClient() result, err := plsClient.List(context.Background(), resourceGroupName) diff --git a/tests/e2e/utils/network_utils_test.go b/tests/e2e/utils/network_utils_test.go index f943f08386..e2531e58d5 100644 --- a/tests/e2e/utils/network_utils_test.go +++ b/tests/e2e/utils/network_utils_test.go @@ -20,7 +20,7 @@ import ( "testing" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" - aznetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/stretchr/testify/assert" "k8s.io/utils/ptr" @@ -30,13 +30,13 @@ func TestSelectSubnets(t *testing.T) { testcases := []struct { desc string ipFamily IPFamily - vNetSubnets []*aznetwork.Subnet + vNetSubnets []*armnetwork.Subnet expectedSubnets []*string }{ { "only control-plane subnet", IPv4, - []*aznetwork.Subnet{ + []*armnetwork.Subnet{ {Name: ptr.To("control-plane")}, }, []*string{}, @@ -44,18 +44,18 @@ func TestSelectSubnets(t *testing.T) { { "IPv4", IPv4, - []*aznetwork.Subnet{ - {Name: ptr.To("subnet0"), Properties: &aznetwork.SubnetPropertiesFormat{AddressPrefix: ptr.To("10.0.0.0/24")}}, + []*armnetwork.Subnet{ + {Name: ptr.To("subnet0"), Properties: &armnetwork.SubnetPropertiesFormat{AddressPrefix: ptr.To("10.0.0.0/24")}}, }, []*string{to.Ptr("10.0.0.0/24")}, }, { "IPv6", IPv6, - []*aznetwork.Subnet{ + []*armnetwork.Subnet{ { Name: ptr.To("subnet0"), - Properties: &aznetwork.SubnetPropertiesFormat{ + Properties: &armnetwork.SubnetPropertiesFormat{ AddressPrefix: ptr.To("10.0.0.0/24"), AddressPrefixes: []*string{to.Ptr("10.0.0.0/24"), to.Ptr("2001::1/96")}, }, @@ -66,10 +66,10 @@ func TestSelectSubnets(t *testing.T) { { "DualStack", DualStack, - []*aznetwork.Subnet{ + []*armnetwork.Subnet{ { Name: ptr.To("subnet0"), - Properties: &aznetwork.SubnetPropertiesFormat{ + Properties: &armnetwork.SubnetPropertiesFormat{ AddressPrefix: ptr.To("10.0.0.0/24"), AddressPrefixes: []*string{to.Ptr("10.0.0.0/24"), to.Ptr("2001::1/96")}, }, diff --git a/tests/e2e/utils/node_utils.go b/tests/e2e/utils/node_utils.go index 341ea18bab..d5c2c3dd33 100644 --- a/tests/e2e/utils/node_utils.go +++ b/tests/e2e/utils/node_utils.go @@ -378,10 +378,10 @@ func LabelNode(cs clientset.Interface, node *v1.Node, label string, isDelete boo return node, nil } -func GetNodepoolNodeMap(nodes *[]v1.Node) map[string][]string { +func GetNodepoolNodeMap(nodes []v1.Node) map[string][]string { nodepoolNodeMap := make(map[string][]string) - for i := range *nodes { - node := (*nodes)[i] + for i := range nodes { + node := (nodes)[i] labels := node.ObjectMeta.Labels if IsSystemPoolNode(&node) { continue diff --git a/tests/e2e/utils/pod_utils.go b/tests/e2e/utils/pod_utils.go index dc7f5220bb..4e4ab6e849 100644 --- a/tests/e2e/utils/pod_utils.go +++ b/tests/e2e/utils/pod_utils.go @@ -60,7 +60,7 @@ func GetPodList(cs clientset.Interface, ns string) (*v1.PodList, error) { } // countPendingPods counts how many pods is in the `pending` state -func countPendingPods(cs clientset.Interface, ns string, pods []v1.Pod) int { +func countPendingPods(_ clientset.Interface, _ string, pods []v1.Pod) int { pendingPodCount := 0 for _, p := range pods { if p.Status.Phase == v1.PodPending { @@ -81,10 +81,6 @@ func WaitPodsToBeReady(cs clientset.Interface, ns string) error { } pods = podList.Items pendingPodCount := countPendingPods(cs, ns, pods) - if err != nil { - Logf("unexpected error: %w", err) - return false, err - } Logf("%d pods in namespace %s are pending", pendingPodCount, ns) return pendingPodCount == 0, nil diff --git a/tests/e2e/utils/route_table_utils.go b/tests/e2e/utils/route_table_utils.go index da98d35682..47aa7ad387 100644 --- a/tests/e2e/utils/route_table_utils.go +++ b/tests/e2e/utils/route_table_utils.go @@ -20,7 +20,7 @@ import ( "context" "fmt" - aznetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "k8s.io/utils/ptr" @@ -28,7 +28,7 @@ import ( ) // ListRouteTables returns the list of all route tables in the resource group -func ListRouteTables(tc *AzureTestClient) ([]*aznetwork.RouteTable, error) { +func ListRouteTables(tc *AzureTestClient) ([]*armnetwork.RouteTable, error) { routeTableClient := tc.createRouteTableClient() list, err := routeTableClient.List(context.Background(), tc.GetResourceGroup()) @@ -39,7 +39,7 @@ func ListRouteTables(tc *AzureTestClient) ([]*aznetwork.RouteTable, error) { } // GetNodesInRouteTable returns all the nodes in the route table -func GetNodesInRouteTable(routeTable aznetwork.RouteTable) (map[string]interface{}, error) { +func GetNodesInRouteTable(routeTable armnetwork.RouteTable) (map[string]interface{}, error) { if routeTable.Properties == nil || len(routeTable.Properties.Routes) == 0 { return nil, fmt.Errorf("cannot obtained routes in route table %s", *routeTable.Name) } diff --git a/tests/e2e/utils/service_utils.go b/tests/e2e/utils/service_utils.go index ef8938a5a4..8dbed9f665 100644 --- a/tests/e2e/utils/service_utils.go +++ b/tests/e2e/utils/service_utils.go @@ -24,8 +24,7 @@ import ( "strings" "time" - aznetwork "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" v1 "k8s.io/api/core/v1" apierrs "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -168,8 +167,8 @@ func WaitServiceExposure(cs clientset.Interface, namespace string, name string, var externalIPs []*string timeout := serviceTimeout - if skuEnv := os.Getenv(LoadBalancerSkuEnv); skuEnv != "" { - if strings.EqualFold(skuEnv, string(aznetwork.LoadBalancerSkuNameBasic)) { + if SKUEnv := os.Getenv(LoadBalancerSKUEnv); SKUEnv != "" { + if strings.EqualFold(SKUEnv, string(armnetwork.LoadBalancerSKUNameBasic)) { timeout = serviceTimeoutBasicLB } } diff --git a/tests/e2e/utils/vmss_utils.go b/tests/e2e/utils/vmss_utils.go index bcfda99946..07994a367c 100644 --- a/tests/e2e/utils/vmss_utils.go +++ b/tests/e2e/utils/vmss_utils.go @@ -279,7 +279,7 @@ func ValidateClusterNodesMatchVMSSInstances(tc *AzureTestClient, expectedCap map if cap != int64(originalNodeSet.Intersection(vmssInstanceSet).Len()) { // For autoscaling cluster, simply comparing the capacity may not work since if the number of current nodes is lower than the "minCount", a new node may be created after scaling down. // In this situation, we compare the expected capacity with the length of intersection between original nodes and current nodes. - Logf("VMSS %q sku capacity is expected to be %d, but actually %d", *vmss.Name, cap, *vmss.SKU.Capacity) + Logf("VMSS %q SKU capacity is expected to be %d, but actually %d", *vmss.Name, cap, *vmss.SKU.Capacity) capMatch = false break } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/CHANGELOG.md deleted file mode 100644 index 52911e4cc5..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/CHANGELOG.md +++ /dev/null @@ -1,2 +0,0 @@ -# Change History - diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/_meta.json b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/_meta.json deleted file mode 100644 index 1ccde570f9..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "c91eca4e2081703002581da6f58f9d9332e1afd1", - "readme": "/_/azure-rest-api-specs/specification/network/resource-manager/readme.md", - "tag": "package-2022-07", - "use": "@microsoft.azure/autorest.go@2.1.188", - "repository_url": "https://github.com/Azure/azure-rest-api-specs.git", - "autorest_command": "autorest --use=@microsoft.azure/autorest.go@2.1.188 --tag=package-2022-07 --go-sdk-folder=/_/azure-sdk-for-go --go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION /_/azure-rest-api-specs/specification/network/resource-manager/readme.md", - "additional_properties": { - "additional_options": "--go --verbose --use-onever --version=2.0.4421 --go.license-header=MICROSOFT_MIT_NO_VERSION" - } -} \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/adminrulecollections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/adminrulecollections.go deleted file mode 100644 index 2292b61ce2..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/adminrulecollections.go +++ /dev/null @@ -1,431 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AdminRuleCollectionsClient is the network Client -type AdminRuleCollectionsClient struct { - BaseClient -} - -// NewAdminRuleCollectionsClient creates an instance of the AdminRuleCollectionsClient client. -func NewAdminRuleCollectionsClient(subscriptionID string) AdminRuleCollectionsClient { - return NewAdminRuleCollectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAdminRuleCollectionsClientWithBaseURI creates an instance of the AdminRuleCollectionsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewAdminRuleCollectionsClientWithBaseURI(baseURI string, subscriptionID string) AdminRuleCollectionsClient { - return AdminRuleCollectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates an admin rule collection. -// Parameters: -// ruleCollection - the Rule Collection to create or update -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager Security Configuration. -// ruleCollectionName - the name of the network manager security Configuration rule collection. -func (client AdminRuleCollectionsClient) CreateOrUpdate(ctx context.Context, ruleCollection AdminRuleCollection, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string) (result AdminRuleCollection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRuleCollectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: ruleCollection, - Constraints: []validation.Constraint{{Target: "ruleCollection.AdminRuleCollectionPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "ruleCollection.AdminRuleCollectionPropertiesFormat.AppliesToGroups", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { - return result, validation.NewError("network.AdminRuleCollectionsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, ruleCollection, resourceGroupName, networkManagerName, configurationName, ruleCollectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRuleCollectionsClient", "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.AdminRuleCollectionsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRuleCollectionsClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client AdminRuleCollectionsClient) CreateOrUpdatePreparer(ctx context.Context, ruleCollection AdminRuleCollection, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "ruleCollectionName": autorest.Encode("path", ruleCollectionName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - ruleCollection.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}", pathParameters), - autorest.WithJSON(ruleCollection), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client AdminRuleCollectionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client AdminRuleCollectionsClient) CreateOrUpdateResponder(resp *http.Response) (result AdminRuleCollection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes an admin rule collection. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager Security Configuration. -// ruleCollectionName - the name of the network manager security Configuration rule collection. -// force - deletes the resource even if it is part of a deployed configuration. If the configuration has been -// deployed, the service will do a cleanup deployment in the background, prior to the delete. -func (client AdminRuleCollectionsClient) Delete(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, force *bool) (result AdminRuleCollectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRuleCollectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkManagerName, configurationName, ruleCollectionName, force) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRuleCollectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRuleCollectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client AdminRuleCollectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, force *bool) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "ruleCollectionName": autorest.Encode("path", ruleCollectionName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if force != nil { - queryParameters["force"] = autorest.Encode("query", *force) - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client AdminRuleCollectionsClient) DeleteSender(req *http.Request) (future AdminRuleCollectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client AdminRuleCollectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a network manager security admin configuration rule collection. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager Security Configuration. -// ruleCollectionName - the name of the network manager security Configuration rule collection. -func (client AdminRuleCollectionsClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string) (result AdminRuleCollection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRuleCollectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkManagerName, configurationName, ruleCollectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRuleCollectionsClient", "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.AdminRuleCollectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRuleCollectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client AdminRuleCollectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "ruleCollectionName": autorest.Encode("path", ruleCollectionName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client AdminRuleCollectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client AdminRuleCollectionsClient) GetResponder(resp *http.Response) (result AdminRuleCollection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the rule collections in a security admin configuration, in a paginated format. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager Security Configuration. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -// skipToken - skipToken is only used if a previous operation returned a partial result. If a previous response -// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that -// specifies a starting point to use for subsequent calls. -func (client AdminRuleCollectionsClient) List(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, top *int32, skipToken string) (result AdminRuleCollectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRuleCollectionsClient.List") - defer func() { - sc := -1 - if result.arclr.Response.Response != nil { - sc = result.arclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.AdminRuleCollectionsClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkManagerName, configurationName, top, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRuleCollectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.arclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AdminRuleCollectionsClient", "List", resp, "Failure sending request") - return - } - - result.arclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRuleCollectionsClient", "List", resp, "Failure responding to request") - return - } - if result.arclr.hasNextLink() && result.arclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AdminRuleCollectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, top *int32, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(skipToken) > 0 { - queryParameters["$skipToken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client AdminRuleCollectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AdminRuleCollectionsClient) ListResponder(resp *http.Response) (result AdminRuleCollectionListResult, err error) { - err = autorest.Respond( - resp, - 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 AdminRuleCollectionsClient) listNextResults(ctx context.Context, lastResults AdminRuleCollectionListResult) (result AdminRuleCollectionListResult, err error) { - req, err := lastResults.adminRuleCollectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AdminRuleCollectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AdminRuleCollectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRuleCollectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AdminRuleCollectionsClient) ListComplete(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, top *int32, skipToken string) (result AdminRuleCollectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRuleCollectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkManagerName, configurationName, top, skipToken) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/adminrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/adminrules.go deleted file mode 100644 index e38d6e174a..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/adminrules.go +++ /dev/null @@ -1,430 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AdminRulesClient is the network Client -type AdminRulesClient struct { - BaseClient -} - -// NewAdminRulesClient creates an instance of the AdminRulesClient client. -func NewAdminRulesClient(subscriptionID string) AdminRulesClient { - return NewAdminRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAdminRulesClientWithBaseURI creates an instance of the AdminRulesClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewAdminRulesClientWithBaseURI(baseURI string, subscriptionID string) AdminRulesClient { - return AdminRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates an admin rule. -// Parameters: -// adminRule - the admin rule to create or update -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager Security Configuration. -// ruleCollectionName - the name of the network manager security Configuration rule collection. -// ruleName - the name of the rule. -func (client AdminRulesClient) CreateOrUpdate(ctx context.Context, adminRule BasicBaseAdminRule, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleName string) (result BaseAdminRuleModel, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRulesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, adminRule, resourceGroupName, networkManagerName, configurationName, ruleCollectionName, ruleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRulesClient", "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.AdminRulesClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRulesClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client AdminRulesClient) CreateOrUpdatePreparer(ctx context.Context, adminRule BasicBaseAdminRule, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "ruleCollectionName": autorest.Encode("path", ruleCollectionName), - "ruleName": autorest.Encode("path", ruleName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}/rules/{ruleName}", pathParameters), - autorest.WithJSON(adminRule), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client AdminRulesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client AdminRulesClient) CreateOrUpdateResponder(resp *http.Response) (result BaseAdminRuleModel, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes an admin rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager Security Configuration. -// ruleCollectionName - the name of the network manager security Configuration rule collection. -// ruleName - the name of the rule. -// force - deletes the resource even if it is part of a deployed configuration. If the configuration has been -// deployed, the service will do a cleanup deployment in the background, prior to the delete. -func (client AdminRulesClient) Delete(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleName string, force *bool) (result AdminRulesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRulesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkManagerName, configurationName, ruleCollectionName, ruleName, force) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRulesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRulesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client AdminRulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleName string, force *bool) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "ruleCollectionName": autorest.Encode("path", ruleCollectionName), - "ruleName": autorest.Encode("path", ruleName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if force != nil { - queryParameters["force"] = autorest.Encode("query", *force) - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}/rules/{ruleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client AdminRulesClient) DeleteSender(req *http.Request) (future AdminRulesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client AdminRulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a network manager security configuration admin rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager Security Configuration. -// ruleCollectionName - the name of the network manager security Configuration rule collection. -// ruleName - the name of the rule. -func (client AdminRulesClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleName string) (result BaseAdminRuleModel, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkManagerName, configurationName, ruleCollectionName, ruleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRulesClient", "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.AdminRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client AdminRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, ruleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "ruleCollectionName": autorest.Encode("path", ruleCollectionName), - "ruleName": autorest.Encode("path", ruleName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}/rules/{ruleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client AdminRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client AdminRulesClient) GetResponder(resp *http.Response) (result BaseAdminRuleModel, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all network manager security configuration admin rules. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager Security Configuration. -// ruleCollectionName - the name of the network manager security Configuration rule collection. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -// skipToken - skipToken is only used if a previous operation returned a partial result. If a previous response -// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that -// specifies a starting point to use for subsequent calls. -func (client AdminRulesClient) List(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, top *int32, skipToken string) (result AdminRuleListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRulesClient.List") - defer func() { - sc := -1 - if result.arlr.Response.Response != nil { - sc = result.arlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.AdminRulesClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkManagerName, configurationName, ruleCollectionName, top, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRulesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.arlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AdminRulesClient", "List", resp, "Failure sending request") - return - } - - result.arlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRulesClient", "List", resp, "Failure responding to request") - return - } - if result.arlr.hasNextLink() && result.arlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AdminRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, top *int32, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "ruleCollectionName": autorest.Encode("path", ruleCollectionName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(skipToken) > 0 { - queryParameters["$skipToken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}/ruleCollections/{ruleCollectionName}/rules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client AdminRulesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AdminRulesClient) ListResponder(resp *http.Response) (result AdminRuleListResult, err error) { - err = autorest.Respond( - resp, - 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 AdminRulesClient) listNextResults(ctx context.Context, lastResults AdminRuleListResult) (result AdminRuleListResult, err error) { - req, err := lastResults.adminRuleListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AdminRulesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AdminRulesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRulesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AdminRulesClient) ListComplete(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, ruleCollectionName string, top *int32, skipToken string) (result AdminRuleListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRulesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkManagerName, configurationName, ruleCollectionName, top, skipToken) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgatewayprivateendpointconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgatewayprivateendpointconnections.go deleted file mode 100644 index 917f0b7b64..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgatewayprivateendpointconnections.go +++ /dev/null @@ -1,395 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ApplicationGatewayPrivateEndpointConnectionsClient is the network Client -type ApplicationGatewayPrivateEndpointConnectionsClient struct { - BaseClient -} - -// NewApplicationGatewayPrivateEndpointConnectionsClient creates an instance of the -// ApplicationGatewayPrivateEndpointConnectionsClient client. -func NewApplicationGatewayPrivateEndpointConnectionsClient(subscriptionID string) ApplicationGatewayPrivateEndpointConnectionsClient { - return NewApplicationGatewayPrivateEndpointConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewApplicationGatewayPrivateEndpointConnectionsClientWithBaseURI creates an instance of the -// ApplicationGatewayPrivateEndpointConnectionsClient client using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewApplicationGatewayPrivateEndpointConnectionsClientWithBaseURI(baseURI string, subscriptionID string) ApplicationGatewayPrivateEndpointConnectionsClient { - return ApplicationGatewayPrivateEndpointConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Delete deletes the specified private endpoint connection on application gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -// connectionName - the name of the application gateway private endpoint connection. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) Delete(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string) (result ApplicationGatewayPrivateEndpointConnectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayPrivateEndpointConnectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, applicationGatewayName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "connectionName": autorest.Encode("path", connectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/applicationGateways/{applicationGatewayName}/privateEndpointConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) DeleteSender(req *http.Request) (future ApplicationGatewayPrivateEndpointConnectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified private endpoint connection on application gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -// connectionName - the name of the application gateway private endpoint connection. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string) (result ApplicationGatewayPrivateEndpointConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayPrivateEndpointConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, applicationGatewayName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsClient", "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.ApplicationGatewayPrivateEndpointConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "connectionName": autorest.Encode("path", connectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/applicationGateways/{applicationGatewayName}/privateEndpointConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) GetResponder(resp *http.Response) (result ApplicationGatewayPrivateEndpointConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all private endpoint connections on an application gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) List(ctx context.Context, resourceGroupName string, applicationGatewayName string) (result ApplicationGatewayPrivateEndpointConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayPrivateEndpointConnectionsClient.List") - defer func() { - sc := -1 - if result.agpeclr.Response.Response != nil { - sc = result.agpeclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, applicationGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.agpeclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.agpeclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.agpeclr.hasNextLink() && result.agpeclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/applicationGateways/{applicationGatewayName}/privateEndpointConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) ListResponder(resp *http.Response) (result ApplicationGatewayPrivateEndpointConnectionListResult, err error) { - err = autorest.Respond( - resp, - 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 ApplicationGatewayPrivateEndpointConnectionsClient) listNextResults(ctx context.Context, lastResults ApplicationGatewayPrivateEndpointConnectionListResult) (result ApplicationGatewayPrivateEndpointConnectionListResult, err error) { - req, err := lastResults.applicationGatewayPrivateEndpointConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) ListComplete(ctx context.Context, resourceGroupName string, applicationGatewayName string) (result ApplicationGatewayPrivateEndpointConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayPrivateEndpointConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, applicationGatewayName) - return -} - -// Update updates the specified private endpoint connection on application gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -// connectionName - the name of the application gateway private endpoint connection. -// parameters - parameters supplied to update application gateway private endpoint connection operation. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) Update(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string, parameters ApplicationGatewayPrivateEndpointConnection) (result ApplicationGatewayPrivateEndpointConnectionsUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayPrivateEndpointConnectionsClient.Update") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePreparer(ctx, resourceGroupName, applicationGatewayName, connectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsClient", "Update", nil, "Failure preparing request") - return - } - - result, err = client.UpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsClient", "Update", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string, connectionName string, parameters ApplicationGatewayPrivateEndpointConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "connectionName": autorest.Encode("path", connectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - parameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/privateEndpointConnections/{connectionName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) UpdateSender(req *http.Request) (future ApplicationGatewayPrivateEndpointConnectionsUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client ApplicationGatewayPrivateEndpointConnectionsClient) UpdateResponder(resp *http.Response) (result ApplicationGatewayPrivateEndpointConnection, err error) { - err = autorest.Respond( - resp, - 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/services/network/mgmt/2022-07-01/network/applicationgatewayprivatelinkresources.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgatewayprivatelinkresources.go deleted file mode 100644 index e899d166e8..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgatewayprivatelinkresources.go +++ /dev/null @@ -1,151 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ApplicationGatewayPrivateLinkResourcesClient is the network Client -type ApplicationGatewayPrivateLinkResourcesClient struct { - BaseClient -} - -// NewApplicationGatewayPrivateLinkResourcesClient creates an instance of the -// ApplicationGatewayPrivateLinkResourcesClient client. -func NewApplicationGatewayPrivateLinkResourcesClient(subscriptionID string) ApplicationGatewayPrivateLinkResourcesClient { - return NewApplicationGatewayPrivateLinkResourcesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewApplicationGatewayPrivateLinkResourcesClientWithBaseURI creates an instance of the -// ApplicationGatewayPrivateLinkResourcesClient client using a custom endpoint. Use this when interacting with an -// Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewApplicationGatewayPrivateLinkResourcesClientWithBaseURI(baseURI string, subscriptionID string) ApplicationGatewayPrivateLinkResourcesClient { - return ApplicationGatewayPrivateLinkResourcesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List lists all private link resources on an application gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -func (client ApplicationGatewayPrivateLinkResourcesClient) List(ctx context.Context, resourceGroupName string, applicationGatewayName string) (result ApplicationGatewayPrivateLinkResourceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayPrivateLinkResourcesClient.List") - defer func() { - sc := -1 - if result.agplrlr.Response.Response != nil { - sc = result.agplrlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, applicationGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateLinkResourcesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.agplrlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateLinkResourcesClient", "List", resp, "Failure sending request") - return - } - - result.agplrlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateLinkResourcesClient", "List", resp, "Failure responding to request") - return - } - if result.agplrlr.hasNextLink() && result.agplrlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ApplicationGatewayPrivateLinkResourcesClient) ListPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/applicationGateways/{applicationGatewayName}/privateLinkResources", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewayPrivateLinkResourcesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ApplicationGatewayPrivateLinkResourcesClient) ListResponder(resp *http.Response) (result ApplicationGatewayPrivateLinkResourceListResult, err error) { - err = autorest.Respond( - resp, - 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 ApplicationGatewayPrivateLinkResourcesClient) listNextResults(ctx context.Context, lastResults ApplicationGatewayPrivateLinkResourceListResult) (result ApplicationGatewayPrivateLinkResourceListResult, err error) { - req, err := lastResults.applicationGatewayPrivateLinkResourceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateLinkResourcesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateLinkResourcesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateLinkResourcesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ApplicationGatewayPrivateLinkResourcesClient) ListComplete(ctx context.Context, resourceGroupName string, applicationGatewayName string) (result ApplicationGatewayPrivateLinkResourceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayPrivateLinkResourcesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, applicationGatewayName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgateways.go deleted file mode 100644 index 55a64bbc1a..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgateways.go +++ /dev/null @@ -1,1474 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ApplicationGatewaysClient is the network Client -type ApplicationGatewaysClient struct { - BaseClient -} - -// NewApplicationGatewaysClient creates an instance of the ApplicationGatewaysClient client. -func NewApplicationGatewaysClient(subscriptionID string) ApplicationGatewaysClient { - return NewApplicationGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewApplicationGatewaysClientWithBaseURI creates an instance of the ApplicationGatewaysClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewApplicationGatewaysClientWithBaseURI(baseURI string, subscriptionID string) ApplicationGatewaysClient { - return ApplicationGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// BackendHealth gets the backend health of the specified application gateway in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -// expand - expands BackendAddressPool and BackendHttpSettings referenced in backend health. -func (client ApplicationGatewaysClient) BackendHealth(ctx context.Context, resourceGroupName string, applicationGatewayName string, expand string) (result ApplicationGatewaysBackendHealthFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.BackendHealth") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.BackendHealthPreparer(ctx, resourceGroupName, applicationGatewayName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "BackendHealth", nil, "Failure preparing request") - return - } - - result, err = client.BackendHealthSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "BackendHealth", result.Response(), "Failure sending request") - return - } - - return -} - -// BackendHealthPreparer prepares the BackendHealth request. -func (client ApplicationGatewaysClient) BackendHealthPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/backendhealth", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// BackendHealthSender sends the BackendHealth request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) BackendHealthSender(req *http.Request) (future ApplicationGatewaysBackendHealthFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// BackendHealthResponder handles the response to the BackendHealth request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) BackendHealthResponder(resp *http.Response) (result ApplicationGatewayBackendHealth, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// BackendHealthOnDemand gets the backend health for given combination of backend pool and http setting of the -// specified application gateway in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -// probeRequest - request body for on-demand test probe operation. -// expand - expands BackendAddressPool and BackendHttpSettings referenced in backend health. -func (client ApplicationGatewaysClient) BackendHealthOnDemand(ctx context.Context, resourceGroupName string, applicationGatewayName string, probeRequest ApplicationGatewayOnDemandProbe, expand string) (result ApplicationGatewaysBackendHealthOnDemandFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.BackendHealthOnDemand") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.BackendHealthOnDemandPreparer(ctx, resourceGroupName, applicationGatewayName, probeRequest, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "BackendHealthOnDemand", nil, "Failure preparing request") - return - } - - result, err = client.BackendHealthOnDemandSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "BackendHealthOnDemand", result.Response(), "Failure sending request") - return - } - - return -} - -// BackendHealthOnDemandPreparer prepares the BackendHealthOnDemand request. -func (client ApplicationGatewaysClient) BackendHealthOnDemandPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string, probeRequest ApplicationGatewayOnDemandProbe, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(expand) > 0 { - queryParameters["$expand"] = autorest.Encode("query", expand) - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/getBackendHealthOnDemand", pathParameters), - autorest.WithJSON(probeRequest), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// BackendHealthOnDemandSender sends the BackendHealthOnDemand request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) BackendHealthOnDemandSender(req *http.Request) (future ApplicationGatewaysBackendHealthOnDemandFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// BackendHealthOnDemandResponder handles the response to the BackendHealthOnDemand request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) BackendHealthOnDemandResponder(resp *http.Response) (result ApplicationGatewayBackendHealthOnDemand, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate creates or updates the specified application gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -// parameters - parameters supplied to the create or update application gateway operation. -func (client ApplicationGatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway) (result ApplicationGatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.WebApplicationFirewallConfiguration.RuleSetType", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.RuleSetVersion", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.MaxRequestBodySize", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.MaxRequestBodySize", Name: validation.InclusiveMaximum, Rule: int64(128), Chain: nil}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.MaxRequestBodySize", Name: validation.InclusiveMinimum, Rule: int64(8), Chain: nil}, - }}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.MaxRequestBodySizeInKb", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.MaxRequestBodySizeInKb", Name: validation.InclusiveMaximum, Rule: int64(128), Chain: nil}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.MaxRequestBodySizeInKb", Name: validation.InclusiveMinimum, Rule: int64(8), Chain: nil}, - }}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.FileUploadLimitInMb", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.FileUploadLimitInMb", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}, - }}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.AutoscaleConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.AutoscaleConfiguration.MinCapacity", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.AutoscaleConfiguration.MinCapacity", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.AutoscaleConfiguration.MaxCapacity", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.AutoscaleConfiguration.MaxCapacity", Name: validation.InclusiveMinimum, Rule: int64(2), Chain: nil}}}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.ApplicationGatewaysClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, applicationGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ApplicationGatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) CreateOrUpdateSender(req *http.Request) (future ApplicationGatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result ApplicationGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified application gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -func (client ApplicationGatewaysClient) Delete(ctx context.Context, resourceGroupName string, applicationGatewayName string) (result ApplicationGatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, applicationGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ApplicationGatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/applicationGateways/{applicationGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) DeleteSender(req *http.Request) (future ApplicationGatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified application gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -func (client ApplicationGatewaysClient) Get(ctx context.Context, resourceGroupName string, applicationGatewayName string) (result ApplicationGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, applicationGatewayName) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ApplicationGatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/applicationGateways/{applicationGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) GetResponder(resp *http.Response) (result ApplicationGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetSslPredefinedPolicy gets Ssl predefined policy with the specified policy name. -// Parameters: -// predefinedPolicyName - name of Ssl predefined policy. -func (client ApplicationGatewaysClient) GetSslPredefinedPolicy(ctx context.Context, predefinedPolicyName string) (result ApplicationGatewaySslPredefinedPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.GetSslPredefinedPolicy") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetSslPredefinedPolicyPreparer(ctx, predefinedPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "GetSslPredefinedPolicy", nil, "Failure preparing request") - return - } - - resp, err := client.GetSslPredefinedPolicySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "GetSslPredefinedPolicy", resp, "Failure sending request") - return - } - - result, err = client.GetSslPredefinedPolicyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "GetSslPredefinedPolicy", resp, "Failure responding to request") - return - } - - return -} - -// GetSslPredefinedPolicyPreparer prepares the GetSslPredefinedPolicy request. -func (client ApplicationGatewaysClient) GetSslPredefinedPolicyPreparer(ctx context.Context, predefinedPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "predefinedPolicyName": autorest.Encode("path", predefinedPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableSslOptions/default/predefinedPolicies/{predefinedPolicyName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSslPredefinedPolicySender sends the GetSslPredefinedPolicy request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) GetSslPredefinedPolicySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetSslPredefinedPolicyResponder handles the response to the GetSslPredefinedPolicy request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) GetSslPredefinedPolicyResponder(resp *http.Response) (result ApplicationGatewaySslPredefinedPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all application gateways in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ApplicationGatewaysClient) List(ctx context.Context, resourceGroupName string) (result ApplicationGatewayListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.List") - defer func() { - sc := -1 - if result.aglr.Response.Response != nil { - sc = result.aglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.aglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure sending request") - return - } - - result.aglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure responding to request") - return - } - if result.aglr.hasNextLink() && result.aglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ApplicationGatewaysClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/applicationGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) ListResponder(resp *http.Response) (result ApplicationGatewayListResult, err error) { - err = autorest.Respond( - resp, - 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 ApplicationGatewaysClient) listNextResults(ctx context.Context, lastResults ApplicationGatewayListResult) (result ApplicationGatewayListResult, err error) { - req, err := lastResults.applicationGatewayListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ApplicationGatewaysClient) ListComplete(ctx context.Context, resourceGroupName string) (result ApplicationGatewayListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the application gateways in a subscription. -func (client ApplicationGatewaysClient) ListAll(ctx context.Context) (result ApplicationGatewayListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAll") - defer func() { - sc := -1 - if result.aglr.Response.Response != nil { - sc = result.aglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.aglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure sending request") - return - } - - result.aglr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure responding to request") - return - } - if result.aglr.hasNextLink() && result.aglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client ApplicationGatewaysClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) ListAllResponder(resp *http.Response) (result ApplicationGatewayListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client ApplicationGatewaysClient) listAllNextResults(ctx context.Context, lastResults ApplicationGatewayListResult) (result ApplicationGatewayListResult, err error) { - req, err := lastResults.applicationGatewayListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client ApplicationGatewaysClient) ListAllComplete(ctx context.Context) (result ApplicationGatewayListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListAvailableRequestHeaders lists all available request headers. -func (client ApplicationGatewaysClient) ListAvailableRequestHeaders(ctx context.Context) (result ListString, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAvailableRequestHeaders") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAvailableRequestHeadersPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableRequestHeaders", nil, "Failure preparing request") - return - } - - resp, err := client.ListAvailableRequestHeadersSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableRequestHeaders", resp, "Failure sending request") - return - } - - result, err = client.ListAvailableRequestHeadersResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableRequestHeaders", resp, "Failure responding to request") - return - } - - return -} - -// ListAvailableRequestHeadersPreparer prepares the ListAvailableRequestHeaders request. -func (client ApplicationGatewaysClient) ListAvailableRequestHeadersPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableRequestHeaders", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAvailableRequestHeadersSender sends the ListAvailableRequestHeaders request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) ListAvailableRequestHeadersSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAvailableRequestHeadersResponder handles the response to the ListAvailableRequestHeaders request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) ListAvailableRequestHeadersResponder(resp *http.Response) (result ListString, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListAvailableResponseHeaders lists all available response headers. -func (client ApplicationGatewaysClient) ListAvailableResponseHeaders(ctx context.Context) (result ListString, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAvailableResponseHeaders") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAvailableResponseHeadersPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableResponseHeaders", nil, "Failure preparing request") - return - } - - resp, err := client.ListAvailableResponseHeadersSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableResponseHeaders", resp, "Failure sending request") - return - } - - result, err = client.ListAvailableResponseHeadersResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableResponseHeaders", resp, "Failure responding to request") - return - } - - return -} - -// ListAvailableResponseHeadersPreparer prepares the ListAvailableResponseHeaders request. -func (client ApplicationGatewaysClient) ListAvailableResponseHeadersPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableResponseHeaders", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAvailableResponseHeadersSender sends the ListAvailableResponseHeaders request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) ListAvailableResponseHeadersSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAvailableResponseHeadersResponder handles the response to the ListAvailableResponseHeaders request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) ListAvailableResponseHeadersResponder(resp *http.Response) (result ListString, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListAvailableServerVariables lists all available server variables. -func (client ApplicationGatewaysClient) ListAvailableServerVariables(ctx context.Context) (result ListString, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAvailableServerVariables") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAvailableServerVariablesPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableServerVariables", nil, "Failure preparing request") - return - } - - resp, err := client.ListAvailableServerVariablesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableServerVariables", resp, "Failure sending request") - return - } - - result, err = client.ListAvailableServerVariablesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableServerVariables", resp, "Failure responding to request") - return - } - - return -} - -// ListAvailableServerVariablesPreparer prepares the ListAvailableServerVariables request. -func (client ApplicationGatewaysClient) ListAvailableServerVariablesPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableServerVariables", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAvailableServerVariablesSender sends the ListAvailableServerVariables request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) ListAvailableServerVariablesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAvailableServerVariablesResponder handles the response to the ListAvailableServerVariables request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) ListAvailableServerVariablesResponder(resp *http.Response) (result ListString, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListAvailableSslOptions lists available Ssl options for configuring Ssl policy. -func (client ApplicationGatewaysClient) ListAvailableSslOptions(ctx context.Context) (result ApplicationGatewayAvailableSslOptions, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAvailableSslOptions") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAvailableSslOptionsPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableSslOptions", nil, "Failure preparing request") - return - } - - resp, err := client.ListAvailableSslOptionsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableSslOptions", resp, "Failure sending request") - return - } - - result, err = client.ListAvailableSslOptionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableSslOptions", resp, "Failure responding to request") - return - } - - return -} - -// ListAvailableSslOptionsPreparer prepares the ListAvailableSslOptions request. -func (client ApplicationGatewaysClient) ListAvailableSslOptionsPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableSslOptions/default", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAvailableSslOptionsSender sends the ListAvailableSslOptions request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) ListAvailableSslOptionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAvailableSslOptionsResponder handles the response to the ListAvailableSslOptions request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) ListAvailableSslOptionsResponder(resp *http.Response) (result ApplicationGatewayAvailableSslOptions, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListAvailableSslPredefinedPolicies lists all SSL predefined policies for configuring Ssl policy. -func (client ApplicationGatewaysClient) ListAvailableSslPredefinedPolicies(ctx context.Context) (result ApplicationGatewayAvailableSslPredefinedPoliciesPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAvailableSslPredefinedPolicies") - defer func() { - sc := -1 - if result.agaspp.Response.Response != nil { - sc = result.agaspp.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAvailableSslPredefinedPoliciesNextResults - req, err := client.ListAvailableSslPredefinedPoliciesPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableSslPredefinedPolicies", nil, "Failure preparing request") - return - } - - resp, err := client.ListAvailableSslPredefinedPoliciesSender(req) - if err != nil { - result.agaspp.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableSslPredefinedPolicies", resp, "Failure sending request") - return - } - - result.agaspp, err = client.ListAvailableSslPredefinedPoliciesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableSslPredefinedPolicies", resp, "Failure responding to request") - return - } - if result.agaspp.hasNextLink() && result.agaspp.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAvailableSslPredefinedPoliciesPreparer prepares the ListAvailableSslPredefinedPolicies request. -func (client ApplicationGatewaysClient) ListAvailableSslPredefinedPoliciesPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableSslOptions/default/predefinedPolicies", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAvailableSslPredefinedPoliciesSender sends the ListAvailableSslPredefinedPolicies request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) ListAvailableSslPredefinedPoliciesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAvailableSslPredefinedPoliciesResponder handles the response to the ListAvailableSslPredefinedPolicies request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) ListAvailableSslPredefinedPoliciesResponder(resp *http.Response) (result ApplicationGatewayAvailableSslPredefinedPolicies, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAvailableSslPredefinedPoliciesNextResults retrieves the next set of results, if any. -func (client ApplicationGatewaysClient) listAvailableSslPredefinedPoliciesNextResults(ctx context.Context, lastResults ApplicationGatewayAvailableSslPredefinedPolicies) (result ApplicationGatewayAvailableSslPredefinedPolicies, err error) { - req, err := lastResults.applicationGatewayAvailableSslPredefinedPoliciesPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listAvailableSslPredefinedPoliciesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAvailableSslPredefinedPoliciesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listAvailableSslPredefinedPoliciesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAvailableSslPredefinedPoliciesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "listAvailableSslPredefinedPoliciesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAvailableSslPredefinedPoliciesComplete enumerates all values, automatically crossing page boundaries as required. -func (client ApplicationGatewaysClient) ListAvailableSslPredefinedPoliciesComplete(ctx context.Context) (result ApplicationGatewayAvailableSslPredefinedPoliciesIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAvailableSslPredefinedPolicies") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAvailableSslPredefinedPolicies(ctx) - return -} - -// ListAvailableWafRuleSets lists all available web application firewall rule sets. -func (client ApplicationGatewaysClient) ListAvailableWafRuleSets(ctx context.Context) (result ApplicationGatewayAvailableWafRuleSetsResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.ListAvailableWafRuleSets") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAvailableWafRuleSetsPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableWafRuleSets", nil, "Failure preparing request") - return - } - - resp, err := client.ListAvailableWafRuleSetsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableWafRuleSets", resp, "Failure sending request") - return - } - - result, err = client.ListAvailableWafRuleSetsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableWafRuleSets", resp, "Failure responding to request") - return - } - - return -} - -// ListAvailableWafRuleSetsPreparer prepares the ListAvailableWafRuleSets request. -func (client ApplicationGatewaysClient) ListAvailableWafRuleSetsPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Start starts the specified application gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -func (client ApplicationGatewaysClient) Start(ctx context.Context, resourceGroupName string, applicationGatewayName string) (result ApplicationGatewaysStartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.Start") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPreparer(ctx, resourceGroupName, applicationGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", nil, "Failure preparing request") - return - } - - result, err = client.StartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPreparer prepares the Start request. -func (client ApplicationGatewaysClient) StartPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/applicationGateways/{applicationGatewayName}/start", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartSender sends the Start request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) StartSender(req *http.Request) (future ApplicationGatewaysStartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartResponder handles the response to the Start request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Stop stops the specified application gateway in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -func (client ApplicationGatewaysClient) Stop(ctx context.Context, resourceGroupName string, applicationGatewayName string) (result ApplicationGatewaysStopFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.Stop") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPreparer(ctx, resourceGroupName, applicationGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", nil, "Failure preparing request") - return - } - - result, err = client.StopSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", result.Response(), "Failure sending request") - return - } - - return -} - -// StopPreparer prepares the Stop request. -func (client ApplicationGatewaysClient) StopPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/applicationGateways/{applicationGatewayName}/stop", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StopSender sends the Stop request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) StopSender(req *http.Request) (future ApplicationGatewaysStopFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StopResponder handles the response to the Stop request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// UpdateTags updates the specified application gateway tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationGatewayName - the name of the application gateway. -// parameters - parameters supplied to update application gateway tags. -func (client ApplicationGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, applicationGatewayName string, parameters TagsObject) (result ApplicationGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewaysClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, applicationGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ApplicationGatewaysClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, applicationGatewayName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationGatewayName": autorest.Encode("path", applicationGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewaysClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ApplicationGatewaysClient) UpdateTagsResponder(resp *http.Response) (result ApplicationGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgatewaywafdynamicmanifests.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgatewaywafdynamicmanifests.go deleted file mode 100644 index b77a7e4da9..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgatewaywafdynamicmanifests.go +++ /dev/null @@ -1,149 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ApplicationGatewayWafDynamicManifestsClient is the network Client -type ApplicationGatewayWafDynamicManifestsClient struct { - BaseClient -} - -// NewApplicationGatewayWafDynamicManifestsClient creates an instance of the -// ApplicationGatewayWafDynamicManifestsClient client. -func NewApplicationGatewayWafDynamicManifestsClient(subscriptionID string) ApplicationGatewayWafDynamicManifestsClient { - return NewApplicationGatewayWafDynamicManifestsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewApplicationGatewayWafDynamicManifestsClientWithBaseURI creates an instance of the -// ApplicationGatewayWafDynamicManifestsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewApplicationGatewayWafDynamicManifestsClientWithBaseURI(baseURI string, subscriptionID string) ApplicationGatewayWafDynamicManifestsClient { - return ApplicationGatewayWafDynamicManifestsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets the regional application gateway waf manifest. -// Parameters: -// location - the region where the nrp are located at. -func (client ApplicationGatewayWafDynamicManifestsClient) Get(ctx context.Context, location string) (result ApplicationGatewayWafDynamicManifestResultListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayWafDynamicManifestsClient.Get") - defer func() { - sc := -1 - if result.agwdmrl.Response.Response != nil { - sc = result.agwdmrl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.getNextResults - req, err := client.GetPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayWafDynamicManifestsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.agwdmrl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayWafDynamicManifestsClient", "Get", resp, "Failure sending request") - return - } - - result.agwdmrl, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayWafDynamicManifestsClient", "Get", resp, "Failure responding to request") - return - } - if result.agwdmrl.hasNextLink() && result.agwdmrl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ApplicationGatewayWafDynamicManifestsClient) GetPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/applicationGatewayWafDynamicManifests", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewayWafDynamicManifestsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ApplicationGatewayWafDynamicManifestsClient) GetResponder(resp *http.Response) (result ApplicationGatewayWafDynamicManifestResultList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getNextResults retrieves the next set of results, if any. -func (client ApplicationGatewayWafDynamicManifestsClient) getNextResults(ctx context.Context, lastResults ApplicationGatewayWafDynamicManifestResultList) (result ApplicationGatewayWafDynamicManifestResultList, err error) { - req, err := lastResults.applicationGatewayWafDynamicManifestResultListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewayWafDynamicManifestsClient", "getNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewayWafDynamicManifestsClient", "getNextResults", resp, "Failure sending next results request") - } - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayWafDynamicManifestsClient", "getNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetComplete enumerates all values, automatically crossing page boundaries as required. -func (client ApplicationGatewayWafDynamicManifestsClient) GetComplete(ctx context.Context, location string) (result ApplicationGatewayWafDynamicManifestResultListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayWafDynamicManifestsClient.Get") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.Get(ctx, location) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgatewaywafdynamicmanifestsdefault.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgatewaywafdynamicmanifestsdefault.go deleted file mode 100644 index 5068e59eef..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationgatewaywafdynamicmanifestsdefault.go +++ /dev/null @@ -1,107 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ApplicationGatewayWafDynamicManifestsDefaultClient is the network Client -type ApplicationGatewayWafDynamicManifestsDefaultClient struct { - BaseClient -} - -// NewApplicationGatewayWafDynamicManifestsDefaultClient creates an instance of the -// ApplicationGatewayWafDynamicManifestsDefaultClient client. -func NewApplicationGatewayWafDynamicManifestsDefaultClient(subscriptionID string) ApplicationGatewayWafDynamicManifestsDefaultClient { - return NewApplicationGatewayWafDynamicManifestsDefaultClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewApplicationGatewayWafDynamicManifestsDefaultClientWithBaseURI creates an instance of the -// ApplicationGatewayWafDynamicManifestsDefaultClient client using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewApplicationGatewayWafDynamicManifestsDefaultClientWithBaseURI(baseURI string, subscriptionID string) ApplicationGatewayWafDynamicManifestsDefaultClient { - return ApplicationGatewayWafDynamicManifestsDefaultClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets the regional application gateway waf manifest. -// Parameters: -// location - the region where the nrp are located at. -func (client ApplicationGatewayWafDynamicManifestsDefaultClient) Get(ctx context.Context, location string) (result ApplicationGatewayWafDynamicManifestResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayWafDynamicManifestsDefaultClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayWafDynamicManifestsDefaultClient", "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.ApplicationGatewayWafDynamicManifestsDefaultClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayWafDynamicManifestsDefaultClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ApplicationGatewayWafDynamicManifestsDefaultClient) GetPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/applicationGatewayWafDynamicManifests/dafault", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationGatewayWafDynamicManifestsDefaultClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ApplicationGatewayWafDynamicManifestsDefaultClient) GetResponder(resp *http.Response) (result ApplicationGatewayWafDynamicManifestResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationsecuritygroups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationsecuritygroups.go deleted file mode 100644 index 7e0bf86d3a..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/applicationsecuritygroups.go +++ /dev/null @@ -1,577 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ApplicationSecurityGroupsClient is the network Client -type ApplicationSecurityGroupsClient struct { - BaseClient -} - -// NewApplicationSecurityGroupsClient creates an instance of the ApplicationSecurityGroupsClient client. -func NewApplicationSecurityGroupsClient(subscriptionID string) ApplicationSecurityGroupsClient { - return NewApplicationSecurityGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewApplicationSecurityGroupsClientWithBaseURI creates an instance of the ApplicationSecurityGroupsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewApplicationSecurityGroupsClientWithBaseURI(baseURI string, subscriptionID string) ApplicationSecurityGroupsClient { - return ApplicationSecurityGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates an application security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationSecurityGroupName - the name of the application security group. -// parameters - parameters supplied to the create or update ApplicationSecurityGroup operation. -func (client ApplicationSecurityGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, parameters ApplicationSecurityGroup) (result ApplicationSecurityGroupsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, applicationSecurityGroupName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ApplicationSecurityGroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, parameters ApplicationSecurityGroup) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationSecurityGroupName": autorest.Encode("path", applicationSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationSecurityGroupsClient) CreateOrUpdateSender(req *http.Request) (future ApplicationSecurityGroupsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ApplicationSecurityGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result ApplicationSecurityGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified application security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationSecurityGroupName - the name of the application security group. -func (client ApplicationSecurityGroupsClient) Delete(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string) (result ApplicationSecurityGroupsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, applicationSecurityGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ApplicationSecurityGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationSecurityGroupName": autorest.Encode("path", applicationSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/applicationSecurityGroups/{applicationSecurityGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationSecurityGroupsClient) DeleteSender(req *http.Request) (future ApplicationSecurityGroupsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ApplicationSecurityGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets information about the specified application security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationSecurityGroupName - the name of the application security group. -func (client ApplicationSecurityGroupsClient) Get(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string) (result ApplicationSecurityGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, applicationSecurityGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "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.ApplicationSecurityGroupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ApplicationSecurityGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationSecurityGroupName": autorest.Encode("path", applicationSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/applicationSecurityGroups/{applicationSecurityGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationSecurityGroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ApplicationSecurityGroupsClient) GetResponder(resp *http.Response) (result ApplicationSecurityGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the application security groups in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ApplicationSecurityGroupsClient) List(ctx context.Context, resourceGroupName string) (result ApplicationSecurityGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.List") - defer func() { - sc := -1 - if result.asglr.Response.Response != nil { - sc = result.asglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.asglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "List", resp, "Failure sending request") - return - } - - result.asglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "List", resp, "Failure responding to request") - return - } - if result.asglr.hasNextLink() && result.asglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ApplicationSecurityGroupsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/applicationSecurityGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationSecurityGroupsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ApplicationSecurityGroupsClient) ListResponder(resp *http.Response) (result ApplicationSecurityGroupListResult, err error) { - err = autorest.Respond( - resp, - 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 ApplicationSecurityGroupsClient) listNextResults(ctx context.Context, lastResults ApplicationSecurityGroupListResult) (result ApplicationSecurityGroupListResult, err error) { - req, err := lastResults.applicationSecurityGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ApplicationSecurityGroupsClient) ListComplete(ctx context.Context, resourceGroupName string) (result ApplicationSecurityGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all application security groups in a subscription. -func (client ApplicationSecurityGroupsClient) ListAll(ctx context.Context) (result ApplicationSecurityGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.ListAll") - defer func() { - sc := -1 - if result.asglr.Response.Response != nil { - sc = result.asglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.asglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "ListAll", resp, "Failure sending request") - return - } - - result.asglr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "ListAll", resp, "Failure responding to request") - return - } - if result.asglr.hasNextLink() && result.asglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client ApplicationSecurityGroupsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationSecurityGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationSecurityGroupsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client ApplicationSecurityGroupsClient) ListAllResponder(resp *http.Response) (result ApplicationSecurityGroupListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client ApplicationSecurityGroupsClient) listAllNextResults(ctx context.Context, lastResults ApplicationSecurityGroupListResult) (result ApplicationSecurityGroupListResult, err error) { - req, err := lastResults.applicationSecurityGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client ApplicationSecurityGroupsClient) ListAllComplete(ctx context.Context) (result ApplicationSecurityGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// UpdateTags updates an application security group's tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// applicationSecurityGroupName - the name of the application security group. -// parameters - parameters supplied to update application security group tags. -func (client ApplicationSecurityGroupsClient) UpdateTags(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, parameters TagsObject) (result ApplicationSecurityGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupsClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, applicationSecurityGroupName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ApplicationSecurityGroupsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, applicationSecurityGroupName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "applicationSecurityGroupName": autorest.Encode("path", applicationSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ApplicationSecurityGroupsClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ApplicationSecurityGroupsClient) UpdateTagsResponder(resp *http.Response) (result ApplicationSecurityGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availabledelegations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availabledelegations.go deleted file mode 100644 index f5262c8851..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availabledelegations.go +++ /dev/null @@ -1,148 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AvailableDelegationsClient is the network Client -type AvailableDelegationsClient struct { - BaseClient -} - -// NewAvailableDelegationsClient creates an instance of the AvailableDelegationsClient client. -func NewAvailableDelegationsClient(subscriptionID string) AvailableDelegationsClient { - return NewAvailableDelegationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAvailableDelegationsClientWithBaseURI creates an instance of the AvailableDelegationsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewAvailableDelegationsClientWithBaseURI(baseURI string, subscriptionID string) AvailableDelegationsClient { - return AvailableDelegationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets all of the available subnet delegations for this subscription in this region. -// Parameters: -// location - the location of the subnet. -func (client AvailableDelegationsClient) List(ctx context.Context, location string) (result AvailableDelegationsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableDelegationsClient.List") - defer func() { - sc := -1 - if result.adr.Response.Response != nil { - sc = result.adr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableDelegationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.adr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AvailableDelegationsClient", "List", resp, "Failure sending request") - return - } - - result.adr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableDelegationsClient", "List", resp, "Failure responding to request") - return - } - if result.adr.hasNextLink() && result.adr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AvailableDelegationsClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/availableDelegations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client AvailableDelegationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AvailableDelegationsClient) ListResponder(resp *http.Response) (result AvailableDelegationsResult, err error) { - err = autorest.Respond( - resp, - 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 AvailableDelegationsClient) listNextResults(ctx context.Context, lastResults AvailableDelegationsResult) (result AvailableDelegationsResult, err error) { - req, err := lastResults.availableDelegationsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AvailableDelegationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AvailableDelegationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableDelegationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AvailableDelegationsClient) ListComplete(ctx context.Context, location string) (result AvailableDelegationsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableDelegationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, location) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availableendpointservices.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availableendpointservices.go deleted file mode 100644 index c5ac9b3f4e..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availableendpointservices.go +++ /dev/null @@ -1,148 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AvailableEndpointServicesClient is the network Client -type AvailableEndpointServicesClient struct { - BaseClient -} - -// NewAvailableEndpointServicesClient creates an instance of the AvailableEndpointServicesClient client. -func NewAvailableEndpointServicesClient(subscriptionID string) AvailableEndpointServicesClient { - return NewAvailableEndpointServicesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAvailableEndpointServicesClientWithBaseURI creates an instance of the AvailableEndpointServicesClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewAvailableEndpointServicesClientWithBaseURI(baseURI string, subscriptionID string) AvailableEndpointServicesClient { - return AvailableEndpointServicesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List list what values of endpoint services are available for use. -// Parameters: -// location - the location to check available endpoint services. -func (client AvailableEndpointServicesClient) List(ctx context.Context, location string) (result EndpointServicesListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableEndpointServicesClient.List") - defer func() { - sc := -1 - if result.eslr.Response.Response != nil { - sc = result.eslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.eslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "List", resp, "Failure sending request") - return - } - - result.eslr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "List", resp, "Failure responding to request") - return - } - if result.eslr.hasNextLink() && result.eslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AvailableEndpointServicesClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/virtualNetworkAvailableEndpointServices", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client AvailableEndpointServicesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AvailableEndpointServicesClient) ListResponder(resp *http.Response) (result EndpointServicesListResult, err error) { - err = autorest.Respond( - resp, - 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 AvailableEndpointServicesClient) listNextResults(ctx context.Context, lastResults EndpointServicesListResult) (result EndpointServicesListResult, err error) { - req, err := lastResults.endpointServicesListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableEndpointServicesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AvailableEndpointServicesClient) ListComplete(ctx context.Context, location string) (result EndpointServicesListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableEndpointServicesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, location) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availableprivateendpointtypes.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availableprivateendpointtypes.go deleted file mode 100644 index cfbe6e5075..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availableprivateendpointtypes.go +++ /dev/null @@ -1,267 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AvailablePrivateEndpointTypesClient is the network Client -type AvailablePrivateEndpointTypesClient struct { - BaseClient -} - -// NewAvailablePrivateEndpointTypesClient creates an instance of the AvailablePrivateEndpointTypesClient client. -func NewAvailablePrivateEndpointTypesClient(subscriptionID string) AvailablePrivateEndpointTypesClient { - return NewAvailablePrivateEndpointTypesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAvailablePrivateEndpointTypesClientWithBaseURI creates an instance of the AvailablePrivateEndpointTypesClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewAvailablePrivateEndpointTypesClientWithBaseURI(baseURI string, subscriptionID string) AvailablePrivateEndpointTypesClient { - return AvailablePrivateEndpointTypesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List returns all of the resource types that can be linked to a Private Endpoint in this subscription in this region. -// Parameters: -// location - the location of the domain name. -func (client AvailablePrivateEndpointTypesClient) List(ctx context.Context, location string) (result AvailablePrivateEndpointTypesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailablePrivateEndpointTypesClient.List") - defer func() { - sc := -1 - if result.apetr.Response.Response != nil { - sc = result.apetr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailablePrivateEndpointTypesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.apetr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AvailablePrivateEndpointTypesClient", "List", resp, "Failure sending request") - return - } - - result.apetr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailablePrivateEndpointTypesClient", "List", resp, "Failure responding to request") - return - } - if result.apetr.hasNextLink() && result.apetr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AvailablePrivateEndpointTypesClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/availablePrivateEndpointTypes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client AvailablePrivateEndpointTypesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AvailablePrivateEndpointTypesClient) ListResponder(resp *http.Response) (result AvailablePrivateEndpointTypesResult, err error) { - err = autorest.Respond( - resp, - 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 AvailablePrivateEndpointTypesClient) listNextResults(ctx context.Context, lastResults AvailablePrivateEndpointTypesResult) (result AvailablePrivateEndpointTypesResult, err error) { - req, err := lastResults.availablePrivateEndpointTypesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AvailablePrivateEndpointTypesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AvailablePrivateEndpointTypesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailablePrivateEndpointTypesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AvailablePrivateEndpointTypesClient) ListComplete(ctx context.Context, location string) (result AvailablePrivateEndpointTypesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailablePrivateEndpointTypesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, location) - return -} - -// ListByResourceGroup returns all of the resource types that can be linked to a Private Endpoint in this subscription -// in this region. -// Parameters: -// location - the location of the domain name. -// resourceGroupName - the name of the resource group. -func (client AvailablePrivateEndpointTypesClient) ListByResourceGroup(ctx context.Context, location string, resourceGroupName string) (result AvailablePrivateEndpointTypesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailablePrivateEndpointTypesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.apetr.Response.Response != nil { - sc = result.apetr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, location, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailablePrivateEndpointTypesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.apetr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AvailablePrivateEndpointTypesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.apetr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailablePrivateEndpointTypesClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.apetr.hasNextLink() && result.apetr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client AvailablePrivateEndpointTypesClient) ListByResourceGroupPreparer(ctx context.Context, location string, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/locations/{location}/availablePrivateEndpointTypes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client AvailablePrivateEndpointTypesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client AvailablePrivateEndpointTypesClient) ListByResourceGroupResponder(resp *http.Response) (result AvailablePrivateEndpointTypesResult, err error) { - err = autorest.Respond( - resp, - 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 AvailablePrivateEndpointTypesClient) listByResourceGroupNextResults(ctx context.Context, lastResults AvailablePrivateEndpointTypesResult) (result AvailablePrivateEndpointTypesResult, err error) { - req, err := lastResults.availablePrivateEndpointTypesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AvailablePrivateEndpointTypesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AvailablePrivateEndpointTypesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailablePrivateEndpointTypesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client AvailablePrivateEndpointTypesClient) ListByResourceGroupComplete(ctx context.Context, location string, resourceGroupName string) (result AvailablePrivateEndpointTypesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailablePrivateEndpointTypesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, location, resourceGroupName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availableresourcegroupdelegations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availableresourcegroupdelegations.go deleted file mode 100644 index 81bce62072..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availableresourcegroupdelegations.go +++ /dev/null @@ -1,151 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AvailableResourceGroupDelegationsClient is the network Client -type AvailableResourceGroupDelegationsClient struct { - BaseClient -} - -// NewAvailableResourceGroupDelegationsClient creates an instance of the AvailableResourceGroupDelegationsClient -// client. -func NewAvailableResourceGroupDelegationsClient(subscriptionID string) AvailableResourceGroupDelegationsClient { - return NewAvailableResourceGroupDelegationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAvailableResourceGroupDelegationsClientWithBaseURI creates an instance of the -// AvailableResourceGroupDelegationsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewAvailableResourceGroupDelegationsClientWithBaseURI(baseURI string, subscriptionID string) AvailableResourceGroupDelegationsClient { - return AvailableResourceGroupDelegationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets all of the available subnet delegations for this resource group in this region. -// Parameters: -// location - the location of the domain name. -// resourceGroupName - the name of the resource group. -func (client AvailableResourceGroupDelegationsClient) List(ctx context.Context, location string, resourceGroupName string) (result AvailableDelegationsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableResourceGroupDelegationsClient.List") - defer func() { - sc := -1 - if result.adr.Response.Response != nil { - sc = result.adr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, location, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableResourceGroupDelegationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.adr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AvailableResourceGroupDelegationsClient", "List", resp, "Failure sending request") - return - } - - result.adr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableResourceGroupDelegationsClient", "List", resp, "Failure responding to request") - return - } - if result.adr.hasNextLink() && result.adr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AvailableResourceGroupDelegationsClient) ListPreparer(ctx context.Context, location string, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/locations/{location}/availableDelegations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client AvailableResourceGroupDelegationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AvailableResourceGroupDelegationsClient) ListResponder(resp *http.Response) (result AvailableDelegationsResult, err error) { - err = autorest.Respond( - resp, - 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 AvailableResourceGroupDelegationsClient) listNextResults(ctx context.Context, lastResults AvailableDelegationsResult) (result AvailableDelegationsResult, err error) { - req, err := lastResults.availableDelegationsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AvailableResourceGroupDelegationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AvailableResourceGroupDelegationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableResourceGroupDelegationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AvailableResourceGroupDelegationsClient) ListComplete(ctx context.Context, location string, resourceGroupName string) (result AvailableDelegationsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableResourceGroupDelegationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, location, resourceGroupName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availableservicealiases.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availableservicealiases.go deleted file mode 100644 index 6b7a2b613d..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/availableservicealiases.go +++ /dev/null @@ -1,266 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AvailableServiceAliasesClient is the network Client -type AvailableServiceAliasesClient struct { - BaseClient -} - -// NewAvailableServiceAliasesClient creates an instance of the AvailableServiceAliasesClient client. -func NewAvailableServiceAliasesClient(subscriptionID string) AvailableServiceAliasesClient { - return NewAvailableServiceAliasesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAvailableServiceAliasesClientWithBaseURI creates an instance of the AvailableServiceAliasesClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewAvailableServiceAliasesClientWithBaseURI(baseURI string, subscriptionID string) AvailableServiceAliasesClient { - return AvailableServiceAliasesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets all available service aliases for this subscription in this region. -// Parameters: -// location - the location. -func (client AvailableServiceAliasesClient) List(ctx context.Context, location string) (result AvailableServiceAliasesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableServiceAliasesClient.List") - defer func() { - sc := -1 - if result.asar.Response.Response != nil { - sc = result.asar.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableServiceAliasesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.asar.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AvailableServiceAliasesClient", "List", resp, "Failure sending request") - return - } - - result.asar, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableServiceAliasesClient", "List", resp, "Failure responding to request") - return - } - if result.asar.hasNextLink() && result.asar.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AvailableServiceAliasesClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/availableServiceAliases", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client AvailableServiceAliasesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AvailableServiceAliasesClient) ListResponder(resp *http.Response) (result AvailableServiceAliasesResult, err error) { - err = autorest.Respond( - resp, - 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 AvailableServiceAliasesClient) listNextResults(ctx context.Context, lastResults AvailableServiceAliasesResult) (result AvailableServiceAliasesResult, err error) { - req, err := lastResults.availableServiceAliasesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AvailableServiceAliasesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AvailableServiceAliasesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableServiceAliasesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AvailableServiceAliasesClient) ListComplete(ctx context.Context, location string) (result AvailableServiceAliasesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableServiceAliasesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, location) - return -} - -// ListByResourceGroup gets all available service aliases for this resource group in this region. -// Parameters: -// resourceGroupName - the name of the resource group. -// location - the location. -func (client AvailableServiceAliasesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, location string) (result AvailableServiceAliasesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableServiceAliasesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.asar.Response.Response != nil { - sc = result.asar.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, location) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableServiceAliasesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.asar.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AvailableServiceAliasesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.asar, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableServiceAliasesClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.asar.hasNextLink() && result.asar.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client AvailableServiceAliasesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/locations/{location}/availableServiceAliases", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client AvailableServiceAliasesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client AvailableServiceAliasesClient) ListByResourceGroupResponder(resp *http.Response) (result AvailableServiceAliasesResult, err error) { - err = autorest.Respond( - resp, - 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 AvailableServiceAliasesClient) listByResourceGroupNextResults(ctx context.Context, lastResults AvailableServiceAliasesResult) (result AvailableServiceAliasesResult, err error) { - req, err := lastResults.availableServiceAliasesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AvailableServiceAliasesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AvailableServiceAliasesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AvailableServiceAliasesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client AvailableServiceAliasesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, location string) (result AvailableServiceAliasesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableServiceAliasesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName, location) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/azurefirewallfqdntags.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/azurefirewallfqdntags.go deleted file mode 100644 index d8d05de9f5..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/azurefirewallfqdntags.go +++ /dev/null @@ -1,145 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AzureFirewallFqdnTagsClient is the network Client -type AzureFirewallFqdnTagsClient struct { - BaseClient -} - -// NewAzureFirewallFqdnTagsClient creates an instance of the AzureFirewallFqdnTagsClient client. -func NewAzureFirewallFqdnTagsClient(subscriptionID string) AzureFirewallFqdnTagsClient { - return NewAzureFirewallFqdnTagsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAzureFirewallFqdnTagsClientWithBaseURI creates an instance of the AzureFirewallFqdnTagsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewAzureFirewallFqdnTagsClientWithBaseURI(baseURI string, subscriptionID string) AzureFirewallFqdnTagsClient { - return AzureFirewallFqdnTagsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// ListAll gets all the Azure Firewall FQDN Tags in a subscription. -func (client AzureFirewallFqdnTagsClient) ListAll(ctx context.Context) (result AzureFirewallFqdnTagListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallFqdnTagsClient.ListAll") - defer func() { - sc := -1 - if result.afftlr.Response.Response != nil { - sc = result.afftlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallFqdnTagsClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.afftlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AzureFirewallFqdnTagsClient", "ListAll", resp, "Failure sending request") - return - } - - result.afftlr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallFqdnTagsClient", "ListAll", resp, "Failure responding to request") - return - } - if result.afftlr.hasNextLink() && result.afftlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client AzureFirewallFqdnTagsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureFirewallFqdnTags", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallFqdnTagsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client AzureFirewallFqdnTagsClient) ListAllResponder(resp *http.Response) (result AzureFirewallFqdnTagListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client AzureFirewallFqdnTagsClient) listAllNextResults(ctx context.Context, lastResults AzureFirewallFqdnTagListResult) (result AzureFirewallFqdnTagListResult, err error) { - req, err := lastResults.azureFirewallFqdnTagListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AzureFirewallFqdnTagsClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AzureFirewallFqdnTagsClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallFqdnTagsClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client AzureFirewallFqdnTagsClient) ListAllComplete(ctx context.Context) (result AzureFirewallFqdnTagListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallFqdnTagsClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/azurefirewalls.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/azurefirewalls.go deleted file mode 100644 index 3246b6636b..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/azurefirewalls.go +++ /dev/null @@ -1,666 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// AzureFirewallsClient is the network Client -type AzureFirewallsClient struct { - BaseClient -} - -// NewAzureFirewallsClient creates an instance of the AzureFirewallsClient client. -func NewAzureFirewallsClient(subscriptionID string) AzureFirewallsClient { - return NewAzureFirewallsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewAzureFirewallsClientWithBaseURI creates an instance of the AzureFirewallsClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewAzureFirewallsClientWithBaseURI(baseURI string, subscriptionID string) AzureFirewallsClient { - return AzureFirewallsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates the specified Azure Firewall. -// Parameters: -// resourceGroupName - the name of the resource group. -// azureFirewallName - the name of the Azure Firewall. -// parameters - parameters supplied to the create or update Azure Firewall operation. -func (client AzureFirewallsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters AzureFirewall) (result AzureFirewallsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: azureFirewallName, - Constraints: []validation.Constraint{{Target: "azureFirewallName", Name: validation.MaxLength, Rule: 56, Chain: nil}, - {Target: "azureFirewallName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.AzureFirewallsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, azureFirewallName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client AzureFirewallsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters AzureFirewall) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "azureFirewallName": autorest.Encode("path", azureFirewallName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallsClient) CreateOrUpdateSender(req *http.Request) (future AzureFirewallsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client AzureFirewallsClient) CreateOrUpdateResponder(resp *http.Response) (result AzureFirewall, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified Azure Firewall. -// Parameters: -// resourceGroupName - the name of the resource group. -// azureFirewallName - the name of the Azure Firewall. -func (client AzureFirewallsClient) Delete(ctx context.Context, resourceGroupName string, azureFirewallName string) (result AzureFirewallsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, azureFirewallName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client AzureFirewallsClient) DeletePreparer(ctx context.Context, resourceGroupName string, azureFirewallName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "azureFirewallName": autorest.Encode("path", azureFirewallName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/azureFirewalls/{azureFirewallName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallsClient) DeleteSender(req *http.Request) (future AzureFirewallsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client AzureFirewallsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified Azure Firewall. -// Parameters: -// resourceGroupName - the name of the resource group. -// azureFirewallName - the name of the Azure Firewall. -func (client AzureFirewallsClient) Get(ctx context.Context, resourceGroupName string, azureFirewallName string) (result AzureFirewall, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, azureFirewallName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "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.AzureFirewallsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client AzureFirewallsClient) GetPreparer(ctx context.Context, resourceGroupName string, azureFirewallName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "azureFirewallName": autorest.Encode("path", azureFirewallName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/azureFirewalls/{azureFirewallName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client AzureFirewallsClient) GetResponder(resp *http.Response) (result AzureFirewall, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all Azure Firewalls in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client AzureFirewallsClient) List(ctx context.Context, resourceGroupName string) (result AzureFirewallListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.List") - defer func() { - sc := -1 - if result.aflr.Response.Response != nil { - sc = result.aflr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.aflr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "List", resp, "Failure sending request") - return - } - - result.aflr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "List", resp, "Failure responding to request") - return - } - if result.aflr.hasNextLink() && result.aflr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client AzureFirewallsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/azureFirewalls", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client AzureFirewallsClient) ListResponder(resp *http.Response) (result AzureFirewallListResult, err error) { - err = autorest.Respond( - resp, - 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 AzureFirewallsClient) listNextResults(ctx context.Context, lastResults AzureFirewallListResult) (result AzureFirewallListResult, err error) { - req, err := lastResults.azureFirewallListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client AzureFirewallsClient) ListComplete(ctx context.Context, resourceGroupName string) (result AzureFirewallListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the Azure Firewalls in a subscription. -func (client AzureFirewallsClient) ListAll(ctx context.Context) (result AzureFirewallListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.ListAll") - defer func() { - sc := -1 - if result.aflr.Response.Response != nil { - sc = result.aflr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.aflr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "ListAll", resp, "Failure sending request") - return - } - - result.aflr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "ListAll", resp, "Failure responding to request") - return - } - if result.aflr.hasNextLink() && result.aflr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client AzureFirewallsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureFirewalls", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client AzureFirewallsClient) ListAllResponder(resp *http.Response) (result AzureFirewallListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client AzureFirewallsClient) listAllNextResults(ctx context.Context, lastResults AzureFirewallListResult) (result AzureFirewallListResult, err error) { - req, err := lastResults.azureFirewallListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client AzureFirewallsClient) ListAllComplete(ctx context.Context) (result AzureFirewallListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListLearnedPrefixes retrieves a list of all IP prefixes that azure firewall has learned to not SNAT. -// Parameters: -// resourceGroupName - the name of the resource group. -// azureFirewallName - the name of the azure firewall. -func (client AzureFirewallsClient) ListLearnedPrefixes(ctx context.Context, resourceGroupName string, azureFirewallName string) (result AzureFirewallsListLearnedPrefixesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.ListLearnedPrefixes") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListLearnedPrefixesPreparer(ctx, resourceGroupName, azureFirewallName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "ListLearnedPrefixes", nil, "Failure preparing request") - return - } - - result, err = client.ListLearnedPrefixesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "ListLearnedPrefixes", result.Response(), "Failure sending request") - return - } - - return -} - -// ListLearnedPrefixesPreparer prepares the ListLearnedPrefixes request. -func (client AzureFirewallsClient) ListLearnedPrefixesPreparer(ctx context.Context, resourceGroupName string, azureFirewallName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "azureFirewallName": autorest.Encode("path", azureFirewallName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/azureFirewalls/{azureFirewallName}/learnedIPPrefixes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListLearnedPrefixesSender sends the ListLearnedPrefixes request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallsClient) ListLearnedPrefixesSender(req *http.Request) (future AzureFirewallsListLearnedPrefixesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListLearnedPrefixesResponder handles the response to the ListLearnedPrefixes request. The method always -// closes the http.Response Body. -func (client AzureFirewallsClient) ListLearnedPrefixesResponder(resp *http.Response) (result IPPrefixesList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates tags of an Azure Firewall resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// azureFirewallName - the name of the Azure Firewall. -// parameters - parameters supplied to update azure firewall tags. -func (client AzureFirewallsClient) UpdateTags(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters TagsObject) (result AzureFirewallsUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallsClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, azureFirewallName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client AzureFirewallsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, azureFirewallName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "azureFirewallName": autorest.Encode("path", azureFirewallName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/azureFirewalls/{azureFirewallName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client AzureFirewallsClient) UpdateTagsSender(req *http.Request) (future AzureFirewallsUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client AzureFirewallsClient) UpdateTagsResponder(resp *http.Response) (result AzureFirewall, err error) { - err = autorest.Respond( - resp, - 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/services/network/mgmt/2022-07-01/network/bastionhosts.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/bastionhosts.go deleted file mode 100644 index f7f7b35717..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/bastionhosts.go +++ /dev/null @@ -1,591 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// BastionHostsClient is the network Client -type BastionHostsClient struct { - BaseClient -} - -// NewBastionHostsClient creates an instance of the BastionHostsClient client. -func NewBastionHostsClient(subscriptionID string) BastionHostsClient { - return NewBastionHostsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewBastionHostsClientWithBaseURI creates an instance of the BastionHostsClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewBastionHostsClientWithBaseURI(baseURI string, subscriptionID string) BastionHostsClient { - return BastionHostsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates the specified Bastion Host. -// Parameters: -// resourceGroupName - the name of the resource group. -// bastionHostName - the name of the Bastion Host. -// parameters - parameters supplied to the create or update Bastion Host operation. -func (client BastionHostsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, bastionHostName string, parameters BastionHost) (result BastionHostsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionHostsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.BastionHostPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.BastionHostPropertiesFormat.ScaleUnits", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.BastionHostPropertiesFormat.ScaleUnits", Name: validation.InclusiveMaximum, Rule: int64(50), Chain: nil}, - {Target: "parameters.BastionHostPropertiesFormat.ScaleUnits", Name: validation.InclusiveMinimum, Rule: int64(2), Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.BastionHostsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, bastionHostName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client BastionHostsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, bastionHostName string, parameters BastionHost) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "bastionHostName": autorest.Encode("path", bastionHostName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client BastionHostsClient) CreateOrUpdateSender(req *http.Request) (future BastionHostsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client BastionHostsClient) CreateOrUpdateResponder(resp *http.Response) (result BastionHost, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified Bastion Host. -// Parameters: -// resourceGroupName - the name of the resource group. -// bastionHostName - the name of the Bastion Host. -func (client BastionHostsClient) Delete(ctx context.Context, resourceGroupName string, bastionHostName string) (result BastionHostsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionHostsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, bastionHostName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client BastionHostsClient) DeletePreparer(ctx context.Context, resourceGroupName string, bastionHostName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "bastionHostName": autorest.Encode("path", bastionHostName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/bastionHosts/{bastionHostName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client BastionHostsClient) DeleteSender(req *http.Request) (future BastionHostsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client BastionHostsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified Bastion Host. -// Parameters: -// resourceGroupName - the name of the resource group. -// bastionHostName - the name of the Bastion Host. -func (client BastionHostsClient) Get(ctx context.Context, resourceGroupName string, bastionHostName string) (result BastionHost, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionHostsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, bastionHostName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "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.BastionHostsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client BastionHostsClient) GetPreparer(ctx context.Context, resourceGroupName string, bastionHostName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "bastionHostName": autorest.Encode("path", bastionHostName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/bastionHosts/{bastionHostName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client BastionHostsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client BastionHostsClient) GetResponder(resp *http.Response) (result BastionHost, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all Bastion Hosts in a subscription. -func (client BastionHostsClient) List(ctx context.Context) (result BastionHostListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionHostsClient.List") - defer func() { - sc := -1 - if result.bhlr.Response.Response != nil { - sc = result.bhlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.bhlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "List", resp, "Failure sending request") - return - } - - result.bhlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "List", resp, "Failure responding to request") - return - } - if result.bhlr.hasNextLink() && result.bhlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client BastionHostsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/bastionHosts", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client BastionHostsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client BastionHostsClient) ListResponder(resp *http.Response) (result BastionHostListResult, err error) { - err = autorest.Respond( - resp, - 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 BastionHostsClient) listNextResults(ctx context.Context, lastResults BastionHostListResult) (result BastionHostListResult, err error) { - req, err := lastResults.bastionHostListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.BastionHostsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.BastionHostsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client BastionHostsClient) ListComplete(ctx context.Context) (result BastionHostListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionHostsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all Bastion Hosts in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client BastionHostsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result BastionHostListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionHostsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.bhlr.Response.Response != nil { - sc = result.bhlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.bhlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.bhlr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.bhlr.hasNextLink() && result.bhlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client BastionHostsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/bastionHosts", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client BastionHostsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client BastionHostsClient) ListByResourceGroupResponder(resp *http.Response) (result BastionHostListResult, err error) { - err = autorest.Respond( - resp, - 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 BastionHostsClient) listByResourceGroupNextResults(ctx context.Context, lastResults BastionHostListResult) (result BastionHostListResult, err error) { - req, err := lastResults.bastionHostListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.BastionHostsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.BastionHostsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client BastionHostsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result BastionHostListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionHostsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates Tags for BastionHost resource -// Parameters: -// resourceGroupName - the name of the resource group. -// bastionHostName - the name of the Bastion Host. -// parameters - parameters supplied to update BastionHost tags. -func (client BastionHostsClient) UpdateTags(ctx context.Context, resourceGroupName string, bastionHostName string, parameters TagsObject) (result BastionHostsUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionHostsClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, bastionHostName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client BastionHostsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, bastionHostName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "bastionHostName": autorest.Encode("path", bastionHostName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client BastionHostsClient) UpdateTagsSender(req *http.Request) (future BastionHostsUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client BastionHostsClient) UpdateTagsResponder(resp *http.Response) (result BastionHost, err error) { - err = autorest.Respond( - resp, - 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/services/network/mgmt/2022-07-01/network/bgpservicecommunities.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/bgpservicecommunities.go deleted file mode 100644 index 661637839a..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/bgpservicecommunities.go +++ /dev/null @@ -1,145 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// BgpServiceCommunitiesClient is the network Client -type BgpServiceCommunitiesClient struct { - BaseClient -} - -// 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 using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewBgpServiceCommunitiesClientWithBaseURI(baseURI string, subscriptionID string) BgpServiceCommunitiesClient { - return BgpServiceCommunitiesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets all the available bgp service communities. -func (client BgpServiceCommunitiesClient) List(ctx context.Context) (result BgpServiceCommunityListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BgpServiceCommunitiesClient.List") - defer func() { - sc := -1 - if result.bsclr.Response.Response != nil { - sc = result.bsclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.bsclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", resp, "Failure sending request") - return - } - - result.bsclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", resp, "Failure responding to request") - return - } - if result.bsclr.hasNextLink() && result.bsclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client BgpServiceCommunitiesClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - 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(ctx context.Context, lastResults BgpServiceCommunityListResult) (result BgpServiceCommunityListResult, err error) { - req, err := lastResults.bgpServiceCommunityListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client BgpServiceCommunitiesClient) ListComplete(ctx context.Context) (result BgpServiceCommunityListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BgpServiceCommunitiesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/client.go deleted file mode 100644 index 33703c4c94..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/client.go +++ /dev/null @@ -1,1297 +0,0 @@ -// Deprecated: Please note, this package has been deprecated. A replacement package is available [github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork). We strongly encourage you to upgrade to continue receiving updates. See [Migration Guide](https://aka.ms/azsdk/golang/t2/migration) for guidance on upgrading. Refer to our [deprecation policy](https://azure.github.io/azure-sdk/policies_support.html) for more details. -// -// Package network implements the Azure ARM Network service API version . -// -// Network Client -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -const ( - // DefaultBaseURI is the default URI used for the service Network - DefaultBaseURI = "https://management.azure.com" -) - -// BaseClient is the base client for Network. -type BaseClient struct { - autorest.Client - BaseURI string - SubscriptionID string -} - -// New creates an instance of the BaseClient client. -func New(subscriptionID string) BaseClient { - return NewWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewWithBaseURI creates an instance of the BaseClient client using a custom endpoint. Use this when interacting with -// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { - return BaseClient{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: baseURI, - SubscriptionID: subscriptionID, - } -} - -// CheckDNSNameAvailability checks whether a domain name in the cloudapp.azure.com zone is available for use. -// Parameters: -// location - the location of the domain name. -// domainNameLabel - the domain name to be verified. It must conform to the following regular expression: -// ^[a-z][a-z0-9-]{1,61}[a-z0-9]$. -func (client BaseClient) CheckDNSNameAvailability(ctx context.Context, location string, domainNameLabel string) (result DNSNameAvailabilityResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.CheckDNSNameAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CheckDNSNameAvailabilityPreparer(ctx, location, domainNameLabel) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "CheckDNSNameAvailability", nil, "Failure preparing request") - return - } - - resp, err := client.CheckDNSNameAvailabilitySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BaseClient", "CheckDNSNameAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckDNSNameAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "CheckDNSNameAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckDNSNameAvailabilityPreparer prepares the CheckDNSNameAvailability request. -func (client BaseClient) CheckDNSNameAvailabilityPreparer(ctx context.Context, location string, domainNameLabel string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - "domainNameLabel": autorest.Encode("query", domainNameLabel), - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/CheckDnsNameAvailability", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckDNSNameAvailabilitySender sends the CheckDNSNameAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) CheckDNSNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckDNSNameAvailabilityResponder handles the response to the CheckDNSNameAvailability request. The method always -// closes the http.Response Body. -func (client BaseClient) CheckDNSNameAvailabilityResponder(resp *http.Response) (result DNSNameAvailabilityResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteBastionShareableLink deletes the Bastion Shareable Links for all the VMs specified in the request. -// Parameters: -// resourceGroupName - the name of the resource group. -// bastionHostName - the name of the Bastion Host. -// bslRequest - post request for all the Bastion Shareable Link endpoints. -func (client BaseClient) DeleteBastionShareableLink(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest) (result DeleteBastionShareableLinkFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.DeleteBastionShareableLink") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeleteBastionShareableLinkPreparer(ctx, resourceGroupName, bastionHostName, bslRequest) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "DeleteBastionShareableLink", nil, "Failure preparing request") - return - } - - result, err = client.DeleteBastionShareableLinkSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "DeleteBastionShareableLink", result.Response(), "Failure sending request") - return - } - - return -} - -// DeleteBastionShareableLinkPreparer prepares the DeleteBastionShareableLink request. -func (client BaseClient) DeleteBastionShareableLinkPreparer(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "bastionHostName": autorest.Encode("path", bastionHostName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}/deleteShareableLinks", pathParameters), - autorest.WithJSON(bslRequest), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteBastionShareableLinkSender sends the DeleteBastionShareableLink request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) DeleteBastionShareableLinkSender(req *http.Request) (future DeleteBastionShareableLinkFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteBastionShareableLinkResponder handles the response to the DeleteBastionShareableLink request. The method always -// closes the http.Response Body. -func (client BaseClient) DeleteBastionShareableLinkResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// DisconnectActiveSessions returns the list of currently active sessions on the Bastion. -// Parameters: -// resourceGroupName - the name of the resource group. -// bastionHostName - the name of the Bastion Host. -// sessionIds - the list of sessionids to disconnect. -func (client BaseClient) DisconnectActiveSessions(ctx context.Context, resourceGroupName string, bastionHostName string, sessionIds SessionIds) (result BastionSessionDeleteResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.DisconnectActiveSessions") - defer func() { - sc := -1 - if result.bsdr.Response.Response != nil { - sc = result.bsdr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.disconnectActiveSessionsNextResults - req, err := client.DisconnectActiveSessionsPreparer(ctx, resourceGroupName, bastionHostName, sessionIds) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "DisconnectActiveSessions", nil, "Failure preparing request") - return - } - - resp, err := client.DisconnectActiveSessionsSender(req) - if err != nil { - result.bsdr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BaseClient", "DisconnectActiveSessions", resp, "Failure sending request") - return - } - - result.bsdr, err = client.DisconnectActiveSessionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "DisconnectActiveSessions", resp, "Failure responding to request") - return - } - if result.bsdr.hasNextLink() && result.bsdr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// DisconnectActiveSessionsPreparer prepares the DisconnectActiveSessions request. -func (client BaseClient) DisconnectActiveSessionsPreparer(ctx context.Context, resourceGroupName string, bastionHostName string, sessionIds SessionIds) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "bastionHostName": autorest.Encode("path", bastionHostName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}/disconnectActiveSessions", pathParameters), - autorest.WithJSON(sessionIds), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DisconnectActiveSessionsSender sends the DisconnectActiveSessions request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) DisconnectActiveSessionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// DisconnectActiveSessionsResponder handles the response to the DisconnectActiveSessions request. The method always -// closes the http.Response Body. -func (client BaseClient) DisconnectActiveSessionsResponder(resp *http.Response) (result BastionSessionDeleteResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// disconnectActiveSessionsNextResults retrieves the next set of results, if any. -func (client BaseClient) disconnectActiveSessionsNextResults(ctx context.Context, lastResults BastionSessionDeleteResult) (result BastionSessionDeleteResult, err error) { - req, err := lastResults.bastionSessionDeleteResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.BaseClient", "disconnectActiveSessionsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.DisconnectActiveSessionsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.BaseClient", "disconnectActiveSessionsNextResults", resp, "Failure sending next results request") - } - result, err = client.DisconnectActiveSessionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "disconnectActiveSessionsNextResults", resp, "Failure responding to next results request") - } - return -} - -// DisconnectActiveSessionsComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) DisconnectActiveSessionsComplete(ctx context.Context, resourceGroupName string, bastionHostName string, sessionIds SessionIds) (result BastionSessionDeleteResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.DisconnectActiveSessions") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.DisconnectActiveSessions(ctx, resourceGroupName, bastionHostName, sessionIds) - return -} - -// ExpressRouteProviderPortMethod retrieves detail of a provider port. -// Parameters: -// providerport - the name of the provider port. -func (client BaseClient) ExpressRouteProviderPortMethod(ctx context.Context, providerport string) (result ExpressRouteProviderPort, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.ExpressRouteProviderPortMethod") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ExpressRouteProviderPortMethodPreparer(ctx, providerport) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "ExpressRouteProviderPortMethod", nil, "Failure preparing request") - return - } - - resp, err := client.ExpressRouteProviderPortMethodSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BaseClient", "ExpressRouteProviderPortMethod", resp, "Failure sending request") - return - } - - result, err = client.ExpressRouteProviderPortMethodResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "ExpressRouteProviderPortMethod", resp, "Failure responding to request") - return - } - - return -} - -// ExpressRouteProviderPortMethodPreparer prepares the ExpressRouteProviderPortMethod request. -func (client BaseClient) ExpressRouteProviderPortMethodPreparer(ctx context.Context, providerport string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "providerport": autorest.Encode("path", providerport), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteProviderPorts/{providerport}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ExpressRouteProviderPortMethodSender sends the ExpressRouteProviderPortMethod request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) ExpressRouteProviderPortMethodSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ExpressRouteProviderPortMethodResponder handles the response to the ExpressRouteProviderPortMethod request. The method always -// closes the http.Response Body. -func (client BaseClient) ExpressRouteProviderPortMethodResponder(resp *http.Response) (result ExpressRouteProviderPort, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Generatevirtualwanvpnserverconfigurationvpnprofile generates a unique VPN profile for P2S clients for VirtualWan and -// associated VpnServerConfiguration combination in the specified resource group. -// Parameters: -// resourceGroupName - the resource group name. -// virtualWANName - the name of the VirtualWAN whose associated VpnServerConfigurations is needed. -// vpnClientParams - parameters supplied to the generate VirtualWan VPN profile generation operation. -func (client BaseClient) Generatevirtualwanvpnserverconfigurationvpnprofile(ctx context.Context, resourceGroupName string, virtualWANName string, vpnClientParams VirtualWanVpnProfileParameters) (result GeneratevirtualwanvpnserverconfigurationvpnprofileFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.Generatevirtualwanvpnserverconfigurationvpnprofile") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GeneratevirtualwanvpnserverconfigurationvpnprofilePreparer(ctx, resourceGroupName, virtualWANName, vpnClientParams) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "Generatevirtualwanvpnserverconfigurationvpnprofile", nil, "Failure preparing request") - return - } - - result, err = client.GeneratevirtualwanvpnserverconfigurationvpnprofileSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "Generatevirtualwanvpnserverconfigurationvpnprofile", result.Response(), "Failure sending request") - return - } - - return -} - -// GeneratevirtualwanvpnserverconfigurationvpnprofilePreparer prepares the Generatevirtualwanvpnserverconfigurationvpnprofile request. -func (client BaseClient) GeneratevirtualwanvpnserverconfigurationvpnprofilePreparer(ctx context.Context, resourceGroupName string, virtualWANName string, vpnClientParams VirtualWanVpnProfileParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/GenerateVpnProfile", pathParameters), - autorest.WithJSON(vpnClientParams), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GeneratevirtualwanvpnserverconfigurationvpnprofileSender sends the Generatevirtualwanvpnserverconfigurationvpnprofile request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GeneratevirtualwanvpnserverconfigurationvpnprofileSender(req *http.Request) (future GeneratevirtualwanvpnserverconfigurationvpnprofileFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GeneratevirtualwanvpnserverconfigurationvpnprofileResponder handles the response to the Generatevirtualwanvpnserverconfigurationvpnprofile request. The method always -// closes the http.Response Body. -func (client BaseClient) GeneratevirtualwanvpnserverconfigurationvpnprofileResponder(resp *http.Response) (result VpnProfileResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetActiveSessions returns the list of currently active sessions on the Bastion. -// Parameters: -// resourceGroupName - the name of the resource group. -// bastionHostName - the name of the Bastion Host. -func (client BaseClient) GetActiveSessions(ctx context.Context, resourceGroupName string, bastionHostName string) (result GetActiveSessionsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetActiveSessions") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetActiveSessionsPreparer(ctx, resourceGroupName, bastionHostName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "GetActiveSessions", nil, "Failure preparing request") - return - } - - result, err = client.GetActiveSessionsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "GetActiveSessions", result.Response(), "Failure sending request") - return - } - - return -} - -// GetActiveSessionsPreparer prepares the GetActiveSessions request. -func (client BaseClient) GetActiveSessionsPreparer(ctx context.Context, resourceGroupName string, bastionHostName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "bastionHostName": autorest.Encode("path", bastionHostName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/bastionHosts/{bastionHostName}/getActiveSessions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetActiveSessionsSender sends the GetActiveSessions request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetActiveSessionsSender(req *http.Request) (future GetActiveSessionsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetActiveSessionsResponder handles the response to the GetActiveSessions request. The method always -// closes the http.Response Body. -func (client BaseClient) GetActiveSessionsResponder(resp *http.Response) (result BastionActiveSessionListResultPage, err error) { - result.baslr, err = client.getActiveSessionsResponder(resp) - result.fn = client.getActiveSessionsNextResults - return -} - -func (client BaseClient) getActiveSessionsResponder(resp *http.Response) (result BastionActiveSessionListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getActiveSessionsNextResults retrieves the next set of results, if any. -func (client BaseClient) getActiveSessionsNextResults(ctx context.Context, lastResults BastionActiveSessionListResult) (result BastionActiveSessionListResult, err error) { - req, err := lastResults.bastionActiveSessionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.BaseClient", "getActiveSessionsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - var resp *http.Response - resp, err = client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.BaseClient", "getActiveSessionsNextResults", resp, "Failure sending next results request") - } - return client.getActiveSessionsResponder(resp) -} - -// GetActiveSessionsComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetActiveSessionsComplete(ctx context.Context, resourceGroupName string, bastionHostName string) (result GetActiveSessionsAllFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetActiveSessions") - defer func() { - sc := -1 - if result.Response() != nil { - sc = result.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - var future GetActiveSessionsFuture - future, err = client.GetActiveSessions(ctx, resourceGroupName, bastionHostName) - result.FutureAPI = future.FutureAPI - return -} - -// GetBastionShareableLink return the Bastion Shareable Links for all the VMs specified in the request. -// Parameters: -// resourceGroupName - the name of the resource group. -// bastionHostName - the name of the Bastion Host. -// bslRequest - post request for all the Bastion Shareable Link endpoints. -func (client BaseClient) GetBastionShareableLink(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest) (result BastionShareableLinkListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetBastionShareableLink") - defer func() { - sc := -1 - if result.bsllr.Response.Response != nil { - sc = result.bsllr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.getBastionShareableLinkNextResults - req, err := client.GetBastionShareableLinkPreparer(ctx, resourceGroupName, bastionHostName, bslRequest) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "GetBastionShareableLink", nil, "Failure preparing request") - return - } - - resp, err := client.GetBastionShareableLinkSender(req) - if err != nil { - result.bsllr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BaseClient", "GetBastionShareableLink", resp, "Failure sending request") - return - } - - result.bsllr, err = client.GetBastionShareableLinkResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "GetBastionShareableLink", resp, "Failure responding to request") - return - } - if result.bsllr.hasNextLink() && result.bsllr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetBastionShareableLinkPreparer prepares the GetBastionShareableLink request. -func (client BaseClient) GetBastionShareableLinkPreparer(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "bastionHostName": autorest.Encode("path", bastionHostName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}/getShareableLinks", pathParameters), - autorest.WithJSON(bslRequest), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetBastionShareableLinkSender sends the GetBastionShareableLink request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetBastionShareableLinkSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetBastionShareableLinkResponder handles the response to the GetBastionShareableLink request. The method always -// closes the http.Response Body. -func (client BaseClient) GetBastionShareableLinkResponder(resp *http.Response) (result BastionShareableLinkListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getBastionShareableLinkNextResults retrieves the next set of results, if any. -func (client BaseClient) getBastionShareableLinkNextResults(ctx context.Context, lastResults BastionShareableLinkListResult) (result BastionShareableLinkListResult, err error) { - req, err := lastResults.bastionShareableLinkListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.BaseClient", "getBastionShareableLinkNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetBastionShareableLinkSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.BaseClient", "getBastionShareableLinkNextResults", resp, "Failure sending next results request") - } - result, err = client.GetBastionShareableLinkResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "getBastionShareableLinkNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetBastionShareableLinkComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetBastionShareableLinkComplete(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest) (result BastionShareableLinkListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetBastionShareableLink") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetBastionShareableLink(ctx, resourceGroupName, bastionHostName, bslRequest) - return -} - -// ListActiveConnectivityConfigurations lists active connectivity configurations in a network manager. -// Parameters: -// parameters - active Configuration Parameter. -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -func (client BaseClient) ListActiveConnectivityConfigurations(ctx context.Context, parameters ActiveConfigurationParameter, resourceGroupName string, networkManagerName string, top *int32) (result ActiveConnectivityConfigurationsListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.ListActiveConnectivityConfigurations") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.BaseClient", "ListActiveConnectivityConfigurations", err.Error()) - } - - req, err := client.ListActiveConnectivityConfigurationsPreparer(ctx, parameters, resourceGroupName, networkManagerName, top) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "ListActiveConnectivityConfigurations", nil, "Failure preparing request") - return - } - - resp, err := client.ListActiveConnectivityConfigurationsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BaseClient", "ListActiveConnectivityConfigurations", resp, "Failure sending request") - return - } - - result, err = client.ListActiveConnectivityConfigurationsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "ListActiveConnectivityConfigurations", resp, "Failure responding to request") - return - } - - return -} - -// ListActiveConnectivityConfigurationsPreparer prepares the ListActiveConnectivityConfigurations request. -func (client BaseClient) ListActiveConnectivityConfigurationsPreparer(ctx context.Context, parameters ActiveConfigurationParameter, resourceGroupName string, networkManagerName string, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/listActiveConnectivityConfigurations", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListActiveConnectivityConfigurationsSender sends the ListActiveConnectivityConfigurations request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) ListActiveConnectivityConfigurationsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListActiveConnectivityConfigurationsResponder handles the response to the ListActiveConnectivityConfigurations request. The method always -// closes the http.Response Body. -func (client BaseClient) ListActiveConnectivityConfigurationsResponder(resp *http.Response) (result ActiveConnectivityConfigurationsListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListActiveSecurityAdminRules lists active security admin rules in a network manager. -// Parameters: -// parameters - active Configuration Parameter. -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -func (client BaseClient) ListActiveSecurityAdminRules(ctx context.Context, parameters ActiveConfigurationParameter, resourceGroupName string, networkManagerName string, top *int32) (result ActiveSecurityAdminRulesListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.ListActiveSecurityAdminRules") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.BaseClient", "ListActiveSecurityAdminRules", err.Error()) - } - - req, err := client.ListActiveSecurityAdminRulesPreparer(ctx, parameters, resourceGroupName, networkManagerName, top) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "ListActiveSecurityAdminRules", nil, "Failure preparing request") - return - } - - resp, err := client.ListActiveSecurityAdminRulesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BaseClient", "ListActiveSecurityAdminRules", resp, "Failure sending request") - return - } - - result, err = client.ListActiveSecurityAdminRulesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "ListActiveSecurityAdminRules", resp, "Failure responding to request") - return - } - - return -} - -// ListActiveSecurityAdminRulesPreparer prepares the ListActiveSecurityAdminRules request. -func (client BaseClient) ListActiveSecurityAdminRulesPreparer(ctx context.Context, parameters ActiveConfigurationParameter, resourceGroupName string, networkManagerName string, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/listActiveSecurityAdminRules", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListActiveSecurityAdminRulesSender sends the ListActiveSecurityAdminRules request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) ListActiveSecurityAdminRulesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListActiveSecurityAdminRulesResponder handles the response to the ListActiveSecurityAdminRules request. The method always -// closes the http.Response Body. -func (client BaseClient) ListActiveSecurityAdminRulesResponder(resp *http.Response) (result ActiveSecurityAdminRulesListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListNetworkManagerEffectiveConnectivityConfigurations list all effective connectivity configurations applied on a -// virtual network. -// Parameters: -// parameters - parameters supplied to list correct page. -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -func (client BaseClient) ListNetworkManagerEffectiveConnectivityConfigurations(ctx context.Context, parameters QueryRequestOptions, resourceGroupName string, virtualNetworkName string, top *int32) (result ManagerEffectiveConnectivityConfigurationListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.ListNetworkManagerEffectiveConnectivityConfigurations") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.BaseClient", "ListNetworkManagerEffectiveConnectivityConfigurations", err.Error()) - } - - req, err := client.ListNetworkManagerEffectiveConnectivityConfigurationsPreparer(ctx, parameters, resourceGroupName, virtualNetworkName, top) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "ListNetworkManagerEffectiveConnectivityConfigurations", nil, "Failure preparing request") - return - } - - resp, err := client.ListNetworkManagerEffectiveConnectivityConfigurationsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BaseClient", "ListNetworkManagerEffectiveConnectivityConfigurations", resp, "Failure sending request") - return - } - - result, err = client.ListNetworkManagerEffectiveConnectivityConfigurationsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "ListNetworkManagerEffectiveConnectivityConfigurations", resp, "Failure responding to request") - return - } - - return -} - -// ListNetworkManagerEffectiveConnectivityConfigurationsPreparer prepares the ListNetworkManagerEffectiveConnectivityConfigurations request. -func (client BaseClient) ListNetworkManagerEffectiveConnectivityConfigurationsPreparer(ctx context.Context, parameters QueryRequestOptions, resourceGroupName string, virtualNetworkName string, top *int32) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/listNetworkManagerEffectiveConnectivityConfigurations", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListNetworkManagerEffectiveConnectivityConfigurationsSender sends the ListNetworkManagerEffectiveConnectivityConfigurations request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) ListNetworkManagerEffectiveConnectivityConfigurationsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListNetworkManagerEffectiveConnectivityConfigurationsResponder handles the response to the ListNetworkManagerEffectiveConnectivityConfigurations request. The method always -// closes the http.Response Body. -func (client BaseClient) ListNetworkManagerEffectiveConnectivityConfigurationsResponder(resp *http.Response) (result ManagerEffectiveConnectivityConfigurationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListNetworkManagerEffectiveSecurityAdminRules list all effective security admin rules applied on a virtual network. -// Parameters: -// parameters - parameters supplied to list correct page. -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -func (client BaseClient) ListNetworkManagerEffectiveSecurityAdminRules(ctx context.Context, parameters QueryRequestOptions, resourceGroupName string, virtualNetworkName string, top *int32) (result ManagerEffectiveSecurityAdminRulesListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.ListNetworkManagerEffectiveSecurityAdminRules") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.BaseClient", "ListNetworkManagerEffectiveSecurityAdminRules", err.Error()) - } - - req, err := client.ListNetworkManagerEffectiveSecurityAdminRulesPreparer(ctx, parameters, resourceGroupName, virtualNetworkName, top) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "ListNetworkManagerEffectiveSecurityAdminRules", nil, "Failure preparing request") - return - } - - resp, err := client.ListNetworkManagerEffectiveSecurityAdminRulesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BaseClient", "ListNetworkManagerEffectiveSecurityAdminRules", resp, "Failure sending request") - return - } - - result, err = client.ListNetworkManagerEffectiveSecurityAdminRulesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "ListNetworkManagerEffectiveSecurityAdminRules", resp, "Failure responding to request") - return - } - - return -} - -// ListNetworkManagerEffectiveSecurityAdminRulesPreparer prepares the ListNetworkManagerEffectiveSecurityAdminRules request. -func (client BaseClient) ListNetworkManagerEffectiveSecurityAdminRulesPreparer(ctx context.Context, parameters QueryRequestOptions, resourceGroupName string, virtualNetworkName string, top *int32) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/listNetworkManagerEffectiveSecurityAdminRules", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListNetworkManagerEffectiveSecurityAdminRulesSender sends the ListNetworkManagerEffectiveSecurityAdminRules request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) ListNetworkManagerEffectiveSecurityAdminRulesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListNetworkManagerEffectiveSecurityAdminRulesResponder handles the response to the ListNetworkManagerEffectiveSecurityAdminRules request. The method always -// closes the http.Response Body. -func (client BaseClient) ListNetworkManagerEffectiveSecurityAdminRulesResponder(resp *http.Response) (result ManagerEffectiveSecurityAdminRulesListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// PutBastionShareableLink creates a Bastion Shareable Links for all the VMs specified in the request. -// Parameters: -// resourceGroupName - the name of the resource group. -// bastionHostName - the name of the Bastion Host. -// bslRequest - post request for all the Bastion Shareable Link endpoints. -func (client BaseClient) PutBastionShareableLink(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest) (result PutBastionShareableLinkFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.PutBastionShareableLink") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PutBastionShareableLinkPreparer(ctx, resourceGroupName, bastionHostName, bslRequest) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "PutBastionShareableLink", nil, "Failure preparing request") - return - } - - result, err = client.PutBastionShareableLinkSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "PutBastionShareableLink", result.Response(), "Failure sending request") - return - } - - return -} - -// PutBastionShareableLinkPreparer prepares the PutBastionShareableLink request. -func (client BaseClient) PutBastionShareableLinkPreparer(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "bastionHostName": autorest.Encode("path", bastionHostName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}/createShareableLinks", pathParameters), - autorest.WithJSON(bslRequest), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PutBastionShareableLinkSender sends the PutBastionShareableLink request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) PutBastionShareableLinkSender(req *http.Request) (future PutBastionShareableLinkFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// PutBastionShareableLinkResponder handles the response to the PutBastionShareableLink request. The method always -// closes the http.Response Body. -func (client BaseClient) PutBastionShareableLinkResponder(resp *http.Response) (result BastionShareableLinkListResultPage, err error) { - result.bsllr, err = client.putBastionShareableLinkResponder(resp) - result.fn = client.putBastionShareableLinkNextResults - return -} - -func (client BaseClient) putBastionShareableLinkResponder(resp *http.Response) (result BastionShareableLinkListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// putBastionShareableLinkNextResults retrieves the next set of results, if any. -func (client BaseClient) putBastionShareableLinkNextResults(ctx context.Context, lastResults BastionShareableLinkListResult) (result BastionShareableLinkListResult, err error) { - req, err := lastResults.bastionShareableLinkListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.BaseClient", "putBastionShareableLinkNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - var resp *http.Response - resp, err = client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.BaseClient", "putBastionShareableLinkNextResults", resp, "Failure sending next results request") - } - return client.putBastionShareableLinkResponder(resp) -} - -// PutBastionShareableLinkComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) PutBastionShareableLinkComplete(ctx context.Context, resourceGroupName string, bastionHostName string, bslRequest BastionShareableLinkListRequest) (result PutBastionShareableLinkAllFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.PutBastionShareableLink") - defer func() { - sc := -1 - if result.Response() != nil { - sc = result.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - var future PutBastionShareableLinkFuture - future, err = client.PutBastionShareableLink(ctx, resourceGroupName, bastionHostName, bslRequest) - result.FutureAPI = future.FutureAPI - return -} - -// SupportedSecurityProviders gives the supported security providers for the virtual wan. -// Parameters: -// resourceGroupName - the resource group name. -// virtualWANName - the name of the VirtualWAN for which supported security providers are needed. -func (client BaseClient) SupportedSecurityProviders(ctx context.Context, resourceGroupName string, virtualWANName string) (result VirtualWanSecurityProviders, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.SupportedSecurityProviders") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.SupportedSecurityProvidersPreparer(ctx, resourceGroupName, virtualWANName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "SupportedSecurityProviders", nil, "Failure preparing request") - return - } - - resp, err := client.SupportedSecurityProvidersSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.BaseClient", "SupportedSecurityProviders", resp, "Failure sending request") - return - } - - result, err = client.SupportedSecurityProvidersResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BaseClient", "SupportedSecurityProviders", resp, "Failure responding to request") - return - } - - return -} - -// SupportedSecurityProvidersPreparer prepares the SupportedSecurityProviders request. -func (client BaseClient) SupportedSecurityProvidersPreparer(ctx context.Context, resourceGroupName string, virtualWANName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2022-07-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/virtualWans/{virtualWANName}/supportedSecurityProviders", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SupportedSecurityProvidersSender sends the SupportedSecurityProviders request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) SupportedSecurityProvidersSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// SupportedSecurityProvidersResponder handles the response to the SupportedSecurityProviders request. The method always -// closes the http.Response Body. -func (client BaseClient) SupportedSecurityProvidersResponder(resp *http.Response) (result VirtualWanSecurityProviders, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/configurationpolicygroups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/configurationpolicygroups.go deleted file mode 100644 index 79c24fee95..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/configurationpolicygroups.go +++ /dev/null @@ -1,396 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ConfigurationPolicyGroupsClient is the network Client -type ConfigurationPolicyGroupsClient struct { - BaseClient -} - -// NewConfigurationPolicyGroupsClient creates an instance of the ConfigurationPolicyGroupsClient client. -func NewConfigurationPolicyGroupsClient(subscriptionID string) ConfigurationPolicyGroupsClient { - return NewConfigurationPolicyGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewConfigurationPolicyGroupsClientWithBaseURI creates an instance of the ConfigurationPolicyGroupsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewConfigurationPolicyGroupsClientWithBaseURI(baseURI string, subscriptionID string) ConfigurationPolicyGroupsClient { - return ConfigurationPolicyGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a ConfigurationPolicyGroup if it doesn't exist else updates the existing one. -// Parameters: -// resourceGroupName - the resource group name of the ConfigurationPolicyGroup. -// vpnServerConfigurationName - the name of the VpnServerConfiguration. -// configurationPolicyGroupName - the name of the ConfigurationPolicyGroup. -// vpnServerConfigurationPolicyGroupParameters - parameters supplied to create or update a -// VpnServerConfiguration PolicyGroup. -func (client ConfigurationPolicyGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string, vpnServerConfigurationPolicyGroupParameters VpnServerConfigurationPolicyGroup) (result ConfigurationPolicyGroupsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationPolicyGroupsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, vpnServerConfigurationName, configurationPolicyGroupName, vpnServerConfigurationPolicyGroupParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ConfigurationPolicyGroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string, vpnServerConfigurationPolicyGroupParameters VpnServerConfigurationPolicyGroup) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationPolicyGroupName": autorest.Encode("path", configurationPolicyGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnServerConfigurationName": autorest.Encode("path", vpnServerConfigurationName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - vpnServerConfigurationPolicyGroupParameters.Etag = nil - vpnServerConfigurationPolicyGroupParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}/configurationPolicyGroups/{configurationPolicyGroupName}", pathParameters), - autorest.WithJSON(vpnServerConfigurationPolicyGroupParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ConfigurationPolicyGroupsClient) CreateOrUpdateSender(req *http.Request) (future ConfigurationPolicyGroupsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ConfigurationPolicyGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result VpnServerConfigurationPolicyGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a ConfigurationPolicyGroup. -// Parameters: -// resourceGroupName - the resource group name of the ConfigurationPolicyGroup. -// vpnServerConfigurationName - the name of the VpnServerConfiguration. -// configurationPolicyGroupName - the name of the ConfigurationPolicyGroup. -func (client ConfigurationPolicyGroupsClient) Delete(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string) (result ConfigurationPolicyGroupsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationPolicyGroupsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, vpnServerConfigurationName, configurationPolicyGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ConfigurationPolicyGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationPolicyGroupName": autorest.Encode("path", configurationPolicyGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnServerConfigurationName": autorest.Encode("path", vpnServerConfigurationName), - } - - const APIVersion = "2022-07-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/vpnServerConfigurations/{vpnServerConfigurationName}/configurationPolicyGroups/{configurationPolicyGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ConfigurationPolicyGroupsClient) DeleteSender(req *http.Request) (future ConfigurationPolicyGroupsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ConfigurationPolicyGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a ConfigurationPolicyGroup. -// Parameters: -// resourceGroupName - the resource group name of the VpnServerConfiguration. -// vpnServerConfigurationName - the name of the VpnServerConfiguration. -// configurationPolicyGroupName - the name of the ConfigurationPolicyGroup being retrieved. -func (client ConfigurationPolicyGroupsClient) Get(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string) (result VpnServerConfigurationPolicyGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationPolicyGroupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, vpnServerConfigurationName, configurationPolicyGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsClient", "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.ConfigurationPolicyGroupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ConfigurationPolicyGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, configurationPolicyGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationPolicyGroupName": autorest.Encode("path", configurationPolicyGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnServerConfigurationName": autorest.Encode("path", vpnServerConfigurationName), - } - - const APIVersion = "2022-07-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/vpnServerConfigurations/{vpnServerConfigurationName}/configurationPolicyGroups/{configurationPolicyGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ConfigurationPolicyGroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ConfigurationPolicyGroupsClient) GetResponder(resp *http.Response) (result VpnServerConfigurationPolicyGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByVpnServerConfiguration lists all the configurationPolicyGroups in a resource group for a -// vpnServerConfiguration. -// Parameters: -// resourceGroupName - the resource group name of the VpnServerConfiguration. -// vpnServerConfigurationName - the name of the VpnServerConfiguration. -func (client ConfigurationPolicyGroupsClient) ListByVpnServerConfiguration(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string) (result ListVpnServerConfigurationPolicyGroupsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationPolicyGroupsClient.ListByVpnServerConfiguration") - defer func() { - sc := -1 - if result.lvscpgr.Response.Response != nil { - sc = result.lvscpgr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByVpnServerConfigurationNextResults - req, err := client.ListByVpnServerConfigurationPreparer(ctx, resourceGroupName, vpnServerConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsClient", "ListByVpnServerConfiguration", nil, "Failure preparing request") - return - } - - resp, err := client.ListByVpnServerConfigurationSender(req) - if err != nil { - result.lvscpgr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsClient", "ListByVpnServerConfiguration", resp, "Failure sending request") - return - } - - result.lvscpgr, err = client.ListByVpnServerConfigurationResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsClient", "ListByVpnServerConfiguration", resp, "Failure responding to request") - return - } - if result.lvscpgr.hasNextLink() && result.lvscpgr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByVpnServerConfigurationPreparer prepares the ListByVpnServerConfiguration request. -func (client ConfigurationPolicyGroupsClient) ListByVpnServerConfigurationPreparer(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnServerConfigurationName": autorest.Encode("path", vpnServerConfigurationName), - } - - const APIVersion = "2022-07-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/vpnServerConfigurations/{vpnServerConfigurationName}/configurationPolicyGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByVpnServerConfigurationSender sends the ListByVpnServerConfiguration request. The method will close the -// http.Response Body if it receives an error. -func (client ConfigurationPolicyGroupsClient) ListByVpnServerConfigurationSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByVpnServerConfigurationResponder handles the response to the ListByVpnServerConfiguration request. The method always -// closes the http.Response Body. -func (client ConfigurationPolicyGroupsClient) ListByVpnServerConfigurationResponder(resp *http.Response) (result ListVpnServerConfigurationPolicyGroupsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByVpnServerConfigurationNextResults retrieves the next set of results, if any. -func (client ConfigurationPolicyGroupsClient) listByVpnServerConfigurationNextResults(ctx context.Context, lastResults ListVpnServerConfigurationPolicyGroupsResult) (result ListVpnServerConfigurationPolicyGroupsResult, err error) { - req, err := lastResults.listVpnServerConfigurationPolicyGroupsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsClient", "listByVpnServerConfigurationNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByVpnServerConfigurationSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsClient", "listByVpnServerConfigurationNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByVpnServerConfigurationResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsClient", "listByVpnServerConfigurationNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByVpnServerConfigurationComplete enumerates all values, automatically crossing page boundaries as required. -func (client ConfigurationPolicyGroupsClient) ListByVpnServerConfigurationComplete(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string) (result ListVpnServerConfigurationPolicyGroupsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConfigurationPolicyGroupsClient.ListByVpnServerConfiguration") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByVpnServerConfiguration(ctx, resourceGroupName, vpnServerConfigurationName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/connectionmonitors.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/connectionmonitors.go deleted file mode 100644 index bdd5308976..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/connectionmonitors.go +++ /dev/null @@ -1,701 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ConnectionMonitorsClient is the network Client -type ConnectionMonitorsClient struct { - BaseClient -} - -// NewConnectionMonitorsClient creates an instance of the ConnectionMonitorsClient client. -func NewConnectionMonitorsClient(subscriptionID string) ConnectionMonitorsClient { - return NewConnectionMonitorsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewConnectionMonitorsClientWithBaseURI creates an instance of the ConnectionMonitorsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewConnectionMonitorsClientWithBaseURI(baseURI string, subscriptionID string) ConnectionMonitorsClient { - return ConnectionMonitorsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update a connection monitor. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -// connectionMonitorName - the name of the connection monitor. -// parameters - parameters that define the operation to create a connection monitor. -// migrate - value indicating whether connection monitor V1 should be migrated to V2 format. -func (client ConnectionMonitorsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, parameters ConnectionMonitor, migrate string) (result ConnectionMonitorsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.ConnectionMonitorParameters", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.ConnectionMonitorParameters.Source", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ConnectionMonitorParameters.Source.ResourceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ConnectionMonitorParameters.Source.Port", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ConnectionMonitorParameters.Source.Port", Name: validation.InclusiveMaximum, Rule: int64(65535), Chain: nil}, - {Target: "parameters.ConnectionMonitorParameters.Source.Port", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}, - {Target: "parameters.ConnectionMonitorParameters.Destination", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ConnectionMonitorParameters.Destination.Port", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ConnectionMonitorParameters.Destination.Port", Name: validation.InclusiveMaximum, Rule: int64(65535), Chain: nil}, - {Target: "parameters.ConnectionMonitorParameters.Destination.Port", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}, - {Target: "parameters.ConnectionMonitorParameters.MonitoringIntervalInSeconds", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ConnectionMonitorParameters.MonitoringIntervalInSeconds", Name: validation.InclusiveMaximum, Rule: int64(1800), Chain: nil}, - {Target: "parameters.ConnectionMonitorParameters.MonitoringIntervalInSeconds", Name: validation.InclusiveMinimum, Rule: int64(30), Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.ConnectionMonitorsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName, parameters, migrate) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ConnectionMonitorsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, parameters ConnectionMonitor, migrate string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionMonitorName": autorest.Encode("path", connectionMonitorName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(migrate) > 0 { - queryParameters["migrate"] = autorest.Encode("query", migrate) - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) CreateOrUpdateSender(req *http.Request) (future ConnectionMonitorsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) CreateOrUpdateResponder(resp *http.Response) (result ConnectionMonitorResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified connection monitor. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -// connectionMonitorName - the name of the connection monitor. -func (client ConnectionMonitorsClient) Delete(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ConnectionMonitorsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionMonitorName": autorest.Encode("path", connectionMonitorName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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}/connectionMonitors/{connectionMonitorName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) DeleteSender(req *http.Request) (future ConnectionMonitorsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a connection monitor by name. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -// connectionMonitorName - the name of the connection monitor. -func (client ConnectionMonitorsClient) Get(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "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.ConnectionMonitorsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ConnectionMonitorsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionMonitorName": autorest.Encode("path", connectionMonitorName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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}/connectionMonitors/{connectionMonitorName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) GetResponder(resp *http.Response) (result ConnectionMonitorResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all connection monitors for the specified Network Watcher. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -func (client ConnectionMonitorsClient) List(ctx context.Context, resourceGroupName string, networkWatcherName string) (result ConnectionMonitorListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, networkWatcherName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "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.ConnectionMonitorsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ConnectionMonitorsClient) ListPreparer(ctx context.Context, 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 = "2022-07-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}/connectionMonitors", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) ListResponder(resp *http.Response) (result ConnectionMonitorListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Query query a snapshot of the most recent connection states. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -// connectionMonitorName - the name given to the connection monitor. -func (client ConnectionMonitorsClient) Query(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorsQueryFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.Query") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.QueryPreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Query", nil, "Failure preparing request") - return - } - - result, err = client.QuerySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Query", result.Response(), "Failure sending request") - return - } - - return -} - -// QueryPreparer prepares the Query request. -func (client ConnectionMonitorsClient) QueryPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionMonitorName": autorest.Encode("path", connectionMonitorName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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}/connectionMonitors/{connectionMonitorName}/query", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// QuerySender sends the Query request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) QuerySender(req *http.Request) (future ConnectionMonitorsQueryFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// QueryResponder handles the response to the Query request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) QueryResponder(resp *http.Response) (result ConnectionMonitorQueryResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Start starts the specified connection monitor. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -// connectionMonitorName - the name of the connection monitor. -func (client ConnectionMonitorsClient) Start(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorsStartFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.Start") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Start", nil, "Failure preparing request") - return - } - - result, err = client.StartSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Start", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPreparer prepares the Start request. -func (client ConnectionMonitorsClient) StartPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionMonitorName": autorest.Encode("path", connectionMonitorName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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}/connectionMonitors/{connectionMonitorName}/start", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartSender sends the Start request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) StartSender(req *http.Request) (future ConnectionMonitorsStartFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartResponder handles the response to the Start request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Stop stops the specified connection monitor. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -// connectionMonitorName - the name of the connection monitor. -func (client ConnectionMonitorsClient) Stop(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (result ConnectionMonitorsStopFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.Stop") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Stop", nil, "Failure preparing request") - return - } - - result, err = client.StopSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "Stop", result.Response(), "Failure sending request") - return - } - - return -} - -// StopPreparer prepares the Stop request. -func (client ConnectionMonitorsClient) StopPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionMonitorName": autorest.Encode("path", connectionMonitorName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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}/connectionMonitors/{connectionMonitorName}/stop", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StopSender sends the Stop request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) StopSender(req *http.Request) (future ConnectionMonitorsStopFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StopResponder handles the response to the Stop request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// UpdateTags update tags of the specified connection monitor. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// connectionMonitorName - the name of the connection monitor. -// parameters - parameters supplied to update connection monitor tags. -func (client ConnectionMonitorsClient) UpdateTags(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, parameters TagsObject) (result ConnectionMonitorResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectionMonitorsClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, networkWatcherName, connectionMonitorName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ConnectionMonitorsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, connectionMonitorName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionMonitorName": autorest.Encode("path", connectionMonitorName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectionMonitorsClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ConnectionMonitorsClient) UpdateTagsResponder(resp *http.Response) (result ConnectionMonitorResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/connectivityconfigurations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/connectivityconfigurations.go deleted file mode 100644 index c5243c646b..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/connectivityconfigurations.go +++ /dev/null @@ -1,426 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ConnectivityConfigurationsClient is the network Client -type ConnectivityConfigurationsClient struct { - BaseClient -} - -// NewConnectivityConfigurationsClient creates an instance of the ConnectivityConfigurationsClient client. -func NewConnectivityConfigurationsClient(subscriptionID string) ConnectivityConfigurationsClient { - return NewConnectivityConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewConnectivityConfigurationsClientWithBaseURI creates an instance of the ConnectivityConfigurationsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewConnectivityConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) ConnectivityConfigurationsClient { - return ConnectivityConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates/Updates a new network manager connectivity configuration -// Parameters: -// connectivityConfiguration - parameters supplied to create/update a network manager connectivity -// configuration -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager connectivity configuration. -func (client ConnectivityConfigurationsClient) CreateOrUpdate(ctx context.Context, connectivityConfiguration ConnectivityConfiguration, resourceGroupName string, networkManagerName string, configurationName string) (result ConnectivityConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectivityConfigurationsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: connectivityConfiguration, - Constraints: []validation.Constraint{{Target: "connectivityConfiguration.ConnectivityConfigurationProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "connectivityConfiguration.ConnectivityConfigurationProperties.AppliesToGroups", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { - return result, validation.NewError("network.ConnectivityConfigurationsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, connectivityConfiguration, resourceGroupName, networkManagerName, configurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectivityConfigurationsClient", "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.ConnectivityConfigurationsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectivityConfigurationsClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ConnectivityConfigurationsClient) CreateOrUpdatePreparer(ctx context.Context, connectivityConfiguration ConnectivityConfiguration, resourceGroupName string, networkManagerName string, configurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - connectivityConfiguration.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/connectivityConfigurations/{configurationName}", pathParameters), - autorest.WithJSON(connectivityConfiguration), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectivityConfigurationsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ConnectivityConfigurationsClient) CreateOrUpdateResponder(resp *http.Response) (result ConnectivityConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a network manager connectivity configuration, specified by the resource group, network manager name, -// and connectivity configuration name -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager connectivity configuration. -// force - deletes the resource even if it is part of a deployed configuration. If the configuration has been -// deployed, the service will do a cleanup deployment in the background, prior to the delete. -func (client ConnectivityConfigurationsClient) Delete(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, force *bool) (result ConnectivityConfigurationsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectivityConfigurationsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkManagerName, configurationName, force) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectivityConfigurationsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectivityConfigurationsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ConnectivityConfigurationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, force *bool) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if force != nil { - queryParameters["force"] = autorest.Encode("query", *force) - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/connectivityConfigurations/{configurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectivityConfigurationsClient) DeleteSender(req *http.Request) (future ConnectivityConfigurationsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ConnectivityConfigurationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a Network Connectivity Configuration, specified by the resource group, network manager name, and -// connectivity Configuration name -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager connectivity configuration. -func (client ConnectivityConfigurationsClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string) (result ConnectivityConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectivityConfigurationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkManagerName, configurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectivityConfigurationsClient", "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.ConnectivityConfigurationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectivityConfigurationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ConnectivityConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkManagers/{networkManagerName}/connectivityConfigurations/{configurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectivityConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ConnectivityConfigurationsClient) GetResponder(resp *http.Response) (result ConnectivityConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the network manager connectivity configuration in a specified network manager. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -// skipToken - skipToken is only used if a previous operation returned a partial result. If a previous response -// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that -// specifies a starting point to use for subsequent calls. -func (client ConnectivityConfigurationsClient) List(ctx context.Context, resourceGroupName string, networkManagerName string, top *int32, skipToken string) (result ConnectivityConfigurationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectivityConfigurationsClient.List") - defer func() { - sc := -1 - if result.cclr.Response.Response != nil { - sc = result.cclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.ConnectivityConfigurationsClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkManagerName, top, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectivityConfigurationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.cclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ConnectivityConfigurationsClient", "List", resp, "Failure sending request") - return - } - - result.cclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectivityConfigurationsClient", "List", resp, "Failure responding to request") - return - } - if result.cclr.hasNextLink() && result.cclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ConnectivityConfigurationsClient) ListPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, top *int32, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(skipToken) > 0 { - queryParameters["$skipToken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/connectivityConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ConnectivityConfigurationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ConnectivityConfigurationsClient) ListResponder(resp *http.Response) (result ConnectivityConfigurationListResult, err error) { - err = autorest.Respond( - resp, - 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 ConnectivityConfigurationsClient) listNextResults(ctx context.Context, lastResults ConnectivityConfigurationListResult) (result ConnectivityConfigurationListResult, err error) { - req, err := lastResults.connectivityConfigurationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ConnectivityConfigurationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ConnectivityConfigurationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectivityConfigurationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ConnectivityConfigurationsClient) ListComplete(ctx context.Context, resourceGroupName string, networkManagerName string, top *int32, skipToken string) (result ConnectivityConfigurationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectivityConfigurationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkManagerName, top, skipToken) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/customipprefixes.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/customipprefixes.go deleted file mode 100644 index 9667eff635..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/customipprefixes.go +++ /dev/null @@ -1,581 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// CustomIPPrefixesClient is the network Client -type CustomIPPrefixesClient struct { - BaseClient -} - -// NewCustomIPPrefixesClient creates an instance of the CustomIPPrefixesClient client. -func NewCustomIPPrefixesClient(subscriptionID string) CustomIPPrefixesClient { - return NewCustomIPPrefixesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewCustomIPPrefixesClientWithBaseURI creates an instance of the CustomIPPrefixesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewCustomIPPrefixesClientWithBaseURI(baseURI string, subscriptionID string) CustomIPPrefixesClient { - return CustomIPPrefixesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a custom IP prefix. -// Parameters: -// resourceGroupName - the name of the resource group. -// customIPPrefixName - the name of the custom IP prefix. -// parameters - parameters supplied to the create or update custom IP prefix operation. -func (client CustomIPPrefixesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, customIPPrefixName string, parameters CustomIPPrefix) (result CustomIPPrefixesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomIPPrefixesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, customIPPrefixName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client CustomIPPrefixesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, customIPPrefixName string, parameters CustomIPPrefix) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "customIpPrefixName": autorest.Encode("path", customIPPrefixName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/customIpPrefixes/{customIpPrefixName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client CustomIPPrefixesClient) CreateOrUpdateSender(req *http.Request) (future CustomIPPrefixesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client CustomIPPrefixesClient) CreateOrUpdateResponder(resp *http.Response) (result CustomIPPrefix, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified custom IP prefix. -// Parameters: -// resourceGroupName - the name of the resource group. -// customIPPrefixName - the name of the CustomIpPrefix. -func (client CustomIPPrefixesClient) Delete(ctx context.Context, resourceGroupName string, customIPPrefixName string) (result CustomIPPrefixesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomIPPrefixesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, customIPPrefixName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client CustomIPPrefixesClient) DeletePreparer(ctx context.Context, resourceGroupName string, customIPPrefixName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "customIpPrefixName": autorest.Encode("path", customIPPrefixName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/customIpPrefixes/{customIpPrefixName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client CustomIPPrefixesClient) DeleteSender(req *http.Request) (future CustomIPPrefixesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client CustomIPPrefixesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified custom IP prefix in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// customIPPrefixName - the name of the custom IP prefix. -// expand - expands referenced resources. -func (client CustomIPPrefixesClient) Get(ctx context.Context, resourceGroupName string, customIPPrefixName string, expand string) (result CustomIPPrefix, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomIPPrefixesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, customIPPrefixName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "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.CustomIPPrefixesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client CustomIPPrefixesClient) GetPreparer(ctx context.Context, resourceGroupName string, customIPPrefixName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "customIpPrefixName": autorest.Encode("path", customIPPrefixName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/customIpPrefixes/{customIpPrefixName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client CustomIPPrefixesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client CustomIPPrefixesClient) GetResponder(resp *http.Response) (result CustomIPPrefix, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all custom IP prefixes in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client CustomIPPrefixesClient) List(ctx context.Context, resourceGroupName string) (result CustomIPPrefixListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomIPPrefixesClient.List") - defer func() { - sc := -1 - if result.ciplr.Response.Response != nil { - sc = result.ciplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ciplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "List", resp, "Failure sending request") - return - } - - result.ciplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "List", resp, "Failure responding to request") - return - } - if result.ciplr.hasNextLink() && result.ciplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client CustomIPPrefixesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/customIpPrefixes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client CustomIPPrefixesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client CustomIPPrefixesClient) ListResponder(resp *http.Response) (result CustomIPPrefixListResult, err error) { - err = autorest.Respond( - resp, - 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 CustomIPPrefixesClient) listNextResults(ctx context.Context, lastResults CustomIPPrefixListResult) (result CustomIPPrefixListResult, err error) { - req, err := lastResults.customIPPrefixListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client CustomIPPrefixesClient) ListComplete(ctx context.Context, resourceGroupName string) (result CustomIPPrefixListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomIPPrefixesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the custom IP prefixes in a subscription. -func (client CustomIPPrefixesClient) ListAll(ctx context.Context) (result CustomIPPrefixListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomIPPrefixesClient.ListAll") - defer func() { - sc := -1 - if result.ciplr.Response.Response != nil { - sc = result.ciplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.ciplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "ListAll", resp, "Failure sending request") - return - } - - result.ciplr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.ciplr.hasNextLink() && result.ciplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client CustomIPPrefixesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/customIpPrefixes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client CustomIPPrefixesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client CustomIPPrefixesClient) ListAllResponder(resp *http.Response) (result CustomIPPrefixListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client CustomIPPrefixesClient) listAllNextResults(ctx context.Context, lastResults CustomIPPrefixListResult) (result CustomIPPrefixListResult, err error) { - req, err := lastResults.customIPPrefixListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client CustomIPPrefixesClient) ListAllComplete(ctx context.Context) (result CustomIPPrefixListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomIPPrefixesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// UpdateTags updates custom IP prefix tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// customIPPrefixName - the name of the custom IP prefix. -// parameters - parameters supplied to update custom IP prefix tags. -func (client CustomIPPrefixesClient) UpdateTags(ctx context.Context, resourceGroupName string, customIPPrefixName string, parameters TagsObject) (result CustomIPPrefix, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomIPPrefixesClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, customIPPrefixName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client CustomIPPrefixesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, customIPPrefixName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "customIpPrefixName": autorest.Encode("path", customIPPrefixName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/customIpPrefixes/{customIpPrefixName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client CustomIPPrefixesClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client CustomIPPrefixesClient) UpdateTagsResponder(resp *http.Response) (result CustomIPPrefix, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/ddoscustompolicies.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/ddoscustompolicies.go deleted file mode 100644 index e253f8e979..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/ddoscustompolicies.go +++ /dev/null @@ -1,348 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// DdosCustomPoliciesClient is the network Client -type DdosCustomPoliciesClient struct { - BaseClient -} - -// NewDdosCustomPoliciesClient creates an instance of the DdosCustomPoliciesClient client. -func NewDdosCustomPoliciesClient(subscriptionID string) DdosCustomPoliciesClient { - return NewDdosCustomPoliciesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewDdosCustomPoliciesClientWithBaseURI creates an instance of the DdosCustomPoliciesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewDdosCustomPoliciesClientWithBaseURI(baseURI string, subscriptionID string) DdosCustomPoliciesClient { - return DdosCustomPoliciesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a DDoS custom policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// ddosCustomPolicyName - the name of the DDoS custom policy. -// parameters - parameters supplied to the create or update operation. -func (client DdosCustomPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, parameters DdosCustomPolicy) (result DdosCustomPoliciesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosCustomPoliciesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, ddosCustomPolicyName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosCustomPoliciesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosCustomPoliciesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client DdosCustomPoliciesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, parameters DdosCustomPolicy) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ddosCustomPolicyName": autorest.Encode("path", ddosCustomPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosCustomPolicies/{ddosCustomPolicyName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client DdosCustomPoliciesClient) CreateOrUpdateSender(req *http.Request) (future DdosCustomPoliciesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client DdosCustomPoliciesClient) CreateOrUpdateResponder(resp *http.Response) (result DdosCustomPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified DDoS custom policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// ddosCustomPolicyName - the name of the DDoS custom policy. -func (client DdosCustomPoliciesClient) Delete(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string) (result DdosCustomPoliciesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosCustomPoliciesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, ddosCustomPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosCustomPoliciesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosCustomPoliciesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client DdosCustomPoliciesClient) DeletePreparer(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ddosCustomPolicyName": autorest.Encode("path", ddosCustomPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ddosCustomPolicies/{ddosCustomPolicyName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client DdosCustomPoliciesClient) DeleteSender(req *http.Request) (future DdosCustomPoliciesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client DdosCustomPoliciesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets information about the specified DDoS custom policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// ddosCustomPolicyName - the name of the DDoS custom policy. -func (client DdosCustomPoliciesClient) Get(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string) (result DdosCustomPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosCustomPoliciesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, ddosCustomPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosCustomPoliciesClient", "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.DdosCustomPoliciesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosCustomPoliciesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client DdosCustomPoliciesClient) GetPreparer(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ddosCustomPolicyName": autorest.Encode("path", ddosCustomPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ddosCustomPolicies/{ddosCustomPolicyName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client DdosCustomPoliciesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client DdosCustomPoliciesClient) GetResponder(resp *http.Response) (result DdosCustomPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags update a DDoS custom policy tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// ddosCustomPolicyName - the name of the DDoS custom policy. -// parameters - parameters supplied to update DDoS custom policy resource tags. -func (client DdosCustomPoliciesClient) UpdateTags(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, parameters TagsObject) (result DdosCustomPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosCustomPoliciesClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, ddosCustomPolicyName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosCustomPoliciesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.DdosCustomPoliciesClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosCustomPoliciesClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client DdosCustomPoliciesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, ddosCustomPolicyName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ddosCustomPolicyName": autorest.Encode("path", ddosCustomPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosCustomPolicies/{ddosCustomPolicyName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client DdosCustomPoliciesClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client DdosCustomPoliciesClient) UpdateTagsResponder(resp *http.Response) (result DdosCustomPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/ddosprotectionplans.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/ddosprotectionplans.go deleted file mode 100644 index a73299aebf..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/ddosprotectionplans.go +++ /dev/null @@ -1,580 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// DdosProtectionPlansClient is the network Client -type DdosProtectionPlansClient struct { - BaseClient -} - -// NewDdosProtectionPlansClient creates an instance of the DdosProtectionPlansClient client. -func NewDdosProtectionPlansClient(subscriptionID string) DdosProtectionPlansClient { - return NewDdosProtectionPlansClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewDdosProtectionPlansClientWithBaseURI creates an instance of the DdosProtectionPlansClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewDdosProtectionPlansClientWithBaseURI(baseURI string, subscriptionID string) DdosProtectionPlansClient { - return DdosProtectionPlansClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a DDoS protection plan. -// Parameters: -// resourceGroupName - the name of the resource group. -// ddosProtectionPlanName - the name of the DDoS protection plan. -// parameters - parameters supplied to the create or update operation. -func (client DdosProtectionPlansClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, parameters DdosProtectionPlan) (result DdosProtectionPlansCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, ddosProtectionPlanName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client DdosProtectionPlansClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, parameters DdosProtectionPlan) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ddosProtectionPlanName": autorest.Encode("path", ddosProtectionPlanName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.ID = nil - parameters.Name = nil - parameters.Type = nil - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans/{ddosProtectionPlanName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client DdosProtectionPlansClient) CreateOrUpdateSender(req *http.Request) (future DdosProtectionPlansCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client DdosProtectionPlansClient) CreateOrUpdateResponder(resp *http.Response) (result DdosProtectionPlan, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified DDoS protection plan. -// Parameters: -// resourceGroupName - the name of the resource group. -// ddosProtectionPlanName - the name of the DDoS protection plan. -func (client DdosProtectionPlansClient) Delete(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string) (result DdosProtectionPlansDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, ddosProtectionPlanName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client DdosProtectionPlansClient) DeletePreparer(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ddosProtectionPlanName": autorest.Encode("path", ddosProtectionPlanName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ddosProtectionPlans/{ddosProtectionPlanName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client DdosProtectionPlansClient) DeleteSender(req *http.Request) (future DdosProtectionPlansDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client DdosProtectionPlansClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets information about the specified DDoS protection plan. -// Parameters: -// resourceGroupName - the name of the resource group. -// ddosProtectionPlanName - the name of the DDoS protection plan. -func (client DdosProtectionPlansClient) Get(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string) (result DdosProtectionPlan, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, ddosProtectionPlanName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "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.DdosProtectionPlansClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client DdosProtectionPlansClient) GetPreparer(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ddosProtectionPlanName": autorest.Encode("path", ddosProtectionPlanName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ddosProtectionPlans/{ddosProtectionPlanName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client DdosProtectionPlansClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client DdosProtectionPlansClient) GetResponder(resp *http.Response) (result DdosProtectionPlan, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all DDoS protection plans in a subscription. -func (client DdosProtectionPlansClient) List(ctx context.Context) (result DdosProtectionPlanListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.List") - defer func() { - sc := -1 - if result.dpplr.Response.Response != nil { - sc = result.dpplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.dpplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "List", resp, "Failure sending request") - return - } - - result.dpplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "List", resp, "Failure responding to request") - return - } - if result.dpplr.hasNextLink() && result.dpplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client DdosProtectionPlansClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ddosProtectionPlans", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client DdosProtectionPlansClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client DdosProtectionPlansClient) ListResponder(resp *http.Response) (result DdosProtectionPlanListResult, err error) { - err = autorest.Respond( - resp, - 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 DdosProtectionPlansClient) listNextResults(ctx context.Context, lastResults DdosProtectionPlanListResult) (result DdosProtectionPlanListResult, err error) { - req, err := lastResults.ddosProtectionPlanListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client DdosProtectionPlansClient) ListComplete(ctx context.Context) (result DdosProtectionPlanListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup gets all the DDoS protection plans in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client DdosProtectionPlansClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result DdosProtectionPlanListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.dpplr.Response.Response != nil { - sc = result.dpplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.dpplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.dpplr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.dpplr.hasNextLink() && result.dpplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client DdosProtectionPlansClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ddosProtectionPlans", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client DdosProtectionPlansClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client DdosProtectionPlansClient) ListByResourceGroupResponder(resp *http.Response) (result DdosProtectionPlanListResult, err error) { - err = autorest.Respond( - resp, - 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 DdosProtectionPlansClient) listByResourceGroupNextResults(ctx context.Context, lastResults DdosProtectionPlanListResult) (result DdosProtectionPlanListResult, err error) { - req, err := lastResults.ddosProtectionPlanListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client DdosProtectionPlansClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result DdosProtectionPlanListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags update a DDoS protection plan tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// ddosProtectionPlanName - the name of the DDoS protection plan. -// parameters - parameters supplied to the update DDoS protection plan resource tags. -func (client DdosProtectionPlansClient) UpdateTags(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, parameters TagsObject) (result DdosProtectionPlan, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlansClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, ddosProtectionPlanName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client DdosProtectionPlansClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, ddosProtectionPlanName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ddosProtectionPlanName": autorest.Encode("path", ddosProtectionPlanName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosProtectionPlans/{ddosProtectionPlanName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client DdosProtectionPlansClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client DdosProtectionPlansClient) UpdateTagsResponder(resp *http.Response) (result DdosProtectionPlan, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/defaultsecurityrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/defaultsecurityrules.go deleted file mode 100644 index fa15bacf8d..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/defaultsecurityrules.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// DefaultSecurityRulesClient is the network Client -type DefaultSecurityRulesClient struct { - BaseClient -} - -// NewDefaultSecurityRulesClient creates an instance of the DefaultSecurityRulesClient client. -func NewDefaultSecurityRulesClient(subscriptionID string) DefaultSecurityRulesClient { - return NewDefaultSecurityRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewDefaultSecurityRulesClientWithBaseURI creates an instance of the DefaultSecurityRulesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewDefaultSecurityRulesClientWithBaseURI(baseURI string, subscriptionID string) DefaultSecurityRulesClient { - return DefaultSecurityRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get get the specified default network security rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// defaultSecurityRuleName - the name of the default security rule. -func (client DefaultSecurityRulesClient) Get(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, defaultSecurityRuleName string) (result SecurityRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DefaultSecurityRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkSecurityGroupName, defaultSecurityRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "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.DefaultSecurityRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client DefaultSecurityRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, defaultSecurityRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "defaultSecurityRuleName": autorest.Encode("path", defaultSecurityRuleName), - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules/{defaultSecurityRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client DefaultSecurityRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client DefaultSecurityRulesClient) GetResponder(resp *http.Response) (result SecurityRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all default security rules in a network security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -func (client DefaultSecurityRulesClient) List(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DefaultSecurityRulesClient.List") - defer func() { - sc := -1 - if result.srlr.Response.Response != nil { - sc = result.srlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkSecurityGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.srlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure sending request") - return - } - - result.srlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "List", resp, "Failure responding to request") - return - } - if result.srlr.hasNextLink() && result.srlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client DefaultSecurityRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client DefaultSecurityRulesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client DefaultSecurityRulesClient) ListResponder(resp *http.Response) (result SecurityRuleListResult, err error) { - err = autorest.Respond( - resp, - 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 DefaultSecurityRulesClient) listNextResults(ctx context.Context, lastResults SecurityRuleListResult) (result SecurityRuleListResult, err error) { - req, err := lastResults.securityRuleListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DefaultSecurityRulesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client DefaultSecurityRulesClient) ListComplete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DefaultSecurityRulesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkSecurityGroupName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/dscpconfiguration.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/dscpconfiguration.go deleted file mode 100644 index e0c2f52fe9..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/dscpconfiguration.go +++ /dev/null @@ -1,498 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// DscpConfigurationClient is the network Client -type DscpConfigurationClient struct { - BaseClient -} - -// NewDscpConfigurationClient creates an instance of the DscpConfigurationClient client. -func NewDscpConfigurationClient(subscriptionID string) DscpConfigurationClient { - return NewDscpConfigurationClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewDscpConfigurationClientWithBaseURI creates an instance of the DscpConfigurationClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewDscpConfigurationClientWithBaseURI(baseURI string, subscriptionID string) DscpConfigurationClient { - return DscpConfigurationClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a DSCP Configuration. -// Parameters: -// resourceGroupName - the name of the resource group. -// dscpConfigurationName - the name of the resource. -// parameters - parameters supplied to the create or update dscp configuration operation. -func (client DscpConfigurationClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, dscpConfigurationName string, parameters DscpConfiguration) (result DscpConfigurationCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DscpConfigurationClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, dscpConfigurationName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client DscpConfigurationClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, dscpConfigurationName string, parameters DscpConfiguration) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "dscpConfigurationName": autorest.Encode("path", dscpConfigurationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dscpConfigurations/{dscpConfigurationName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client DscpConfigurationClient) CreateOrUpdateSender(req *http.Request) (future DscpConfigurationCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client DscpConfigurationClient) CreateOrUpdateResponder(resp *http.Response) (result DscpConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a DSCP Configuration. -// Parameters: -// resourceGroupName - the name of the resource group. -// dscpConfigurationName - the name of the resource. -func (client DscpConfigurationClient) Delete(ctx context.Context, resourceGroupName string, dscpConfigurationName string) (result DscpConfigurationDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DscpConfigurationClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, dscpConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client DscpConfigurationClient) DeletePreparer(ctx context.Context, resourceGroupName string, dscpConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "dscpConfigurationName": autorest.Encode("path", dscpConfigurationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/dscpConfigurations/{dscpConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client DscpConfigurationClient) DeleteSender(req *http.Request) (future DscpConfigurationDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client DscpConfigurationClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a DSCP Configuration. -// Parameters: -// resourceGroupName - the name of the resource group. -// dscpConfigurationName - the name of the resource. -func (client DscpConfigurationClient) Get(ctx context.Context, resourceGroupName string, dscpConfigurationName string) (result DscpConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DscpConfigurationClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, dscpConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "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.DscpConfigurationClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client DscpConfigurationClient) GetPreparer(ctx context.Context, resourceGroupName string, dscpConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "dscpConfigurationName": autorest.Encode("path", dscpConfigurationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/dscpConfigurations/{dscpConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client DscpConfigurationClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client DscpConfigurationClient) GetResponder(resp *http.Response) (result DscpConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets a DSCP Configuration. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client DscpConfigurationClient) List(ctx context.Context, resourceGroupName string) (result DscpConfigurationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DscpConfigurationClient.List") - defer func() { - sc := -1 - if result.dclr.Response.Response != nil { - sc = result.dclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.dclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "List", resp, "Failure sending request") - return - } - - result.dclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "List", resp, "Failure responding to request") - return - } - if result.dclr.hasNextLink() && result.dclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client DscpConfigurationClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/dscpConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client DscpConfigurationClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client DscpConfigurationClient) ListResponder(resp *http.Response) (result DscpConfigurationListResult, err error) { - err = autorest.Respond( - resp, - 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 DscpConfigurationClient) listNextResults(ctx context.Context, lastResults DscpConfigurationListResult) (result DscpConfigurationListResult, err error) { - req, err := lastResults.dscpConfigurationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client DscpConfigurationClient) ListComplete(ctx context.Context, resourceGroupName string) (result DscpConfigurationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DscpConfigurationClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all dscp configurations in a subscription. -func (client DscpConfigurationClient) ListAll(ctx context.Context) (result DscpConfigurationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DscpConfigurationClient.ListAll") - defer func() { - sc := -1 - if result.dclr.Response.Response != nil { - sc = result.dclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.dclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "ListAll", resp, "Failure sending request") - return - } - - result.dclr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "ListAll", resp, "Failure responding to request") - return - } - if result.dclr.hasNextLink() && result.dclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client DscpConfigurationClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/dscpConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client DscpConfigurationClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client DscpConfigurationClient) ListAllResponder(resp *http.Response) (result DscpConfigurationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client DscpConfigurationClient) listAllNextResults(ctx context.Context, lastResults DscpConfigurationListResult) (result DscpConfigurationListResult, err error) { - req, err := lastResults.dscpConfigurationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client DscpConfigurationClient) ListAllComplete(ctx context.Context) (result DscpConfigurationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DscpConfigurationClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/enums.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/enums.go deleted file mode 100644 index f4ea93ba33..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/enums.go +++ /dev/null @@ -1,3703 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// Access enumerates the values for access. -type Access string - -const ( - // Allow ... - Allow Access = "Allow" - // Deny ... - Deny Access = "Deny" -) - -// PossibleAccessValues returns an array of possible values for the Access const type. -func PossibleAccessValues() []Access { - return []Access{Allow, Deny} -} - -// ActionType enumerates the values for action type. -type ActionType string - -const ( - // ActionTypeAllow ... - ActionTypeAllow ActionType = "Allow" - // ActionTypeAnomalyScoring ... - ActionTypeAnomalyScoring ActionType = "AnomalyScoring" - // ActionTypeBlock ... - ActionTypeBlock ActionType = "Block" - // ActionTypeLog ... - ActionTypeLog ActionType = "Log" -) - -// PossibleActionTypeValues returns an array of possible values for the ActionType const type. -func PossibleActionTypeValues() []ActionType { - return []ActionType{ActionTypeAllow, ActionTypeAnomalyScoring, ActionTypeBlock, ActionTypeLog} -} - -// AddressPrefixType enumerates the values for address prefix type. -type AddressPrefixType string - -const ( - // IPPrefix ... - IPPrefix AddressPrefixType = "IPPrefix" - // ServiceTag ... - ServiceTag AddressPrefixType = "ServiceTag" -) - -// PossibleAddressPrefixTypeValues returns an array of possible values for the AddressPrefixType const type. -func PossibleAddressPrefixTypeValues() []AddressPrefixType { - return []AddressPrefixType{IPPrefix, ServiceTag} -} - -// ApplicationGatewayBackendHealthServerHealth enumerates the values for application gateway backend health -// server health. -type ApplicationGatewayBackendHealthServerHealth string - -const ( - // Down ... - Down ApplicationGatewayBackendHealthServerHealth = "Down" - // Draining ... - Draining ApplicationGatewayBackendHealthServerHealth = "Draining" - // Partial ... - Partial ApplicationGatewayBackendHealthServerHealth = "Partial" - // Unknown ... - Unknown ApplicationGatewayBackendHealthServerHealth = "Unknown" - // Up ... - Up ApplicationGatewayBackendHealthServerHealth = "Up" -) - -// PossibleApplicationGatewayBackendHealthServerHealthValues returns an array of possible values for the ApplicationGatewayBackendHealthServerHealth const type. -func PossibleApplicationGatewayBackendHealthServerHealthValues() []ApplicationGatewayBackendHealthServerHealth { - return []ApplicationGatewayBackendHealthServerHealth{Down, Draining, Partial, Unknown, Up} -} - -// ApplicationGatewayClientRevocationOptions enumerates the values for application gateway client revocation -// options. -type ApplicationGatewayClientRevocationOptions string - -const ( - // None ... - None ApplicationGatewayClientRevocationOptions = "None" - // OCSP ... - OCSP ApplicationGatewayClientRevocationOptions = "OCSP" -) - -// PossibleApplicationGatewayClientRevocationOptionsValues returns an array of possible values for the ApplicationGatewayClientRevocationOptions const type. -func PossibleApplicationGatewayClientRevocationOptionsValues() []ApplicationGatewayClientRevocationOptions { - return []ApplicationGatewayClientRevocationOptions{None, OCSP} -} - -// ApplicationGatewayCookieBasedAffinity enumerates the values for application gateway cookie based affinity. -type ApplicationGatewayCookieBasedAffinity string - -const ( - // Disabled ... - Disabled ApplicationGatewayCookieBasedAffinity = "Disabled" - // Enabled ... - Enabled ApplicationGatewayCookieBasedAffinity = "Enabled" -) - -// PossibleApplicationGatewayCookieBasedAffinityValues returns an array of possible values for the ApplicationGatewayCookieBasedAffinity const type. -func PossibleApplicationGatewayCookieBasedAffinityValues() []ApplicationGatewayCookieBasedAffinity { - return []ApplicationGatewayCookieBasedAffinity{Disabled, Enabled} -} - -// ApplicationGatewayCustomErrorStatusCode enumerates the values for application gateway custom error status -// code. -type ApplicationGatewayCustomErrorStatusCode string - -const ( - // HTTPStatus403 ... - HTTPStatus403 ApplicationGatewayCustomErrorStatusCode = "HttpStatus403" - // HTTPStatus502 ... - HTTPStatus502 ApplicationGatewayCustomErrorStatusCode = "HttpStatus502" -) - -// PossibleApplicationGatewayCustomErrorStatusCodeValues returns an array of possible values for the ApplicationGatewayCustomErrorStatusCode const type. -func PossibleApplicationGatewayCustomErrorStatusCodeValues() []ApplicationGatewayCustomErrorStatusCode { - return []ApplicationGatewayCustomErrorStatusCode{HTTPStatus403, HTTPStatus502} -} - -// ApplicationGatewayFirewallMode enumerates the values for application gateway firewall mode. -type ApplicationGatewayFirewallMode string - -const ( - // Detection ... - Detection ApplicationGatewayFirewallMode = "Detection" - // Prevention ... - Prevention ApplicationGatewayFirewallMode = "Prevention" -) - -// PossibleApplicationGatewayFirewallModeValues returns an array of possible values for the ApplicationGatewayFirewallMode const type. -func PossibleApplicationGatewayFirewallModeValues() []ApplicationGatewayFirewallMode { - return []ApplicationGatewayFirewallMode{Detection, Prevention} -} - -// ApplicationGatewayLoadDistributionAlgorithm enumerates the values for application gateway load distribution -// algorithm. -type ApplicationGatewayLoadDistributionAlgorithm string - -const ( - // IPHash ... - IPHash ApplicationGatewayLoadDistributionAlgorithm = "IpHash" - // LeastConnections ... - LeastConnections ApplicationGatewayLoadDistributionAlgorithm = "LeastConnections" - // RoundRobin ... - RoundRobin ApplicationGatewayLoadDistributionAlgorithm = "RoundRobin" -) - -// PossibleApplicationGatewayLoadDistributionAlgorithmValues returns an array of possible values for the ApplicationGatewayLoadDistributionAlgorithm const type. -func PossibleApplicationGatewayLoadDistributionAlgorithmValues() []ApplicationGatewayLoadDistributionAlgorithm { - return []ApplicationGatewayLoadDistributionAlgorithm{IPHash, LeastConnections, RoundRobin} -} - -// ApplicationGatewayOperationalState enumerates the values for application gateway operational state. -type ApplicationGatewayOperationalState string - -const ( - // Running ... - Running ApplicationGatewayOperationalState = "Running" - // Starting ... - Starting ApplicationGatewayOperationalState = "Starting" - // Stopped ... - Stopped ApplicationGatewayOperationalState = "Stopped" - // Stopping ... - Stopping ApplicationGatewayOperationalState = "Stopping" -) - -// PossibleApplicationGatewayOperationalStateValues returns an array of possible values for the ApplicationGatewayOperationalState const type. -func PossibleApplicationGatewayOperationalStateValues() []ApplicationGatewayOperationalState { - return []ApplicationGatewayOperationalState{Running, Starting, Stopped, Stopping} -} - -// ApplicationGatewayProtocol enumerates the values for application gateway protocol. -type ApplicationGatewayProtocol string - -const ( - // HTTP ... - HTTP ApplicationGatewayProtocol = "Http" - // HTTPS ... - HTTPS ApplicationGatewayProtocol = "Https" - // TCP ... - TCP ApplicationGatewayProtocol = "Tcp" - // TLS ... - TLS ApplicationGatewayProtocol = "Tls" -) - -// PossibleApplicationGatewayProtocolValues returns an array of possible values for the ApplicationGatewayProtocol const type. -func PossibleApplicationGatewayProtocolValues() []ApplicationGatewayProtocol { - return []ApplicationGatewayProtocol{HTTP, HTTPS, TCP, TLS} -} - -// ApplicationGatewayRedirectType enumerates the values for application gateway redirect type. -type ApplicationGatewayRedirectType string - -const ( - // Found ... - Found ApplicationGatewayRedirectType = "Found" - // Permanent ... - Permanent ApplicationGatewayRedirectType = "Permanent" - // SeeOther ... - SeeOther ApplicationGatewayRedirectType = "SeeOther" - // Temporary ... - Temporary ApplicationGatewayRedirectType = "Temporary" -) - -// PossibleApplicationGatewayRedirectTypeValues returns an array of possible values for the ApplicationGatewayRedirectType const type. -func PossibleApplicationGatewayRedirectTypeValues() []ApplicationGatewayRedirectType { - return []ApplicationGatewayRedirectType{Found, Permanent, SeeOther, Temporary} -} - -// ApplicationGatewayRequestRoutingRuleType enumerates the values for application gateway request routing rule -// type. -type ApplicationGatewayRequestRoutingRuleType string - -const ( - // Basic ... - Basic ApplicationGatewayRequestRoutingRuleType = "Basic" - // PathBasedRouting ... - PathBasedRouting ApplicationGatewayRequestRoutingRuleType = "PathBasedRouting" -) - -// PossibleApplicationGatewayRequestRoutingRuleTypeValues returns an array of possible values for the ApplicationGatewayRequestRoutingRuleType const type. -func PossibleApplicationGatewayRequestRoutingRuleTypeValues() []ApplicationGatewayRequestRoutingRuleType { - return []ApplicationGatewayRequestRoutingRuleType{Basic, PathBasedRouting} -} - -// ApplicationGatewayRuleSetStatusOptions enumerates the values for application gateway rule set status -// options. -type ApplicationGatewayRuleSetStatusOptions string - -const ( - // Deprecated ... - Deprecated ApplicationGatewayRuleSetStatusOptions = "Deprecated" - // GA ... - GA ApplicationGatewayRuleSetStatusOptions = "GA" - // Preview ... - Preview ApplicationGatewayRuleSetStatusOptions = "Preview" - // Supported ... - Supported ApplicationGatewayRuleSetStatusOptions = "Supported" -) - -// PossibleApplicationGatewayRuleSetStatusOptionsValues returns an array of possible values for the ApplicationGatewayRuleSetStatusOptions const type. -func PossibleApplicationGatewayRuleSetStatusOptionsValues() []ApplicationGatewayRuleSetStatusOptions { - return []ApplicationGatewayRuleSetStatusOptions{Deprecated, GA, Preview, Supported} -} - -// ApplicationGatewaySkuName enumerates the values for application gateway sku name. -type ApplicationGatewaySkuName string - -const ( - // StandardBasic ... - StandardBasic ApplicationGatewaySkuName = "Standard_Basic" - // StandardLarge ... - StandardLarge ApplicationGatewaySkuName = "Standard_Large" - // StandardMedium ... - StandardMedium ApplicationGatewaySkuName = "Standard_Medium" - // StandardSmall ... - StandardSmall ApplicationGatewaySkuName = "Standard_Small" - // StandardV2 ... - StandardV2 ApplicationGatewaySkuName = "Standard_v2" - // WAFLarge ... - WAFLarge ApplicationGatewaySkuName = "WAF_Large" - // WAFMedium ... - WAFMedium ApplicationGatewaySkuName = "WAF_Medium" - // WAFV2 ... - WAFV2 ApplicationGatewaySkuName = "WAF_v2" -) - -// PossibleApplicationGatewaySkuNameValues returns an array of possible values for the ApplicationGatewaySkuName const type. -func PossibleApplicationGatewaySkuNameValues() []ApplicationGatewaySkuName { - return []ApplicationGatewaySkuName{StandardBasic, StandardLarge, StandardMedium, StandardSmall, StandardV2, WAFLarge, WAFMedium, WAFV2} -} - -// ApplicationGatewaySslCipherSuite enumerates the values for application gateway ssl cipher suite. -type ApplicationGatewaySslCipherSuite string - -const ( - // TLSDHEDSSWITH3DESEDECBCSHA ... - TLSDHEDSSWITH3DESEDECBCSHA ApplicationGatewaySslCipherSuite = "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA" - // TLSDHEDSSWITHAES128CBCSHA ... - TLSDHEDSSWITHAES128CBCSHA ApplicationGatewaySslCipherSuite = "TLS_DHE_DSS_WITH_AES_128_CBC_SHA" - // TLSDHEDSSWITHAES128CBCSHA256 ... - TLSDHEDSSWITHAES128CBCSHA256 ApplicationGatewaySslCipherSuite = "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256" - // TLSDHEDSSWITHAES256CBCSHA ... - TLSDHEDSSWITHAES256CBCSHA ApplicationGatewaySslCipherSuite = "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" - // TLSDHEDSSWITHAES256CBCSHA256 ... - TLSDHEDSSWITHAES256CBCSHA256 ApplicationGatewaySslCipherSuite = "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" - // TLSDHERSAWITHAES128CBCSHA ... - TLSDHERSAWITHAES128CBCSHA ApplicationGatewaySslCipherSuite = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" - // TLSDHERSAWITHAES128GCMSHA256 ... - TLSDHERSAWITHAES128GCMSHA256 ApplicationGatewaySslCipherSuite = "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256" - // TLSDHERSAWITHAES256CBCSHA ... - TLSDHERSAWITHAES256CBCSHA ApplicationGatewaySslCipherSuite = "TLS_DHE_RSA_WITH_AES_256_CBC_SHA" - // TLSDHERSAWITHAES256GCMSHA384 ... - TLSDHERSAWITHAES256GCMSHA384 ApplicationGatewaySslCipherSuite = "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" - // TLSECDHEECDSAWITHAES128CBCSHA ... - TLSECDHEECDSAWITHAES128CBCSHA ApplicationGatewaySslCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" - // TLSECDHEECDSAWITHAES128CBCSHA256 ... - TLSECDHEECDSAWITHAES128CBCSHA256 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256" - // TLSECDHEECDSAWITHAES128GCMSHA256 ... - TLSECDHEECDSAWITHAES128GCMSHA256 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" - // TLSECDHEECDSAWITHAES256CBCSHA ... - TLSECDHEECDSAWITHAES256CBCSHA ApplicationGatewaySslCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA" - // TLSECDHEECDSAWITHAES256CBCSHA384 ... - TLSECDHEECDSAWITHAES256CBCSHA384 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384" - // TLSECDHEECDSAWITHAES256GCMSHA384 ... - TLSECDHEECDSAWITHAES256GCMSHA384 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" - // TLSECDHERSAWITHAES128CBCSHA ... - TLSECDHERSAWITHAES128CBCSHA ApplicationGatewaySslCipherSuite = "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA" - // TLSECDHERSAWITHAES128CBCSHA256 ... - TLSECDHERSAWITHAES128CBCSHA256 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" - // TLSECDHERSAWITHAES128GCMSHA256 ... - TLSECDHERSAWITHAES128GCMSHA256 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" - // TLSECDHERSAWITHAES256CBCSHA ... - TLSECDHERSAWITHAES256CBCSHA ApplicationGatewaySslCipherSuite = "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA" - // TLSECDHERSAWITHAES256CBCSHA384 ... - TLSECDHERSAWITHAES256CBCSHA384 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" - // TLSECDHERSAWITHAES256GCMSHA384 ... - TLSECDHERSAWITHAES256GCMSHA384 ApplicationGatewaySslCipherSuite = "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" - // TLSRSAWITH3DESEDECBCSHA ... - TLSRSAWITH3DESEDECBCSHA ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_3DES_EDE_CBC_SHA" - // TLSRSAWITHAES128CBCSHA ... - TLSRSAWITHAES128CBCSHA ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_AES_128_CBC_SHA" - // TLSRSAWITHAES128CBCSHA256 ... - TLSRSAWITHAES128CBCSHA256 ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_AES_128_CBC_SHA256" - // TLSRSAWITHAES128GCMSHA256 ... - TLSRSAWITHAES128GCMSHA256 ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_AES_128_GCM_SHA256" - // TLSRSAWITHAES256CBCSHA ... - TLSRSAWITHAES256CBCSHA ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_AES_256_CBC_SHA" - // TLSRSAWITHAES256CBCSHA256 ... - TLSRSAWITHAES256CBCSHA256 ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_AES_256_CBC_SHA256" - // TLSRSAWITHAES256GCMSHA384 ... - TLSRSAWITHAES256GCMSHA384 ApplicationGatewaySslCipherSuite = "TLS_RSA_WITH_AES_256_GCM_SHA384" -) - -// PossibleApplicationGatewaySslCipherSuiteValues returns an array of possible values for the ApplicationGatewaySslCipherSuite const type. -func PossibleApplicationGatewaySslCipherSuiteValues() []ApplicationGatewaySslCipherSuite { - return []ApplicationGatewaySslCipherSuite{TLSDHEDSSWITH3DESEDECBCSHA, TLSDHEDSSWITHAES128CBCSHA, TLSDHEDSSWITHAES128CBCSHA256, TLSDHEDSSWITHAES256CBCSHA, TLSDHEDSSWITHAES256CBCSHA256, TLSDHERSAWITHAES128CBCSHA, TLSDHERSAWITHAES128GCMSHA256, TLSDHERSAWITHAES256CBCSHA, TLSDHERSAWITHAES256GCMSHA384, TLSECDHEECDSAWITHAES128CBCSHA, TLSECDHEECDSAWITHAES128CBCSHA256, TLSECDHEECDSAWITHAES128GCMSHA256, TLSECDHEECDSAWITHAES256CBCSHA, TLSECDHEECDSAWITHAES256CBCSHA384, TLSECDHEECDSAWITHAES256GCMSHA384, TLSECDHERSAWITHAES128CBCSHA, TLSECDHERSAWITHAES128CBCSHA256, TLSECDHERSAWITHAES128GCMSHA256, TLSECDHERSAWITHAES256CBCSHA, TLSECDHERSAWITHAES256CBCSHA384, TLSECDHERSAWITHAES256GCMSHA384, TLSRSAWITH3DESEDECBCSHA, TLSRSAWITHAES128CBCSHA, TLSRSAWITHAES128CBCSHA256, TLSRSAWITHAES128GCMSHA256, TLSRSAWITHAES256CBCSHA, TLSRSAWITHAES256CBCSHA256, TLSRSAWITHAES256GCMSHA384} -} - -// ApplicationGatewaySslPolicyName enumerates the values for application gateway ssl policy name. -type ApplicationGatewaySslPolicyName string - -const ( - // AppGwSslPolicy20150501 ... - AppGwSslPolicy20150501 ApplicationGatewaySslPolicyName = "AppGwSslPolicy20150501" - // AppGwSslPolicy20170401 ... - AppGwSslPolicy20170401 ApplicationGatewaySslPolicyName = "AppGwSslPolicy20170401" - // AppGwSslPolicy20170401S ... - AppGwSslPolicy20170401S ApplicationGatewaySslPolicyName = "AppGwSslPolicy20170401S" - // AppGwSslPolicy20220101 ... - AppGwSslPolicy20220101 ApplicationGatewaySslPolicyName = "AppGwSslPolicy20220101" - // AppGwSslPolicy20220101S ... - AppGwSslPolicy20220101S ApplicationGatewaySslPolicyName = "AppGwSslPolicy20220101S" -) - -// PossibleApplicationGatewaySslPolicyNameValues returns an array of possible values for the ApplicationGatewaySslPolicyName const type. -func PossibleApplicationGatewaySslPolicyNameValues() []ApplicationGatewaySslPolicyName { - return []ApplicationGatewaySslPolicyName{AppGwSslPolicy20150501, AppGwSslPolicy20170401, AppGwSslPolicy20170401S, AppGwSslPolicy20220101, AppGwSslPolicy20220101S} -} - -// ApplicationGatewaySslPolicyType enumerates the values for application gateway ssl policy type. -type ApplicationGatewaySslPolicyType string - -const ( - // Custom ... - Custom ApplicationGatewaySslPolicyType = "Custom" - // CustomV2 ... - CustomV2 ApplicationGatewaySslPolicyType = "CustomV2" - // Predefined ... - Predefined ApplicationGatewaySslPolicyType = "Predefined" -) - -// PossibleApplicationGatewaySslPolicyTypeValues returns an array of possible values for the ApplicationGatewaySslPolicyType const type. -func PossibleApplicationGatewaySslPolicyTypeValues() []ApplicationGatewaySslPolicyType { - return []ApplicationGatewaySslPolicyType{Custom, CustomV2, Predefined} -} - -// ApplicationGatewaySslProtocol enumerates the values for application gateway ssl protocol. -type ApplicationGatewaySslProtocol string - -const ( - // TLSv10 ... - TLSv10 ApplicationGatewaySslProtocol = "TLSv1_0" - // TLSv11 ... - TLSv11 ApplicationGatewaySslProtocol = "TLSv1_1" - // TLSv12 ... - TLSv12 ApplicationGatewaySslProtocol = "TLSv1_2" - // TLSv13 ... - TLSv13 ApplicationGatewaySslProtocol = "TLSv1_3" -) - -// PossibleApplicationGatewaySslProtocolValues returns an array of possible values for the ApplicationGatewaySslProtocol const type. -func PossibleApplicationGatewaySslProtocolValues() []ApplicationGatewaySslProtocol { - return []ApplicationGatewaySslProtocol{TLSv10, TLSv11, TLSv12, TLSv13} -} - -// ApplicationGatewayTier enumerates the values for application gateway tier. -type ApplicationGatewayTier string - -const ( - // ApplicationGatewayTierStandard ... - ApplicationGatewayTierStandard ApplicationGatewayTier = "Standard" - // ApplicationGatewayTierStandardBasic ... - ApplicationGatewayTierStandardBasic ApplicationGatewayTier = "Standard_Basic" - // ApplicationGatewayTierStandardV2 ... - ApplicationGatewayTierStandardV2 ApplicationGatewayTier = "Standard_v2" - // ApplicationGatewayTierWAF ... - ApplicationGatewayTierWAF ApplicationGatewayTier = "WAF" - // ApplicationGatewayTierWAFV2 ... - ApplicationGatewayTierWAFV2 ApplicationGatewayTier = "WAF_v2" -) - -// PossibleApplicationGatewayTierValues returns an array of possible values for the ApplicationGatewayTier const type. -func PossibleApplicationGatewayTierValues() []ApplicationGatewayTier { - return []ApplicationGatewayTier{ApplicationGatewayTierStandard, ApplicationGatewayTierStandardBasic, ApplicationGatewayTierStandardV2, ApplicationGatewayTierWAF, ApplicationGatewayTierWAFV2} -} - -// ApplicationGatewayTierTypes enumerates the values for application gateway tier types. -type ApplicationGatewayTierTypes string - -const ( - // ApplicationGatewayTierTypesStandard ... - ApplicationGatewayTierTypesStandard ApplicationGatewayTierTypes = "Standard" - // ApplicationGatewayTierTypesStandardV2 ... - ApplicationGatewayTierTypesStandardV2 ApplicationGatewayTierTypes = "Standard_v2" - // ApplicationGatewayTierTypesWAF ... - ApplicationGatewayTierTypesWAF ApplicationGatewayTierTypes = "WAF" - // ApplicationGatewayTierTypesWAFV2 ... - ApplicationGatewayTierTypesWAFV2 ApplicationGatewayTierTypes = "WAF_v2" -) - -// PossibleApplicationGatewayTierTypesValues returns an array of possible values for the ApplicationGatewayTierTypes const type. -func PossibleApplicationGatewayTierTypesValues() []ApplicationGatewayTierTypes { - return []ApplicationGatewayTierTypes{ApplicationGatewayTierTypesStandard, ApplicationGatewayTierTypesStandardV2, ApplicationGatewayTierTypesWAF, ApplicationGatewayTierTypesWAFV2} -} - -// ApplicationGatewayWafRuleActionTypes enumerates the values for application gateway waf rule action types. -type ApplicationGatewayWafRuleActionTypes string - -const ( - // ApplicationGatewayWafRuleActionTypesAllow ... - ApplicationGatewayWafRuleActionTypesAllow ApplicationGatewayWafRuleActionTypes = "Allow" - // ApplicationGatewayWafRuleActionTypesAnomalyScoring ... - ApplicationGatewayWafRuleActionTypesAnomalyScoring ApplicationGatewayWafRuleActionTypes = "AnomalyScoring" - // ApplicationGatewayWafRuleActionTypesBlock ... - ApplicationGatewayWafRuleActionTypesBlock ApplicationGatewayWafRuleActionTypes = "Block" - // ApplicationGatewayWafRuleActionTypesLog ... - ApplicationGatewayWafRuleActionTypesLog ApplicationGatewayWafRuleActionTypes = "Log" - // ApplicationGatewayWafRuleActionTypesNone ... - ApplicationGatewayWafRuleActionTypesNone ApplicationGatewayWafRuleActionTypes = "None" -) - -// PossibleApplicationGatewayWafRuleActionTypesValues returns an array of possible values for the ApplicationGatewayWafRuleActionTypes const type. -func PossibleApplicationGatewayWafRuleActionTypesValues() []ApplicationGatewayWafRuleActionTypes { - return []ApplicationGatewayWafRuleActionTypes{ApplicationGatewayWafRuleActionTypesAllow, ApplicationGatewayWafRuleActionTypesAnomalyScoring, ApplicationGatewayWafRuleActionTypesBlock, ApplicationGatewayWafRuleActionTypesLog, ApplicationGatewayWafRuleActionTypesNone} -} - -// ApplicationGatewayWafRuleStateTypes enumerates the values for application gateway waf rule state types. -type ApplicationGatewayWafRuleStateTypes string - -const ( - // ApplicationGatewayWafRuleStateTypesDisabled ... - ApplicationGatewayWafRuleStateTypesDisabled ApplicationGatewayWafRuleStateTypes = "Disabled" - // ApplicationGatewayWafRuleStateTypesEnabled ... - ApplicationGatewayWafRuleStateTypesEnabled ApplicationGatewayWafRuleStateTypes = "Enabled" -) - -// PossibleApplicationGatewayWafRuleStateTypesValues returns an array of possible values for the ApplicationGatewayWafRuleStateTypes const type. -func PossibleApplicationGatewayWafRuleStateTypesValues() []ApplicationGatewayWafRuleStateTypes { - return []ApplicationGatewayWafRuleStateTypes{ApplicationGatewayWafRuleStateTypesDisabled, ApplicationGatewayWafRuleStateTypesEnabled} -} - -// AssociationType enumerates the values for association type. -type AssociationType string - -const ( - // Associated ... - Associated AssociationType = "Associated" - // Contains ... - Contains AssociationType = "Contains" -) - -// PossibleAssociationTypeValues returns an array of possible values for the AssociationType const type. -func PossibleAssociationTypeValues() []AssociationType { - return []AssociationType{Associated, Contains} -} - -// AuthenticationMethod enumerates the values for authentication method. -type AuthenticationMethod string - -const ( - // EAPMSCHAPv2 ... - EAPMSCHAPv2 AuthenticationMethod = "EAPMSCHAPv2" - // EAPTLS ... - EAPTLS AuthenticationMethod = "EAPTLS" -) - -// PossibleAuthenticationMethodValues returns an array of possible values for the AuthenticationMethod const type. -func PossibleAuthenticationMethodValues() []AuthenticationMethod { - return []AuthenticationMethod{EAPMSCHAPv2, EAPTLS} -} - -// AuthorizationUseStatus enumerates the values for authorization use status. -type AuthorizationUseStatus string - -const ( - // Available ... - Available AuthorizationUseStatus = "Available" - // InUse ... - InUse AuthorizationUseStatus = "InUse" -) - -// PossibleAuthorizationUseStatusValues returns an array of possible values for the AuthorizationUseStatus const type. -func PossibleAuthorizationUseStatusValues() []AuthorizationUseStatus { - return []AuthorizationUseStatus{Available, InUse} -} - -// AutoLearnPrivateRangesMode enumerates the values for auto learn private ranges mode. -type AutoLearnPrivateRangesMode string - -const ( - // AutoLearnPrivateRangesModeDisabled ... - AutoLearnPrivateRangesModeDisabled AutoLearnPrivateRangesMode = "Disabled" - // AutoLearnPrivateRangesModeEnabled ... - AutoLearnPrivateRangesModeEnabled AutoLearnPrivateRangesMode = "Enabled" -) - -// PossibleAutoLearnPrivateRangesModeValues returns an array of possible values for the AutoLearnPrivateRangesMode const type. -func PossibleAutoLearnPrivateRangesModeValues() []AutoLearnPrivateRangesMode { - return []AutoLearnPrivateRangesMode{AutoLearnPrivateRangesModeDisabled, AutoLearnPrivateRangesModeEnabled} -} - -// AzureFirewallApplicationRuleProtocolType enumerates the values for azure firewall application rule protocol -// type. -type AzureFirewallApplicationRuleProtocolType string - -const ( - // AzureFirewallApplicationRuleProtocolTypeHTTP ... - AzureFirewallApplicationRuleProtocolTypeHTTP AzureFirewallApplicationRuleProtocolType = "Http" - // AzureFirewallApplicationRuleProtocolTypeHTTPS ... - AzureFirewallApplicationRuleProtocolTypeHTTPS AzureFirewallApplicationRuleProtocolType = "Https" - // AzureFirewallApplicationRuleProtocolTypeMssql ... - AzureFirewallApplicationRuleProtocolTypeMssql AzureFirewallApplicationRuleProtocolType = "Mssql" -) - -// PossibleAzureFirewallApplicationRuleProtocolTypeValues returns an array of possible values for the AzureFirewallApplicationRuleProtocolType const type. -func PossibleAzureFirewallApplicationRuleProtocolTypeValues() []AzureFirewallApplicationRuleProtocolType { - return []AzureFirewallApplicationRuleProtocolType{AzureFirewallApplicationRuleProtocolTypeHTTP, AzureFirewallApplicationRuleProtocolTypeHTTPS, AzureFirewallApplicationRuleProtocolTypeMssql} -} - -// AzureFirewallNatRCActionType enumerates the values for azure firewall nat rc action type. -type AzureFirewallNatRCActionType string - -const ( - // Dnat ... - Dnat AzureFirewallNatRCActionType = "Dnat" - // Snat ... - Snat AzureFirewallNatRCActionType = "Snat" -) - -// PossibleAzureFirewallNatRCActionTypeValues returns an array of possible values for the AzureFirewallNatRCActionType const type. -func PossibleAzureFirewallNatRCActionTypeValues() []AzureFirewallNatRCActionType { - return []AzureFirewallNatRCActionType{Dnat, Snat} -} - -// AzureFirewallNetworkRuleProtocol enumerates the values for azure firewall network rule protocol. -type AzureFirewallNetworkRuleProtocol string - -const ( - // AzureFirewallNetworkRuleProtocolAny ... - AzureFirewallNetworkRuleProtocolAny AzureFirewallNetworkRuleProtocol = "Any" - // AzureFirewallNetworkRuleProtocolICMP ... - AzureFirewallNetworkRuleProtocolICMP AzureFirewallNetworkRuleProtocol = "ICMP" - // AzureFirewallNetworkRuleProtocolTCP ... - AzureFirewallNetworkRuleProtocolTCP AzureFirewallNetworkRuleProtocol = "TCP" - // AzureFirewallNetworkRuleProtocolUDP ... - AzureFirewallNetworkRuleProtocolUDP AzureFirewallNetworkRuleProtocol = "UDP" -) - -// PossibleAzureFirewallNetworkRuleProtocolValues returns an array of possible values for the AzureFirewallNetworkRuleProtocol const type. -func PossibleAzureFirewallNetworkRuleProtocolValues() []AzureFirewallNetworkRuleProtocol { - return []AzureFirewallNetworkRuleProtocol{AzureFirewallNetworkRuleProtocolAny, AzureFirewallNetworkRuleProtocolICMP, AzureFirewallNetworkRuleProtocolTCP, AzureFirewallNetworkRuleProtocolUDP} -} - -// AzureFirewallRCActionType enumerates the values for azure firewall rc action type. -type AzureFirewallRCActionType string - -const ( - // AzureFirewallRCActionTypeAllow ... - AzureFirewallRCActionTypeAllow AzureFirewallRCActionType = "Allow" - // AzureFirewallRCActionTypeDeny ... - AzureFirewallRCActionTypeDeny AzureFirewallRCActionType = "Deny" -) - -// PossibleAzureFirewallRCActionTypeValues returns an array of possible values for the AzureFirewallRCActionType const type. -func PossibleAzureFirewallRCActionTypeValues() []AzureFirewallRCActionType { - return []AzureFirewallRCActionType{AzureFirewallRCActionTypeAllow, AzureFirewallRCActionTypeDeny} -} - -// AzureFirewallSkuName enumerates the values for azure firewall sku name. -type AzureFirewallSkuName string - -const ( - // AZFWHub ... - AZFWHub AzureFirewallSkuName = "AZFW_Hub" - // AZFWVNet ... - AZFWVNet AzureFirewallSkuName = "AZFW_VNet" -) - -// PossibleAzureFirewallSkuNameValues returns an array of possible values for the AzureFirewallSkuName const type. -func PossibleAzureFirewallSkuNameValues() []AzureFirewallSkuName { - return []AzureFirewallSkuName{AZFWHub, AZFWVNet} -} - -// AzureFirewallSkuTier enumerates the values for azure firewall sku tier. -type AzureFirewallSkuTier string - -const ( - // AzureFirewallSkuTierBasic ... - AzureFirewallSkuTierBasic AzureFirewallSkuTier = "Basic" - // AzureFirewallSkuTierPremium ... - AzureFirewallSkuTierPremium AzureFirewallSkuTier = "Premium" - // AzureFirewallSkuTierStandard ... - AzureFirewallSkuTierStandard AzureFirewallSkuTier = "Standard" -) - -// PossibleAzureFirewallSkuTierValues returns an array of possible values for the AzureFirewallSkuTier const type. -func PossibleAzureFirewallSkuTierValues() []AzureFirewallSkuTier { - return []AzureFirewallSkuTier{AzureFirewallSkuTierBasic, AzureFirewallSkuTierPremium, AzureFirewallSkuTierStandard} -} - -// AzureFirewallThreatIntelMode enumerates the values for azure firewall threat intel mode. -type AzureFirewallThreatIntelMode string - -const ( - // AzureFirewallThreatIntelModeAlert ... - AzureFirewallThreatIntelModeAlert AzureFirewallThreatIntelMode = "Alert" - // AzureFirewallThreatIntelModeDeny ... - AzureFirewallThreatIntelModeDeny AzureFirewallThreatIntelMode = "Deny" - // AzureFirewallThreatIntelModeOff ... - AzureFirewallThreatIntelModeOff AzureFirewallThreatIntelMode = "Off" -) - -// PossibleAzureFirewallThreatIntelModeValues returns an array of possible values for the AzureFirewallThreatIntelMode const type. -func PossibleAzureFirewallThreatIntelModeValues() []AzureFirewallThreatIntelMode { - return []AzureFirewallThreatIntelMode{AzureFirewallThreatIntelModeAlert, AzureFirewallThreatIntelModeDeny, AzureFirewallThreatIntelModeOff} -} - -// BastionConnectProtocol enumerates the values for bastion connect protocol. -type BastionConnectProtocol string - -const ( - // RDP ... - RDP BastionConnectProtocol = "RDP" - // SSH ... - SSH BastionConnectProtocol = "SSH" -) - -// PossibleBastionConnectProtocolValues returns an array of possible values for the BastionConnectProtocol const type. -func PossibleBastionConnectProtocolValues() []BastionConnectProtocol { - return []BastionConnectProtocol{RDP, SSH} -} - -// BastionHostSkuName enumerates the values for bastion host sku name. -type BastionHostSkuName string - -const ( - // BastionHostSkuNameBasic ... - BastionHostSkuNameBasic BastionHostSkuName = "Basic" - // BastionHostSkuNameStandard ... - BastionHostSkuNameStandard BastionHostSkuName = "Standard" -) - -// PossibleBastionHostSkuNameValues returns an array of possible values for the BastionHostSkuName const type. -func PossibleBastionHostSkuNameValues() []BastionHostSkuName { - return []BastionHostSkuName{BastionHostSkuNameBasic, BastionHostSkuNameStandard} -} - -// BgpPeerState enumerates the values for bgp peer state. -type BgpPeerState string - -const ( - // BgpPeerStateConnected ... - BgpPeerStateConnected BgpPeerState = "Connected" - // BgpPeerStateConnecting ... - BgpPeerStateConnecting BgpPeerState = "Connecting" - // BgpPeerStateIdle ... - BgpPeerStateIdle BgpPeerState = "Idle" - // BgpPeerStateStopped ... - BgpPeerStateStopped BgpPeerState = "Stopped" - // BgpPeerStateUnknown ... - BgpPeerStateUnknown BgpPeerState = "Unknown" -) - -// PossibleBgpPeerStateValues returns an array of possible values for the BgpPeerState const type. -func PossibleBgpPeerStateValues() []BgpPeerState { - return []BgpPeerState{BgpPeerStateConnected, BgpPeerStateConnecting, BgpPeerStateIdle, BgpPeerStateStopped, BgpPeerStateUnknown} -} - -// CircuitConnectionStatus enumerates the values for circuit connection status. -type CircuitConnectionStatus string - -const ( - // Connected ... - Connected CircuitConnectionStatus = "Connected" - // Connecting ... - Connecting CircuitConnectionStatus = "Connecting" - // Disconnected ... - Disconnected CircuitConnectionStatus = "Disconnected" -) - -// PossibleCircuitConnectionStatusValues returns an array of possible values for the CircuitConnectionStatus const type. -func PossibleCircuitConnectionStatusValues() []CircuitConnectionStatus { - return []CircuitConnectionStatus{Connected, Connecting, Disconnected} -} - -// CommissionedState enumerates the values for commissioned state. -type CommissionedState string - -const ( - // Commissioned ... - Commissioned CommissionedState = "Commissioned" - // CommissionedNoInternetAdvertise ... - CommissionedNoInternetAdvertise CommissionedState = "CommissionedNoInternetAdvertise" - // Commissioning ... - Commissioning CommissionedState = "Commissioning" - // Decommissioning ... - Decommissioning CommissionedState = "Decommissioning" - // Deprovisioned ... - Deprovisioned CommissionedState = "Deprovisioned" - // Deprovisioning ... - Deprovisioning CommissionedState = "Deprovisioning" - // Provisioned ... - Provisioned CommissionedState = "Provisioned" - // Provisioning ... - Provisioning CommissionedState = "Provisioning" -) - -// PossibleCommissionedStateValues returns an array of possible values for the CommissionedState const type. -func PossibleCommissionedStateValues() []CommissionedState { - return []CommissionedState{Commissioned, CommissionedNoInternetAdvertise, Commissioning, Decommissioning, Deprovisioned, Deprovisioning, Provisioned, Provisioning} -} - -// ConfigurationType enumerates the values for configuration type. -type ConfigurationType string - -const ( - // Connectivity ... - Connectivity ConfigurationType = "Connectivity" - // SecurityAdmin ... - SecurityAdmin ConfigurationType = "SecurityAdmin" -) - -// PossibleConfigurationTypeValues returns an array of possible values for the ConfigurationType const type. -func PossibleConfigurationTypeValues() []ConfigurationType { - return []ConfigurationType{Connectivity, SecurityAdmin} -} - -// ConnectionMonitorEndpointFilterItemType enumerates the values for connection monitor endpoint filter item -// type. -type ConnectionMonitorEndpointFilterItemType string - -const ( - // AgentAddress ... - AgentAddress ConnectionMonitorEndpointFilterItemType = "AgentAddress" -) - -// PossibleConnectionMonitorEndpointFilterItemTypeValues returns an array of possible values for the ConnectionMonitorEndpointFilterItemType const type. -func PossibleConnectionMonitorEndpointFilterItemTypeValues() []ConnectionMonitorEndpointFilterItemType { - return []ConnectionMonitorEndpointFilterItemType{AgentAddress} -} - -// ConnectionMonitorEndpointFilterType enumerates the values for connection monitor endpoint filter type. -type ConnectionMonitorEndpointFilterType string - -const ( - // Include ... - Include ConnectionMonitorEndpointFilterType = "Include" -) - -// PossibleConnectionMonitorEndpointFilterTypeValues returns an array of possible values for the ConnectionMonitorEndpointFilterType const type. -func PossibleConnectionMonitorEndpointFilterTypeValues() []ConnectionMonitorEndpointFilterType { - return []ConnectionMonitorEndpointFilterType{Include} -} - -// ConnectionMonitorSourceStatus enumerates the values for connection monitor source status. -type ConnectionMonitorSourceStatus string - -const ( - // ConnectionMonitorSourceStatusActive ... - ConnectionMonitorSourceStatusActive ConnectionMonitorSourceStatus = "Active" - // ConnectionMonitorSourceStatusInactive ... - ConnectionMonitorSourceStatusInactive ConnectionMonitorSourceStatus = "Inactive" - // ConnectionMonitorSourceStatusUnknown ... - ConnectionMonitorSourceStatusUnknown ConnectionMonitorSourceStatus = "Unknown" -) - -// PossibleConnectionMonitorSourceStatusValues returns an array of possible values for the ConnectionMonitorSourceStatus const type. -func PossibleConnectionMonitorSourceStatusValues() []ConnectionMonitorSourceStatus { - return []ConnectionMonitorSourceStatus{ConnectionMonitorSourceStatusActive, ConnectionMonitorSourceStatusInactive, ConnectionMonitorSourceStatusUnknown} -} - -// ConnectionMonitorTestConfigurationProtocol enumerates the values for connection monitor test configuration -// protocol. -type ConnectionMonitorTestConfigurationProtocol string - -const ( - // ConnectionMonitorTestConfigurationProtocolHTTP ... - ConnectionMonitorTestConfigurationProtocolHTTP ConnectionMonitorTestConfigurationProtocol = "Http" - // ConnectionMonitorTestConfigurationProtocolIcmp ... - ConnectionMonitorTestConfigurationProtocolIcmp ConnectionMonitorTestConfigurationProtocol = "Icmp" - // ConnectionMonitorTestConfigurationProtocolTCP ... - ConnectionMonitorTestConfigurationProtocolTCP ConnectionMonitorTestConfigurationProtocol = "Tcp" -) - -// PossibleConnectionMonitorTestConfigurationProtocolValues returns an array of possible values for the ConnectionMonitorTestConfigurationProtocol const type. -func PossibleConnectionMonitorTestConfigurationProtocolValues() []ConnectionMonitorTestConfigurationProtocol { - return []ConnectionMonitorTestConfigurationProtocol{ConnectionMonitorTestConfigurationProtocolHTTP, ConnectionMonitorTestConfigurationProtocolIcmp, ConnectionMonitorTestConfigurationProtocolTCP} -} - -// ConnectionMonitorType enumerates the values for connection monitor type. -type ConnectionMonitorType string - -const ( - // MultiEndpoint ... - MultiEndpoint ConnectionMonitorType = "MultiEndpoint" - // SingleSourceDestination ... - SingleSourceDestination ConnectionMonitorType = "SingleSourceDestination" -) - -// PossibleConnectionMonitorTypeValues returns an array of possible values for the ConnectionMonitorType const type. -func PossibleConnectionMonitorTypeValues() []ConnectionMonitorType { - return []ConnectionMonitorType{MultiEndpoint, SingleSourceDestination} -} - -// ConnectionState enumerates the values for connection state. -type ConnectionState string - -const ( - // ConnectionStateReachable ... - ConnectionStateReachable ConnectionState = "Reachable" - // ConnectionStateUnknown ... - ConnectionStateUnknown ConnectionState = "Unknown" - // ConnectionStateUnreachable ... - ConnectionStateUnreachable ConnectionState = "Unreachable" -) - -// PossibleConnectionStateValues returns an array of possible values for the ConnectionState const type. -func PossibleConnectionStateValues() []ConnectionState { - return []ConnectionState{ConnectionStateReachable, ConnectionStateUnknown, ConnectionStateUnreachable} -} - -// ConnectionStatus enumerates the values for connection status. -type ConnectionStatus string - -const ( - // ConnectionStatusConnected ... - ConnectionStatusConnected ConnectionStatus = "Connected" - // ConnectionStatusDegraded ... - ConnectionStatusDegraded ConnectionStatus = "Degraded" - // ConnectionStatusDisconnected ... - ConnectionStatusDisconnected ConnectionStatus = "Disconnected" - // ConnectionStatusUnknown ... - ConnectionStatusUnknown ConnectionStatus = "Unknown" -) - -// PossibleConnectionStatusValues returns an array of possible values for the ConnectionStatus const type. -func PossibleConnectionStatusValues() []ConnectionStatus { - return []ConnectionStatus{ConnectionStatusConnected, ConnectionStatusDegraded, ConnectionStatusDisconnected, ConnectionStatusUnknown} -} - -// ConnectivityTopology enumerates the values for connectivity topology. -type ConnectivityTopology string - -const ( - // HubAndSpoke ... - HubAndSpoke ConnectivityTopology = "HubAndSpoke" - // Mesh ... - Mesh ConnectivityTopology = "Mesh" -) - -// PossibleConnectivityTopologyValues returns an array of possible values for the ConnectivityTopology const type. -func PossibleConnectivityTopologyValues() []ConnectivityTopology { - return []ConnectivityTopology{HubAndSpoke, Mesh} -} - -// CoverageLevel enumerates the values for coverage level. -type CoverageLevel string - -const ( - // AboveAverage ... - AboveAverage CoverageLevel = "AboveAverage" - // Average ... - Average CoverageLevel = "Average" - // BelowAverage ... - BelowAverage CoverageLevel = "BelowAverage" - // Default ... - Default CoverageLevel = "Default" - // Full ... - Full CoverageLevel = "Full" - // Low ... - Low CoverageLevel = "Low" -) - -// PossibleCoverageLevelValues returns an array of possible values for the CoverageLevel const type. -func PossibleCoverageLevelValues() []CoverageLevel { - return []CoverageLevel{AboveAverage, Average, BelowAverage, Default, Full, Low} -} - -// CreatedByType enumerates the values for created by type. -type CreatedByType string - -const ( - // Application ... - Application CreatedByType = "Application" - // Key ... - Key CreatedByType = "Key" - // ManagedIdentity ... - ManagedIdentity CreatedByType = "ManagedIdentity" - // User ... - User CreatedByType = "User" -) - -// PossibleCreatedByTypeValues returns an array of possible values for the CreatedByType const type. -func PossibleCreatedByTypeValues() []CreatedByType { - return []CreatedByType{Application, Key, ManagedIdentity, User} -} - -// CustomIPPrefixType enumerates the values for custom ip prefix type. -type CustomIPPrefixType string - -const ( - // Child ... - Child CustomIPPrefixType = "Child" - // Parent ... - Parent CustomIPPrefixType = "Parent" - // Singular ... - Singular CustomIPPrefixType = "Singular" -) - -// PossibleCustomIPPrefixTypeValues returns an array of possible values for the CustomIPPrefixType const type. -func PossibleCustomIPPrefixTypeValues() []CustomIPPrefixType { - return []CustomIPPrefixType{Child, Parent, Singular} -} - -// DdosSettingsProtectionMode enumerates the values for ddos settings protection mode. -type DdosSettingsProtectionMode string - -const ( - // DdosSettingsProtectionModeDisabled ... - DdosSettingsProtectionModeDisabled DdosSettingsProtectionMode = "Disabled" - // DdosSettingsProtectionModeEnabled ... - DdosSettingsProtectionModeEnabled DdosSettingsProtectionMode = "Enabled" - // DdosSettingsProtectionModeVirtualNetworkInherited ... - DdosSettingsProtectionModeVirtualNetworkInherited DdosSettingsProtectionMode = "VirtualNetworkInherited" -) - -// PossibleDdosSettingsProtectionModeValues returns an array of possible values for the DdosSettingsProtectionMode const type. -func PossibleDdosSettingsProtectionModeValues() []DdosSettingsProtectionMode { - return []DdosSettingsProtectionMode{DdosSettingsProtectionModeDisabled, DdosSettingsProtectionModeEnabled, DdosSettingsProtectionModeVirtualNetworkInherited} -} - -// DeleteExistingPeering enumerates the values for delete existing peering. -type DeleteExistingPeering string - -const ( - // False ... - False DeleteExistingPeering = "False" - // True ... - True DeleteExistingPeering = "True" -) - -// PossibleDeleteExistingPeeringValues returns an array of possible values for the DeleteExistingPeering const type. -func PossibleDeleteExistingPeeringValues() []DeleteExistingPeering { - return []DeleteExistingPeering{False, True} -} - -// DeleteOptions enumerates the values for delete options. -type DeleteOptions string - -const ( - // Delete ... - Delete DeleteOptions = "Delete" - // Detach ... - Detach DeleteOptions = "Detach" -) - -// PossibleDeleteOptionsValues returns an array of possible values for the DeleteOptions const type. -func PossibleDeleteOptionsValues() []DeleteOptions { - return []DeleteOptions{Delete, Detach} -} - -// DeploymentStatus enumerates the values for deployment status. -type DeploymentStatus string - -const ( - // Deployed ... - Deployed DeploymentStatus = "Deployed" - // Deploying ... - Deploying DeploymentStatus = "Deploying" - // Failed ... - Failed DeploymentStatus = "Failed" - // NotStarted ... - NotStarted DeploymentStatus = "NotStarted" -) - -// PossibleDeploymentStatusValues returns an array of possible values for the DeploymentStatus const type. -func PossibleDeploymentStatusValues() []DeploymentStatus { - return []DeploymentStatus{Deployed, Deploying, Failed, NotStarted} -} - -// DestinationPortBehavior enumerates the values for destination port behavior. -type DestinationPortBehavior string - -const ( - // DestinationPortBehaviorListenIfAvailable ... - DestinationPortBehaviorListenIfAvailable DestinationPortBehavior = "ListenIfAvailable" - // DestinationPortBehaviorNone ... - DestinationPortBehaviorNone DestinationPortBehavior = "None" -) - -// PossibleDestinationPortBehaviorValues returns an array of possible values for the DestinationPortBehavior const type. -func PossibleDestinationPortBehaviorValues() []DestinationPortBehavior { - return []DestinationPortBehavior{DestinationPortBehaviorListenIfAvailable, DestinationPortBehaviorNone} -} - -// DhGroup enumerates the values for dh group. -type DhGroup string - -const ( - // DhGroupDHGroup1 ... - DhGroupDHGroup1 DhGroup = "DHGroup1" - // DhGroupDHGroup14 ... - DhGroupDHGroup14 DhGroup = "DHGroup14" - // DhGroupDHGroup2 ... - DhGroupDHGroup2 DhGroup = "DHGroup2" - // DhGroupDHGroup2048 ... - DhGroupDHGroup2048 DhGroup = "DHGroup2048" - // DhGroupDHGroup24 ... - DhGroupDHGroup24 DhGroup = "DHGroup24" - // DhGroupECP256 ... - DhGroupECP256 DhGroup = "ECP256" - // DhGroupECP384 ... - DhGroupECP384 DhGroup = "ECP384" - // DhGroupNone ... - DhGroupNone DhGroup = "None" -) - -// PossibleDhGroupValues returns an array of possible values for the DhGroup const type. -func PossibleDhGroupValues() []DhGroup { - return []DhGroup{DhGroupDHGroup1, DhGroupDHGroup14, DhGroupDHGroup2, DhGroupDHGroup2048, DhGroupDHGroup24, DhGroupECP256, DhGroupECP384, DhGroupNone} -} - -// Direction enumerates the values for direction. -type Direction string - -const ( - // Inbound ... - Inbound Direction = "Inbound" - // Outbound ... - Outbound Direction = "Outbound" -) - -// PossibleDirectionValues returns an array of possible values for the Direction const type. -func PossibleDirectionValues() []Direction { - return []Direction{Inbound, Outbound} -} - -// EffectiveRouteSource enumerates the values for effective route source. -type EffectiveRouteSource string - -const ( - // EffectiveRouteSourceDefault ... - EffectiveRouteSourceDefault EffectiveRouteSource = "Default" - // EffectiveRouteSourceUnknown ... - EffectiveRouteSourceUnknown EffectiveRouteSource = "Unknown" - // EffectiveRouteSourceUser ... - EffectiveRouteSourceUser EffectiveRouteSource = "User" - // EffectiveRouteSourceVirtualNetworkGateway ... - EffectiveRouteSourceVirtualNetworkGateway EffectiveRouteSource = "VirtualNetworkGateway" -) - -// PossibleEffectiveRouteSourceValues returns an array of possible values for the EffectiveRouteSource const type. -func PossibleEffectiveRouteSourceValues() []EffectiveRouteSource { - return []EffectiveRouteSource{EffectiveRouteSourceDefault, EffectiveRouteSourceUnknown, EffectiveRouteSourceUser, EffectiveRouteSourceVirtualNetworkGateway} -} - -// EffectiveRouteState enumerates the values for effective route state. -type EffectiveRouteState string - -const ( - // Active ... - Active EffectiveRouteState = "Active" - // Invalid ... - Invalid EffectiveRouteState = "Invalid" -) - -// PossibleEffectiveRouteStateValues returns an array of possible values for the EffectiveRouteState const type. -func PossibleEffectiveRouteStateValues() []EffectiveRouteState { - return []EffectiveRouteState{Active, Invalid} -} - -// EffectiveSecurityRuleProtocol enumerates the values for effective security rule protocol. -type EffectiveSecurityRuleProtocol string - -const ( - // EffectiveSecurityRuleProtocolAll ... - EffectiveSecurityRuleProtocolAll EffectiveSecurityRuleProtocol = "All" - // EffectiveSecurityRuleProtocolTCP ... - EffectiveSecurityRuleProtocolTCP EffectiveSecurityRuleProtocol = "Tcp" - // EffectiveSecurityRuleProtocolUDP ... - EffectiveSecurityRuleProtocolUDP EffectiveSecurityRuleProtocol = "Udp" -) - -// PossibleEffectiveSecurityRuleProtocolValues returns an array of possible values for the EffectiveSecurityRuleProtocol const type. -func PossibleEffectiveSecurityRuleProtocolValues() []EffectiveSecurityRuleProtocol { - return []EffectiveSecurityRuleProtocol{EffectiveSecurityRuleProtocolAll, EffectiveSecurityRuleProtocolTCP, EffectiveSecurityRuleProtocolUDP} -} - -// EndpointType enumerates the values for endpoint type. -type EndpointType string - -const ( - // AzureArcVM ... - AzureArcVM EndpointType = "AzureArcVM" - // AzureSubnet ... - AzureSubnet EndpointType = "AzureSubnet" - // AzureVM ... - AzureVM EndpointType = "AzureVM" - // AzureVMSS ... - AzureVMSS EndpointType = "AzureVMSS" - // AzureVNet ... - AzureVNet EndpointType = "AzureVNet" - // ExternalAddress ... - ExternalAddress EndpointType = "ExternalAddress" - // MMAWorkspaceMachine ... - MMAWorkspaceMachine EndpointType = "MMAWorkspaceMachine" - // MMAWorkspaceNetwork ... - MMAWorkspaceNetwork EndpointType = "MMAWorkspaceNetwork" -) - -// PossibleEndpointTypeValues returns an array of possible values for the EndpointType const type. -func PossibleEndpointTypeValues() []EndpointType { - return []EndpointType{AzureArcVM, AzureSubnet, AzureVM, AzureVMSS, AzureVNet, ExternalAddress, MMAWorkspaceMachine, MMAWorkspaceNetwork} -} - -// EvaluationState enumerates the values for evaluation state. -type EvaluationState string - -const ( - // EvaluationStateCompleted ... - EvaluationStateCompleted EvaluationState = "Completed" - // EvaluationStateInProgress ... - EvaluationStateInProgress EvaluationState = "InProgress" - // EvaluationStateNotStarted ... - EvaluationStateNotStarted EvaluationState = "NotStarted" -) - -// PossibleEvaluationStateValues returns an array of possible values for the EvaluationState const type. -func PossibleEvaluationStateValues() []EvaluationState { - return []EvaluationState{EvaluationStateCompleted, EvaluationStateInProgress, EvaluationStateNotStarted} -} - -// ExpressRouteCircuitPeeringAdvertisedPublicPrefixState enumerates the values for express route circuit -// peering advertised public prefix state. -type ExpressRouteCircuitPeeringAdvertisedPublicPrefixState string - -const ( - // Configured ... - Configured ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "Configured" - // Configuring ... - Configuring ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "Configuring" - // NotConfigured ... - NotConfigured ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "NotConfigured" - // ValidationNeeded ... - ValidationNeeded ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "ValidationNeeded" -) - -// PossibleExpressRouteCircuitPeeringAdvertisedPublicPrefixStateValues returns an array of possible values for the ExpressRouteCircuitPeeringAdvertisedPublicPrefixState const type. -func PossibleExpressRouteCircuitPeeringAdvertisedPublicPrefixStateValues() []ExpressRouteCircuitPeeringAdvertisedPublicPrefixState { - return []ExpressRouteCircuitPeeringAdvertisedPublicPrefixState{Configured, Configuring, NotConfigured, ValidationNeeded} -} - -// ExpressRouteCircuitPeeringState enumerates the values for express route circuit peering state. -type ExpressRouteCircuitPeeringState string - -const ( - // ExpressRouteCircuitPeeringStateDisabled ... - ExpressRouteCircuitPeeringStateDisabled ExpressRouteCircuitPeeringState = "Disabled" - // ExpressRouteCircuitPeeringStateEnabled ... - ExpressRouteCircuitPeeringStateEnabled ExpressRouteCircuitPeeringState = "Enabled" -) - -// PossibleExpressRouteCircuitPeeringStateValues returns an array of possible values for the ExpressRouteCircuitPeeringState const type. -func PossibleExpressRouteCircuitPeeringStateValues() []ExpressRouteCircuitPeeringState { - return []ExpressRouteCircuitPeeringState{ExpressRouteCircuitPeeringStateDisabled, ExpressRouteCircuitPeeringStateEnabled} -} - -// ExpressRouteCircuitSkuFamily enumerates the values for express route circuit sku family. -type ExpressRouteCircuitSkuFamily string - -const ( - // MeteredData ... - MeteredData ExpressRouteCircuitSkuFamily = "MeteredData" - // UnlimitedData ... - UnlimitedData ExpressRouteCircuitSkuFamily = "UnlimitedData" -) - -// PossibleExpressRouteCircuitSkuFamilyValues returns an array of possible values for the ExpressRouteCircuitSkuFamily const type. -func PossibleExpressRouteCircuitSkuFamilyValues() []ExpressRouteCircuitSkuFamily { - return []ExpressRouteCircuitSkuFamily{MeteredData, UnlimitedData} -} - -// ExpressRouteCircuitSkuTier enumerates the values for express route circuit sku tier. -type ExpressRouteCircuitSkuTier string - -const ( - // ExpressRouteCircuitSkuTierBasic ... - ExpressRouteCircuitSkuTierBasic ExpressRouteCircuitSkuTier = "Basic" - // ExpressRouteCircuitSkuTierLocal ... - ExpressRouteCircuitSkuTierLocal ExpressRouteCircuitSkuTier = "Local" - // ExpressRouteCircuitSkuTierPremium ... - ExpressRouteCircuitSkuTierPremium ExpressRouteCircuitSkuTier = "Premium" - // ExpressRouteCircuitSkuTierStandard ... - ExpressRouteCircuitSkuTierStandard ExpressRouteCircuitSkuTier = "Standard" -) - -// PossibleExpressRouteCircuitSkuTierValues returns an array of possible values for the ExpressRouteCircuitSkuTier const type. -func PossibleExpressRouteCircuitSkuTierValues() []ExpressRouteCircuitSkuTier { - return []ExpressRouteCircuitSkuTier{ExpressRouteCircuitSkuTierBasic, ExpressRouteCircuitSkuTierLocal, ExpressRouteCircuitSkuTierPremium, ExpressRouteCircuitSkuTierStandard} -} - -// ExpressRouteLinkAdminState enumerates the values for express route link admin state. -type ExpressRouteLinkAdminState string - -const ( - // ExpressRouteLinkAdminStateDisabled ... - ExpressRouteLinkAdminStateDisabled ExpressRouteLinkAdminState = "Disabled" - // ExpressRouteLinkAdminStateEnabled ... - ExpressRouteLinkAdminStateEnabled ExpressRouteLinkAdminState = "Enabled" -) - -// PossibleExpressRouteLinkAdminStateValues returns an array of possible values for the ExpressRouteLinkAdminState const type. -func PossibleExpressRouteLinkAdminStateValues() []ExpressRouteLinkAdminState { - return []ExpressRouteLinkAdminState{ExpressRouteLinkAdminStateDisabled, ExpressRouteLinkAdminStateEnabled} -} - -// ExpressRouteLinkConnectorType enumerates the values for express route link connector type. -type ExpressRouteLinkConnectorType string - -const ( - // LC ... - LC ExpressRouteLinkConnectorType = "LC" - // SC ... - SC ExpressRouteLinkConnectorType = "SC" -) - -// PossibleExpressRouteLinkConnectorTypeValues returns an array of possible values for the ExpressRouteLinkConnectorType const type. -func PossibleExpressRouteLinkConnectorTypeValues() []ExpressRouteLinkConnectorType { - return []ExpressRouteLinkConnectorType{LC, SC} -} - -// ExpressRouteLinkMacSecCipher enumerates the values for express route link mac sec cipher. -type ExpressRouteLinkMacSecCipher string - -const ( - // GcmAes128 ... - GcmAes128 ExpressRouteLinkMacSecCipher = "GcmAes128" - // GcmAes256 ... - GcmAes256 ExpressRouteLinkMacSecCipher = "GcmAes256" - // GcmAesXpn128 ... - GcmAesXpn128 ExpressRouteLinkMacSecCipher = "GcmAesXpn128" - // GcmAesXpn256 ... - GcmAesXpn256 ExpressRouteLinkMacSecCipher = "GcmAesXpn256" -) - -// PossibleExpressRouteLinkMacSecCipherValues returns an array of possible values for the ExpressRouteLinkMacSecCipher const type. -func PossibleExpressRouteLinkMacSecCipherValues() []ExpressRouteLinkMacSecCipher { - return []ExpressRouteLinkMacSecCipher{GcmAes128, GcmAes256, GcmAesXpn128, GcmAesXpn256} -} - -// ExpressRouteLinkMacSecSciState enumerates the values for express route link mac sec sci state. -type ExpressRouteLinkMacSecSciState string - -const ( - // ExpressRouteLinkMacSecSciStateDisabled ... - ExpressRouteLinkMacSecSciStateDisabled ExpressRouteLinkMacSecSciState = "Disabled" - // ExpressRouteLinkMacSecSciStateEnabled ... - ExpressRouteLinkMacSecSciStateEnabled ExpressRouteLinkMacSecSciState = "Enabled" -) - -// PossibleExpressRouteLinkMacSecSciStateValues returns an array of possible values for the ExpressRouteLinkMacSecSciState const type. -func PossibleExpressRouteLinkMacSecSciStateValues() []ExpressRouteLinkMacSecSciState { - return []ExpressRouteLinkMacSecSciState{ExpressRouteLinkMacSecSciStateDisabled, ExpressRouteLinkMacSecSciStateEnabled} -} - -// ExpressRoutePeeringState enumerates the values for express route peering state. -type ExpressRoutePeeringState string - -const ( - // ExpressRoutePeeringStateDisabled ... - ExpressRoutePeeringStateDisabled ExpressRoutePeeringState = "Disabled" - // ExpressRoutePeeringStateEnabled ... - ExpressRoutePeeringStateEnabled ExpressRoutePeeringState = "Enabled" -) - -// PossibleExpressRoutePeeringStateValues returns an array of possible values for the ExpressRoutePeeringState const type. -func PossibleExpressRoutePeeringStateValues() []ExpressRoutePeeringState { - return []ExpressRoutePeeringState{ExpressRoutePeeringStateDisabled, ExpressRoutePeeringStateEnabled} -} - -// ExpressRoutePeeringType enumerates the values for express route peering type. -type ExpressRoutePeeringType string - -const ( - // AzurePrivatePeering ... - AzurePrivatePeering ExpressRoutePeeringType = "AzurePrivatePeering" - // AzurePublicPeering ... - AzurePublicPeering ExpressRoutePeeringType = "AzurePublicPeering" - // MicrosoftPeering ... - MicrosoftPeering ExpressRoutePeeringType = "MicrosoftPeering" -) - -// PossibleExpressRoutePeeringTypeValues returns an array of possible values for the ExpressRoutePeeringType const type. -func PossibleExpressRoutePeeringTypeValues() []ExpressRoutePeeringType { - return []ExpressRoutePeeringType{AzurePrivatePeering, AzurePublicPeering, MicrosoftPeering} -} - -// ExpressRoutePortAuthorizationUseStatus enumerates the values for express route port authorization use -// status. -type ExpressRoutePortAuthorizationUseStatus string - -const ( - // ExpressRoutePortAuthorizationUseStatusAvailable ... - ExpressRoutePortAuthorizationUseStatusAvailable ExpressRoutePortAuthorizationUseStatus = "Available" - // ExpressRoutePortAuthorizationUseStatusInUse ... - ExpressRoutePortAuthorizationUseStatusInUse ExpressRoutePortAuthorizationUseStatus = "InUse" -) - -// PossibleExpressRoutePortAuthorizationUseStatusValues returns an array of possible values for the ExpressRoutePortAuthorizationUseStatus const type. -func PossibleExpressRoutePortAuthorizationUseStatusValues() []ExpressRoutePortAuthorizationUseStatus { - return []ExpressRoutePortAuthorizationUseStatus{ExpressRoutePortAuthorizationUseStatusAvailable, ExpressRoutePortAuthorizationUseStatusInUse} -} - -// ExpressRoutePortsBillingType enumerates the values for express route ports billing type. -type ExpressRoutePortsBillingType string - -const ( - // ExpressRoutePortsBillingTypeMeteredData ... - ExpressRoutePortsBillingTypeMeteredData ExpressRoutePortsBillingType = "MeteredData" - // ExpressRoutePortsBillingTypeUnlimitedData ... - ExpressRoutePortsBillingTypeUnlimitedData ExpressRoutePortsBillingType = "UnlimitedData" -) - -// PossibleExpressRoutePortsBillingTypeValues returns an array of possible values for the ExpressRoutePortsBillingType const type. -func PossibleExpressRoutePortsBillingTypeValues() []ExpressRoutePortsBillingType { - return []ExpressRoutePortsBillingType{ExpressRoutePortsBillingTypeMeteredData, ExpressRoutePortsBillingTypeUnlimitedData} -} - -// ExpressRoutePortsEncapsulation enumerates the values for express route ports encapsulation. -type ExpressRoutePortsEncapsulation string - -const ( - // Dot1Q ... - Dot1Q ExpressRoutePortsEncapsulation = "Dot1Q" - // QinQ ... - QinQ ExpressRoutePortsEncapsulation = "QinQ" -) - -// PossibleExpressRoutePortsEncapsulationValues returns an array of possible values for the ExpressRoutePortsEncapsulation const type. -func PossibleExpressRoutePortsEncapsulationValues() []ExpressRoutePortsEncapsulation { - return []ExpressRoutePortsEncapsulation{Dot1Q, QinQ} -} - -// ExtendedLocationTypes enumerates the values for extended location types. -type ExtendedLocationTypes string - -const ( - // EdgeZone ... - EdgeZone ExtendedLocationTypes = "EdgeZone" -) - -// PossibleExtendedLocationTypesValues returns an array of possible values for the ExtendedLocationTypes const type. -func PossibleExtendedLocationTypesValues() []ExtendedLocationTypes { - return []ExtendedLocationTypes{EdgeZone} -} - -// FirewallPolicyFilterRuleCollectionActionType enumerates the values for firewall policy filter rule -// collection action type. -type FirewallPolicyFilterRuleCollectionActionType string - -const ( - // FirewallPolicyFilterRuleCollectionActionTypeAllow ... - FirewallPolicyFilterRuleCollectionActionTypeAllow FirewallPolicyFilterRuleCollectionActionType = "Allow" - // FirewallPolicyFilterRuleCollectionActionTypeDeny ... - FirewallPolicyFilterRuleCollectionActionTypeDeny FirewallPolicyFilterRuleCollectionActionType = "Deny" -) - -// PossibleFirewallPolicyFilterRuleCollectionActionTypeValues returns an array of possible values for the FirewallPolicyFilterRuleCollectionActionType const type. -func PossibleFirewallPolicyFilterRuleCollectionActionTypeValues() []FirewallPolicyFilterRuleCollectionActionType { - return []FirewallPolicyFilterRuleCollectionActionType{FirewallPolicyFilterRuleCollectionActionTypeAllow, FirewallPolicyFilterRuleCollectionActionTypeDeny} -} - -// FirewallPolicyIDPSQuerySortOrder enumerates the values for firewall policy idps query sort order. -type FirewallPolicyIDPSQuerySortOrder string - -const ( - // Ascending ... - Ascending FirewallPolicyIDPSQuerySortOrder = "Ascending" - // Descending ... - Descending FirewallPolicyIDPSQuerySortOrder = "Descending" -) - -// PossibleFirewallPolicyIDPSQuerySortOrderValues returns an array of possible values for the FirewallPolicyIDPSQuerySortOrder const type. -func PossibleFirewallPolicyIDPSQuerySortOrderValues() []FirewallPolicyIDPSQuerySortOrder { - return []FirewallPolicyIDPSQuerySortOrder{Ascending, Descending} -} - -// FirewallPolicyIntrusionDetectionProtocol enumerates the values for firewall policy intrusion detection -// protocol. -type FirewallPolicyIntrusionDetectionProtocol string - -const ( - // FirewallPolicyIntrusionDetectionProtocolANY ... - FirewallPolicyIntrusionDetectionProtocolANY FirewallPolicyIntrusionDetectionProtocol = "ANY" - // FirewallPolicyIntrusionDetectionProtocolICMP ... - FirewallPolicyIntrusionDetectionProtocolICMP FirewallPolicyIntrusionDetectionProtocol = "ICMP" - // FirewallPolicyIntrusionDetectionProtocolTCP ... - FirewallPolicyIntrusionDetectionProtocolTCP FirewallPolicyIntrusionDetectionProtocol = "TCP" - // FirewallPolicyIntrusionDetectionProtocolUDP ... - FirewallPolicyIntrusionDetectionProtocolUDP FirewallPolicyIntrusionDetectionProtocol = "UDP" -) - -// PossibleFirewallPolicyIntrusionDetectionProtocolValues returns an array of possible values for the FirewallPolicyIntrusionDetectionProtocol const type. -func PossibleFirewallPolicyIntrusionDetectionProtocolValues() []FirewallPolicyIntrusionDetectionProtocol { - return []FirewallPolicyIntrusionDetectionProtocol{FirewallPolicyIntrusionDetectionProtocolANY, FirewallPolicyIntrusionDetectionProtocolICMP, FirewallPolicyIntrusionDetectionProtocolTCP, FirewallPolicyIntrusionDetectionProtocolUDP} -} - -// FirewallPolicyIntrusionDetectionStateType enumerates the values for firewall policy intrusion detection -// state type. -type FirewallPolicyIntrusionDetectionStateType string - -const ( - // FirewallPolicyIntrusionDetectionStateTypeAlert ... - FirewallPolicyIntrusionDetectionStateTypeAlert FirewallPolicyIntrusionDetectionStateType = "Alert" - // FirewallPolicyIntrusionDetectionStateTypeDeny ... - FirewallPolicyIntrusionDetectionStateTypeDeny FirewallPolicyIntrusionDetectionStateType = "Deny" - // FirewallPolicyIntrusionDetectionStateTypeOff ... - FirewallPolicyIntrusionDetectionStateTypeOff FirewallPolicyIntrusionDetectionStateType = "Off" -) - -// PossibleFirewallPolicyIntrusionDetectionStateTypeValues returns an array of possible values for the FirewallPolicyIntrusionDetectionStateType const type. -func PossibleFirewallPolicyIntrusionDetectionStateTypeValues() []FirewallPolicyIntrusionDetectionStateType { - return []FirewallPolicyIntrusionDetectionStateType{FirewallPolicyIntrusionDetectionStateTypeAlert, FirewallPolicyIntrusionDetectionStateTypeDeny, FirewallPolicyIntrusionDetectionStateTypeOff} -} - -// FirewallPolicyNatRuleCollectionActionType enumerates the values for firewall policy nat rule collection -// action type. -type FirewallPolicyNatRuleCollectionActionType string - -const ( - // DNAT ... - DNAT FirewallPolicyNatRuleCollectionActionType = "DNAT" -) - -// PossibleFirewallPolicyNatRuleCollectionActionTypeValues returns an array of possible values for the FirewallPolicyNatRuleCollectionActionType const type. -func PossibleFirewallPolicyNatRuleCollectionActionTypeValues() []FirewallPolicyNatRuleCollectionActionType { - return []FirewallPolicyNatRuleCollectionActionType{DNAT} -} - -// FirewallPolicyRuleApplicationProtocolType enumerates the values for firewall policy rule application -// protocol type. -type FirewallPolicyRuleApplicationProtocolType string - -const ( - // FirewallPolicyRuleApplicationProtocolTypeHTTP ... - FirewallPolicyRuleApplicationProtocolTypeHTTP FirewallPolicyRuleApplicationProtocolType = "Http" - // FirewallPolicyRuleApplicationProtocolTypeHTTPS ... - FirewallPolicyRuleApplicationProtocolTypeHTTPS FirewallPolicyRuleApplicationProtocolType = "Https" -) - -// PossibleFirewallPolicyRuleApplicationProtocolTypeValues returns an array of possible values for the FirewallPolicyRuleApplicationProtocolType const type. -func PossibleFirewallPolicyRuleApplicationProtocolTypeValues() []FirewallPolicyRuleApplicationProtocolType { - return []FirewallPolicyRuleApplicationProtocolType{FirewallPolicyRuleApplicationProtocolTypeHTTP, FirewallPolicyRuleApplicationProtocolTypeHTTPS} -} - -// FirewallPolicyRuleNetworkProtocol enumerates the values for firewall policy rule network protocol. -type FirewallPolicyRuleNetworkProtocol string - -const ( - // FirewallPolicyRuleNetworkProtocolAny ... - FirewallPolicyRuleNetworkProtocolAny FirewallPolicyRuleNetworkProtocol = "Any" - // FirewallPolicyRuleNetworkProtocolICMP ... - FirewallPolicyRuleNetworkProtocolICMP FirewallPolicyRuleNetworkProtocol = "ICMP" - // FirewallPolicyRuleNetworkProtocolTCP ... - FirewallPolicyRuleNetworkProtocolTCP FirewallPolicyRuleNetworkProtocol = "TCP" - // FirewallPolicyRuleNetworkProtocolUDP ... - FirewallPolicyRuleNetworkProtocolUDP FirewallPolicyRuleNetworkProtocol = "UDP" -) - -// PossibleFirewallPolicyRuleNetworkProtocolValues returns an array of possible values for the FirewallPolicyRuleNetworkProtocol const type. -func PossibleFirewallPolicyRuleNetworkProtocolValues() []FirewallPolicyRuleNetworkProtocol { - return []FirewallPolicyRuleNetworkProtocol{FirewallPolicyRuleNetworkProtocolAny, FirewallPolicyRuleNetworkProtocolICMP, FirewallPolicyRuleNetworkProtocolTCP, FirewallPolicyRuleNetworkProtocolUDP} -} - -// FirewallPolicySkuTier enumerates the values for firewall policy sku tier. -type FirewallPolicySkuTier string - -const ( - // FirewallPolicySkuTierBasic ... - FirewallPolicySkuTierBasic FirewallPolicySkuTier = "Basic" - // FirewallPolicySkuTierPremium ... - FirewallPolicySkuTierPremium FirewallPolicySkuTier = "Premium" - // FirewallPolicySkuTierStandard ... - FirewallPolicySkuTierStandard FirewallPolicySkuTier = "Standard" -) - -// PossibleFirewallPolicySkuTierValues returns an array of possible values for the FirewallPolicySkuTier const type. -func PossibleFirewallPolicySkuTierValues() []FirewallPolicySkuTier { - return []FirewallPolicySkuTier{FirewallPolicySkuTierBasic, FirewallPolicySkuTierPremium, FirewallPolicySkuTierStandard} -} - -// FlowLogFormatType enumerates the values for flow log format type. -type FlowLogFormatType string - -const ( - // JSON ... - JSON FlowLogFormatType = "JSON" -) - -// PossibleFlowLogFormatTypeValues returns an array of possible values for the FlowLogFormatType const type. -func PossibleFlowLogFormatTypeValues() []FlowLogFormatType { - return []FlowLogFormatType{JSON} -} - -// GatewayLoadBalancerTunnelInterfaceType enumerates the values for gateway load balancer tunnel interface -// type. -type GatewayLoadBalancerTunnelInterfaceType string - -const ( - // GatewayLoadBalancerTunnelInterfaceTypeExternal ... - GatewayLoadBalancerTunnelInterfaceTypeExternal GatewayLoadBalancerTunnelInterfaceType = "External" - // GatewayLoadBalancerTunnelInterfaceTypeInternal ... - GatewayLoadBalancerTunnelInterfaceTypeInternal GatewayLoadBalancerTunnelInterfaceType = "Internal" - // GatewayLoadBalancerTunnelInterfaceTypeNone ... - GatewayLoadBalancerTunnelInterfaceTypeNone GatewayLoadBalancerTunnelInterfaceType = "None" -) - -// PossibleGatewayLoadBalancerTunnelInterfaceTypeValues returns an array of possible values for the GatewayLoadBalancerTunnelInterfaceType const type. -func PossibleGatewayLoadBalancerTunnelInterfaceTypeValues() []GatewayLoadBalancerTunnelInterfaceType { - return []GatewayLoadBalancerTunnelInterfaceType{GatewayLoadBalancerTunnelInterfaceTypeExternal, GatewayLoadBalancerTunnelInterfaceTypeInternal, GatewayLoadBalancerTunnelInterfaceTypeNone} -} - -// GatewayLoadBalancerTunnelProtocol enumerates the values for gateway load balancer tunnel protocol. -type GatewayLoadBalancerTunnelProtocol string - -const ( - // GatewayLoadBalancerTunnelProtocolNative ... - GatewayLoadBalancerTunnelProtocolNative GatewayLoadBalancerTunnelProtocol = "Native" - // GatewayLoadBalancerTunnelProtocolNone ... - GatewayLoadBalancerTunnelProtocolNone GatewayLoadBalancerTunnelProtocol = "None" - // GatewayLoadBalancerTunnelProtocolVXLAN ... - GatewayLoadBalancerTunnelProtocolVXLAN GatewayLoadBalancerTunnelProtocol = "VXLAN" -) - -// PossibleGatewayLoadBalancerTunnelProtocolValues returns an array of possible values for the GatewayLoadBalancerTunnelProtocol const type. -func PossibleGatewayLoadBalancerTunnelProtocolValues() []GatewayLoadBalancerTunnelProtocol { - return []GatewayLoadBalancerTunnelProtocol{GatewayLoadBalancerTunnelProtocolNative, GatewayLoadBalancerTunnelProtocolNone, GatewayLoadBalancerTunnelProtocolVXLAN} -} - -// Geo enumerates the values for geo. -type Geo string - -const ( - // AFRI ... - AFRI Geo = "AFRI" - // APAC ... - APAC Geo = "APAC" - // AQ ... - AQ Geo = "AQ" - // EURO ... - EURO Geo = "EURO" - // GLOBAL ... - GLOBAL Geo = "GLOBAL" - // LATAM ... - LATAM Geo = "LATAM" - // ME ... - ME Geo = "ME" - // NAM ... - NAM Geo = "NAM" - // OCEANIA ... - OCEANIA Geo = "OCEANIA" -) - -// PossibleGeoValues returns an array of possible values for the Geo const type. -func PossibleGeoValues() []Geo { - return []Geo{AFRI, APAC, AQ, EURO, GLOBAL, LATAM, ME, NAM, OCEANIA} -} - -// GroupConnectivity enumerates the values for group connectivity. -type GroupConnectivity string - -const ( - // GroupConnectivityDirectlyConnected ... - GroupConnectivityDirectlyConnected GroupConnectivity = "DirectlyConnected" - // GroupConnectivityNone ... - GroupConnectivityNone GroupConnectivity = "None" -) - -// PossibleGroupConnectivityValues returns an array of possible values for the GroupConnectivity const type. -func PossibleGroupConnectivityValues() []GroupConnectivity { - return []GroupConnectivity{GroupConnectivityDirectlyConnected, GroupConnectivityNone} -} - -// HTTPConfigurationMethod enumerates the values for http configuration method. -type HTTPConfigurationMethod string - -const ( - // Get ... - Get HTTPConfigurationMethod = "Get" - // Post ... - Post HTTPConfigurationMethod = "Post" -) - -// PossibleHTTPConfigurationMethodValues returns an array of possible values for the HTTPConfigurationMethod const type. -func PossibleHTTPConfigurationMethodValues() []HTTPConfigurationMethod { - return []HTTPConfigurationMethod{Get, Post} -} - -// HTTPMethod enumerates the values for http method. -type HTTPMethod string - -const ( - // HTTPMethodGet ... - HTTPMethodGet HTTPMethod = "Get" -) - -// PossibleHTTPMethodValues returns an array of possible values for the HTTPMethod const type. -func PossibleHTTPMethodValues() []HTTPMethod { - return []HTTPMethod{HTTPMethodGet} -} - -// HubBgpConnectionStatus enumerates the values for hub bgp connection status. -type HubBgpConnectionStatus string - -const ( - // HubBgpConnectionStatusConnected ... - HubBgpConnectionStatusConnected HubBgpConnectionStatus = "Connected" - // HubBgpConnectionStatusConnecting ... - HubBgpConnectionStatusConnecting HubBgpConnectionStatus = "Connecting" - // HubBgpConnectionStatusNotConnected ... - HubBgpConnectionStatusNotConnected HubBgpConnectionStatus = "NotConnected" - // HubBgpConnectionStatusUnknown ... - HubBgpConnectionStatusUnknown HubBgpConnectionStatus = "Unknown" -) - -// PossibleHubBgpConnectionStatusValues returns an array of possible values for the HubBgpConnectionStatus const type. -func PossibleHubBgpConnectionStatusValues() []HubBgpConnectionStatus { - return []HubBgpConnectionStatus{HubBgpConnectionStatusConnected, HubBgpConnectionStatusConnecting, HubBgpConnectionStatusNotConnected, HubBgpConnectionStatusUnknown} -} - -// HubRoutingPreference enumerates the values for hub routing preference. -type HubRoutingPreference string - -const ( - // HubRoutingPreferenceASPath ... - HubRoutingPreferenceASPath HubRoutingPreference = "ASPath" - // HubRoutingPreferenceExpressRoute ... - HubRoutingPreferenceExpressRoute HubRoutingPreference = "ExpressRoute" - // HubRoutingPreferenceVpnGateway ... - HubRoutingPreferenceVpnGateway HubRoutingPreference = "VpnGateway" -) - -// PossibleHubRoutingPreferenceValues returns an array of possible values for the HubRoutingPreference const type. -func PossibleHubRoutingPreferenceValues() []HubRoutingPreference { - return []HubRoutingPreference{HubRoutingPreferenceASPath, HubRoutingPreferenceExpressRoute, HubRoutingPreferenceVpnGateway} -} - -// HubVirtualNetworkConnectionStatus enumerates the values for hub virtual network connection status. -type HubVirtualNetworkConnectionStatus string - -const ( - // HubVirtualNetworkConnectionStatusConnected ... - HubVirtualNetworkConnectionStatusConnected HubVirtualNetworkConnectionStatus = "Connected" - // HubVirtualNetworkConnectionStatusConnecting ... - HubVirtualNetworkConnectionStatusConnecting HubVirtualNetworkConnectionStatus = "Connecting" - // HubVirtualNetworkConnectionStatusNotConnected ... - HubVirtualNetworkConnectionStatusNotConnected HubVirtualNetworkConnectionStatus = "NotConnected" - // HubVirtualNetworkConnectionStatusUnknown ... - HubVirtualNetworkConnectionStatusUnknown HubVirtualNetworkConnectionStatus = "Unknown" -) - -// PossibleHubVirtualNetworkConnectionStatusValues returns an array of possible values for the HubVirtualNetworkConnectionStatus const type. -func PossibleHubVirtualNetworkConnectionStatusValues() []HubVirtualNetworkConnectionStatus { - return []HubVirtualNetworkConnectionStatus{HubVirtualNetworkConnectionStatusConnected, HubVirtualNetworkConnectionStatusConnecting, HubVirtualNetworkConnectionStatusNotConnected, HubVirtualNetworkConnectionStatusUnknown} -} - -// IkeEncryption enumerates the values for ike encryption. -type IkeEncryption string - -const ( - // AES128 ... - AES128 IkeEncryption = "AES128" - // AES192 ... - AES192 IkeEncryption = "AES192" - // AES256 ... - AES256 IkeEncryption = "AES256" - // DES ... - DES IkeEncryption = "DES" - // DES3 ... - DES3 IkeEncryption = "DES3" - // GCMAES128 ... - GCMAES128 IkeEncryption = "GCMAES128" - // GCMAES256 ... - GCMAES256 IkeEncryption = "GCMAES256" -) - -// PossibleIkeEncryptionValues returns an array of possible values for the IkeEncryption const type. -func PossibleIkeEncryptionValues() []IkeEncryption { - return []IkeEncryption{AES128, AES192, AES256, DES, DES3, GCMAES128, GCMAES256} -} - -// IkeIntegrity enumerates the values for ike integrity. -type IkeIntegrity string - -const ( - // IkeIntegrityGCMAES128 ... - IkeIntegrityGCMAES128 IkeIntegrity = "GCMAES128" - // IkeIntegrityGCMAES256 ... - IkeIntegrityGCMAES256 IkeIntegrity = "GCMAES256" - // IkeIntegrityMD5 ... - IkeIntegrityMD5 IkeIntegrity = "MD5" - // IkeIntegritySHA1 ... - IkeIntegritySHA1 IkeIntegrity = "SHA1" - // IkeIntegritySHA256 ... - IkeIntegritySHA256 IkeIntegrity = "SHA256" - // IkeIntegritySHA384 ... - IkeIntegritySHA384 IkeIntegrity = "SHA384" -) - -// PossibleIkeIntegrityValues returns an array of possible values for the IkeIntegrity const type. -func PossibleIkeIntegrityValues() []IkeIntegrity { - return []IkeIntegrity{IkeIntegrityGCMAES128, IkeIntegrityGCMAES256, IkeIntegrityMD5, IkeIntegritySHA1, IkeIntegritySHA256, IkeIntegritySHA384} -} - -// InboundSecurityRulesProtocol enumerates the values for inbound security rules protocol. -type InboundSecurityRulesProtocol string - -const ( - // InboundSecurityRulesProtocolTCP ... - InboundSecurityRulesProtocolTCP InboundSecurityRulesProtocol = "TCP" - // InboundSecurityRulesProtocolUDP ... - InboundSecurityRulesProtocolUDP InboundSecurityRulesProtocol = "UDP" -) - -// PossibleInboundSecurityRulesProtocolValues returns an array of possible values for the InboundSecurityRulesProtocol const type. -func PossibleInboundSecurityRulesProtocolValues() []InboundSecurityRulesProtocol { - return []InboundSecurityRulesProtocol{InboundSecurityRulesProtocolTCP, InboundSecurityRulesProtocolUDP} -} - -// IntentPolicyBasedService enumerates the values for intent policy based service. -type IntentPolicyBasedService string - -const ( - // IntentPolicyBasedServiceAll ... - IntentPolicyBasedServiceAll IntentPolicyBasedService = "All" - // IntentPolicyBasedServiceAllowRulesOnly ... - IntentPolicyBasedServiceAllowRulesOnly IntentPolicyBasedService = "AllowRulesOnly" - // IntentPolicyBasedServiceNone ... - IntentPolicyBasedServiceNone IntentPolicyBasedService = "None" -) - -// PossibleIntentPolicyBasedServiceValues returns an array of possible values for the IntentPolicyBasedService const type. -func PossibleIntentPolicyBasedServiceValues() []IntentPolicyBasedService { - return []IntentPolicyBasedService{IntentPolicyBasedServiceAll, IntentPolicyBasedServiceAllowRulesOnly, IntentPolicyBasedServiceNone} -} - -// InterfaceAuxiliaryMode enumerates the values for interface auxiliary mode. -type InterfaceAuxiliaryMode string - -const ( - // InterfaceAuxiliaryModeFloating ... - InterfaceAuxiliaryModeFloating InterfaceAuxiliaryMode = "Floating" - // InterfaceAuxiliaryModeMaxConnections ... - InterfaceAuxiliaryModeMaxConnections InterfaceAuxiliaryMode = "MaxConnections" - // InterfaceAuxiliaryModeNone ... - InterfaceAuxiliaryModeNone InterfaceAuxiliaryMode = "None" -) - -// PossibleInterfaceAuxiliaryModeValues returns an array of possible values for the InterfaceAuxiliaryMode const type. -func PossibleInterfaceAuxiliaryModeValues() []InterfaceAuxiliaryMode { - return []InterfaceAuxiliaryMode{InterfaceAuxiliaryModeFloating, InterfaceAuxiliaryModeMaxConnections, InterfaceAuxiliaryModeNone} -} - -// InterfaceMigrationPhase enumerates the values for interface migration phase. -type InterfaceMigrationPhase string - -const ( - // InterfaceMigrationPhaseAbort ... - InterfaceMigrationPhaseAbort InterfaceMigrationPhase = "Abort" - // InterfaceMigrationPhaseCommit ... - InterfaceMigrationPhaseCommit InterfaceMigrationPhase = "Commit" - // InterfaceMigrationPhaseCommitted ... - InterfaceMigrationPhaseCommitted InterfaceMigrationPhase = "Committed" - // InterfaceMigrationPhaseNone ... - InterfaceMigrationPhaseNone InterfaceMigrationPhase = "None" - // InterfaceMigrationPhasePrepare ... - InterfaceMigrationPhasePrepare InterfaceMigrationPhase = "Prepare" -) - -// PossibleInterfaceMigrationPhaseValues returns an array of possible values for the InterfaceMigrationPhase const type. -func PossibleInterfaceMigrationPhaseValues() []InterfaceMigrationPhase { - return []InterfaceMigrationPhase{InterfaceMigrationPhaseAbort, InterfaceMigrationPhaseCommit, InterfaceMigrationPhaseCommitted, InterfaceMigrationPhaseNone, InterfaceMigrationPhasePrepare} -} - -// InterfaceNicType enumerates the values for interface nic type. -type InterfaceNicType string - -const ( - // Elastic ... - Elastic InterfaceNicType = "Elastic" - // Standard ... - Standard InterfaceNicType = "Standard" -) - -// PossibleInterfaceNicTypeValues returns an array of possible values for the InterfaceNicType const type. -func PossibleInterfaceNicTypeValues() []InterfaceNicType { - return []InterfaceNicType{Elastic, Standard} -} - -// IPAllocationMethod enumerates the values for ip allocation method. -type IPAllocationMethod string - -const ( - // Dynamic ... - Dynamic IPAllocationMethod = "Dynamic" - // Static ... - Static IPAllocationMethod = "Static" -) - -// PossibleIPAllocationMethodValues returns an array of possible values for the IPAllocationMethod const type. -func PossibleIPAllocationMethodValues() []IPAllocationMethod { - return []IPAllocationMethod{Dynamic, Static} -} - -// IPAllocationType enumerates the values for ip allocation type. -type IPAllocationType string - -const ( - // Hypernet ... - Hypernet IPAllocationType = "Hypernet" - // Undefined ... - Undefined IPAllocationType = "Undefined" -) - -// PossibleIPAllocationTypeValues returns an array of possible values for the IPAllocationType const type. -func PossibleIPAllocationTypeValues() []IPAllocationType { - return []IPAllocationType{Hypernet, Undefined} -} - -// IPFlowProtocol enumerates the values for ip flow protocol. -type IPFlowProtocol string - -const ( - // IPFlowProtocolTCP ... - IPFlowProtocolTCP IPFlowProtocol = "TCP" - // IPFlowProtocolUDP ... - IPFlowProtocolUDP IPFlowProtocol = "UDP" -) - -// PossibleIPFlowProtocolValues returns an array of possible values for the IPFlowProtocol const type. -func PossibleIPFlowProtocolValues() []IPFlowProtocol { - return []IPFlowProtocol{IPFlowProtocolTCP, IPFlowProtocolUDP} -} - -// IpsecEncryption enumerates the values for ipsec encryption. -type IpsecEncryption string - -const ( - // IpsecEncryptionAES128 ... - IpsecEncryptionAES128 IpsecEncryption = "AES128" - // IpsecEncryptionAES192 ... - IpsecEncryptionAES192 IpsecEncryption = "AES192" - // IpsecEncryptionAES256 ... - IpsecEncryptionAES256 IpsecEncryption = "AES256" - // IpsecEncryptionDES ... - IpsecEncryptionDES IpsecEncryption = "DES" - // IpsecEncryptionDES3 ... - IpsecEncryptionDES3 IpsecEncryption = "DES3" - // IpsecEncryptionGCMAES128 ... - IpsecEncryptionGCMAES128 IpsecEncryption = "GCMAES128" - // IpsecEncryptionGCMAES192 ... - IpsecEncryptionGCMAES192 IpsecEncryption = "GCMAES192" - // IpsecEncryptionGCMAES256 ... - IpsecEncryptionGCMAES256 IpsecEncryption = "GCMAES256" - // IpsecEncryptionNone ... - IpsecEncryptionNone IpsecEncryption = "None" -) - -// PossibleIpsecEncryptionValues returns an array of possible values for the IpsecEncryption const type. -func PossibleIpsecEncryptionValues() []IpsecEncryption { - return []IpsecEncryption{IpsecEncryptionAES128, IpsecEncryptionAES192, IpsecEncryptionAES256, IpsecEncryptionDES, IpsecEncryptionDES3, IpsecEncryptionGCMAES128, IpsecEncryptionGCMAES192, IpsecEncryptionGCMAES256, IpsecEncryptionNone} -} - -// IpsecIntegrity enumerates the values for ipsec integrity. -type IpsecIntegrity string - -const ( - // IpsecIntegrityGCMAES128 ... - IpsecIntegrityGCMAES128 IpsecIntegrity = "GCMAES128" - // IpsecIntegrityGCMAES192 ... - IpsecIntegrityGCMAES192 IpsecIntegrity = "GCMAES192" - // IpsecIntegrityGCMAES256 ... - IpsecIntegrityGCMAES256 IpsecIntegrity = "GCMAES256" - // IpsecIntegrityMD5 ... - IpsecIntegrityMD5 IpsecIntegrity = "MD5" - // IpsecIntegritySHA1 ... - IpsecIntegritySHA1 IpsecIntegrity = "SHA1" - // IpsecIntegritySHA256 ... - IpsecIntegritySHA256 IpsecIntegrity = "SHA256" -) - -// PossibleIpsecIntegrityValues returns an array of possible values for the IpsecIntegrity const type. -func PossibleIpsecIntegrityValues() []IpsecIntegrity { - return []IpsecIntegrity{IpsecIntegrityGCMAES128, IpsecIntegrityGCMAES192, IpsecIntegrityGCMAES256, IpsecIntegrityMD5, IpsecIntegritySHA1, IpsecIntegritySHA256} -} - -// IPVersion enumerates the values for ip version. -type IPVersion string - -const ( - // IPv4 ... - IPv4 IPVersion = "IPv4" - // IPv6 ... - IPv6 IPVersion = "IPv6" -) - -// PossibleIPVersionValues returns an array of possible values for the IPVersion const type. -func PossibleIPVersionValues() []IPVersion { - return []IPVersion{IPv4, IPv6} -} - -// IsGlobal enumerates the values for is global. -type IsGlobal string - -const ( - // IsGlobalFalse ... - IsGlobalFalse IsGlobal = "False" - // IsGlobalTrue ... - IsGlobalTrue IsGlobal = "True" -) - -// PossibleIsGlobalValues returns an array of possible values for the IsGlobal const type. -func PossibleIsGlobalValues() []IsGlobal { - return []IsGlobal{IsGlobalFalse, IsGlobalTrue} -} - -// IssueType enumerates the values for issue type. -type IssueType string - -const ( - // IssueTypeAgentStopped ... - IssueTypeAgentStopped IssueType = "AgentStopped" - // IssueTypeDNSResolution ... - IssueTypeDNSResolution IssueType = "DnsResolution" - // IssueTypeGuestFirewall ... - IssueTypeGuestFirewall IssueType = "GuestFirewall" - // IssueTypeNetworkSecurityRule ... - IssueTypeNetworkSecurityRule IssueType = "NetworkSecurityRule" - // IssueTypePlatform ... - IssueTypePlatform IssueType = "Platform" - // IssueTypePortThrottled ... - IssueTypePortThrottled IssueType = "PortThrottled" - // IssueTypeSocketBind ... - IssueTypeSocketBind IssueType = "SocketBind" - // IssueTypeUnknown ... - IssueTypeUnknown IssueType = "Unknown" - // IssueTypeUserDefinedRoute ... - IssueTypeUserDefinedRoute IssueType = "UserDefinedRoute" -) - -// PossibleIssueTypeValues returns an array of possible values for the IssueType const type. -func PossibleIssueTypeValues() []IssueType { - return []IssueType{IssueTypeAgentStopped, IssueTypeDNSResolution, IssueTypeGuestFirewall, IssueTypeNetworkSecurityRule, IssueTypePlatform, IssueTypePortThrottled, IssueTypeSocketBind, IssueTypeUnknown, IssueTypeUserDefinedRoute} -} - -// IsWorkloadProtected enumerates the values for is workload protected. -type IsWorkloadProtected string - -const ( - // IsWorkloadProtectedFalse ... - IsWorkloadProtectedFalse IsWorkloadProtected = "False" - // IsWorkloadProtectedTrue ... - IsWorkloadProtectedTrue IsWorkloadProtected = "True" -) - -// PossibleIsWorkloadProtectedValues returns an array of possible values for the IsWorkloadProtected const type. -func PossibleIsWorkloadProtectedValues() []IsWorkloadProtected { - return []IsWorkloadProtected{IsWorkloadProtectedFalse, IsWorkloadProtectedTrue} -} - -// Kind enumerates the values for kind. -type Kind string - -const ( - // KindActiveBaseSecurityAdminRule ... - KindActiveBaseSecurityAdminRule Kind = "ActiveBaseSecurityAdminRule" - // KindCustom ... - KindCustom Kind = "Custom" - // KindDefault ... - KindDefault Kind = "Default" -) - -// PossibleKindValues returns an array of possible values for the Kind const type. -func PossibleKindValues() []Kind { - return []Kind{KindActiveBaseSecurityAdminRule, KindCustom, KindDefault} -} - -// KindBasicBaseAdminRule enumerates the values for kind basic base admin rule. -type KindBasicBaseAdminRule string - -const ( - // KindBasicBaseAdminRuleKindBaseAdminRule ... - KindBasicBaseAdminRuleKindBaseAdminRule KindBasicBaseAdminRule = "BaseAdminRule" - // KindBasicBaseAdminRuleKindCustom ... - KindBasicBaseAdminRuleKindCustom KindBasicBaseAdminRule = "Custom" - // KindBasicBaseAdminRuleKindDefault ... - KindBasicBaseAdminRuleKindDefault KindBasicBaseAdminRule = "Default" -) - -// PossibleKindBasicBaseAdminRuleValues returns an array of possible values for the KindBasicBaseAdminRule const type. -func PossibleKindBasicBaseAdminRuleValues() []KindBasicBaseAdminRule { - return []KindBasicBaseAdminRule{KindBasicBaseAdminRuleKindBaseAdminRule, KindBasicBaseAdminRuleKindCustom, KindBasicBaseAdminRuleKindDefault} -} - -// KindBasicEffectiveBaseSecurityAdminRule enumerates the values for kind basic effective base security admin -// rule. -type KindBasicEffectiveBaseSecurityAdminRule string - -const ( - // KindBasicEffectiveBaseSecurityAdminRuleKindCustom ... - KindBasicEffectiveBaseSecurityAdminRuleKindCustom KindBasicEffectiveBaseSecurityAdminRule = "Custom" - // KindBasicEffectiveBaseSecurityAdminRuleKindDefault ... - KindBasicEffectiveBaseSecurityAdminRuleKindDefault KindBasicEffectiveBaseSecurityAdminRule = "Default" - // KindBasicEffectiveBaseSecurityAdminRuleKindEffectiveBaseSecurityAdminRule ... - KindBasicEffectiveBaseSecurityAdminRuleKindEffectiveBaseSecurityAdminRule KindBasicEffectiveBaseSecurityAdminRule = "EffectiveBaseSecurityAdminRule" -) - -// PossibleKindBasicEffectiveBaseSecurityAdminRuleValues returns an array of possible values for the KindBasicEffectiveBaseSecurityAdminRule const type. -func PossibleKindBasicEffectiveBaseSecurityAdminRuleValues() []KindBasicEffectiveBaseSecurityAdminRule { - return []KindBasicEffectiveBaseSecurityAdminRule{KindBasicEffectiveBaseSecurityAdminRuleKindCustom, KindBasicEffectiveBaseSecurityAdminRuleKindDefault, KindBasicEffectiveBaseSecurityAdminRuleKindEffectiveBaseSecurityAdminRule} -} - -// LoadBalancerBackendAddressAdminState enumerates the values for load balancer backend address admin state. -type LoadBalancerBackendAddressAdminState string - -const ( - // LoadBalancerBackendAddressAdminStateDown ... - LoadBalancerBackendAddressAdminStateDown LoadBalancerBackendAddressAdminState = "Down" - // LoadBalancerBackendAddressAdminStateDrain ... - LoadBalancerBackendAddressAdminStateDrain LoadBalancerBackendAddressAdminState = "Drain" - // LoadBalancerBackendAddressAdminStateNone ... - LoadBalancerBackendAddressAdminStateNone LoadBalancerBackendAddressAdminState = "None" - // LoadBalancerBackendAddressAdminStateUp ... - LoadBalancerBackendAddressAdminStateUp LoadBalancerBackendAddressAdminState = "Up" -) - -// PossibleLoadBalancerBackendAddressAdminStateValues returns an array of possible values for the LoadBalancerBackendAddressAdminState const type. -func PossibleLoadBalancerBackendAddressAdminStateValues() []LoadBalancerBackendAddressAdminState { - return []LoadBalancerBackendAddressAdminState{LoadBalancerBackendAddressAdminStateDown, LoadBalancerBackendAddressAdminStateDrain, LoadBalancerBackendAddressAdminStateNone, LoadBalancerBackendAddressAdminStateUp} -} - -// LoadBalancerOutboundRuleProtocol enumerates the values for load balancer outbound rule protocol. -type LoadBalancerOutboundRuleProtocol string - -const ( - // LoadBalancerOutboundRuleProtocolAll ... - LoadBalancerOutboundRuleProtocolAll LoadBalancerOutboundRuleProtocol = "All" - // LoadBalancerOutboundRuleProtocolTCP ... - LoadBalancerOutboundRuleProtocolTCP LoadBalancerOutboundRuleProtocol = "Tcp" - // LoadBalancerOutboundRuleProtocolUDP ... - LoadBalancerOutboundRuleProtocolUDP LoadBalancerOutboundRuleProtocol = "Udp" -) - -// PossibleLoadBalancerOutboundRuleProtocolValues returns an array of possible values for the LoadBalancerOutboundRuleProtocol const type. -func PossibleLoadBalancerOutboundRuleProtocolValues() []LoadBalancerOutboundRuleProtocol { - return []LoadBalancerOutboundRuleProtocol{LoadBalancerOutboundRuleProtocolAll, LoadBalancerOutboundRuleProtocolTCP, LoadBalancerOutboundRuleProtocolUDP} -} - -// LoadBalancerSkuName enumerates the values for load balancer sku name. -type LoadBalancerSkuName string - -const ( - // LoadBalancerSkuNameBasic ... - LoadBalancerSkuNameBasic LoadBalancerSkuName = "Basic" - // LoadBalancerSkuNameGateway ... - LoadBalancerSkuNameGateway LoadBalancerSkuName = "Gateway" - // LoadBalancerSkuNameStandard ... - LoadBalancerSkuNameStandard LoadBalancerSkuName = "Standard" -) - -// PossibleLoadBalancerSkuNameValues returns an array of possible values for the LoadBalancerSkuName const type. -func PossibleLoadBalancerSkuNameValues() []LoadBalancerSkuName { - return []LoadBalancerSkuName{LoadBalancerSkuNameBasic, LoadBalancerSkuNameGateway, LoadBalancerSkuNameStandard} -} - -// LoadBalancerSkuTier enumerates the values for load balancer sku tier. -type LoadBalancerSkuTier string - -const ( - // Global ... - Global LoadBalancerSkuTier = "Global" - // Regional ... - Regional LoadBalancerSkuTier = "Regional" -) - -// PossibleLoadBalancerSkuTierValues returns an array of possible values for the LoadBalancerSkuTier const type. -func PossibleLoadBalancerSkuTierValues() []LoadBalancerSkuTier { - return []LoadBalancerSkuTier{Global, Regional} -} - -// LoadDistribution enumerates the values for load distribution. -type LoadDistribution string - -const ( - // LoadDistributionDefault ... - LoadDistributionDefault LoadDistribution = "Default" - // LoadDistributionSourceIP ... - LoadDistributionSourceIP LoadDistribution = "SourceIP" - // LoadDistributionSourceIPProtocol ... - LoadDistributionSourceIPProtocol LoadDistribution = "SourceIPProtocol" -) - -// PossibleLoadDistributionValues returns an array of possible values for the LoadDistribution const type. -func PossibleLoadDistributionValues() []LoadDistribution { - return []LoadDistribution{LoadDistributionDefault, LoadDistributionSourceIP, LoadDistributionSourceIPProtocol} -} - -// ManagedRuleEnabledState enumerates the values for managed rule enabled state. -type ManagedRuleEnabledState string - -const ( - // ManagedRuleEnabledStateDisabled ... - ManagedRuleEnabledStateDisabled ManagedRuleEnabledState = "Disabled" - // ManagedRuleEnabledStateEnabled ... - ManagedRuleEnabledStateEnabled ManagedRuleEnabledState = "Enabled" -) - -// PossibleManagedRuleEnabledStateValues returns an array of possible values for the ManagedRuleEnabledState const type. -func PossibleManagedRuleEnabledStateValues() []ManagedRuleEnabledState { - return []ManagedRuleEnabledState{ManagedRuleEnabledStateDisabled, ManagedRuleEnabledStateEnabled} -} - -// NatGatewaySkuName enumerates the values for nat gateway sku name. -type NatGatewaySkuName string - -const ( - // NatGatewaySkuNameStandard ... - NatGatewaySkuNameStandard NatGatewaySkuName = "Standard" -) - -// PossibleNatGatewaySkuNameValues returns an array of possible values for the NatGatewaySkuName const type. -func PossibleNatGatewaySkuNameValues() []NatGatewaySkuName { - return []NatGatewaySkuName{NatGatewaySkuNameStandard} -} - -// NextHopType enumerates the values for next hop type. -type NextHopType string - -const ( - // NextHopTypeHyperNetGateway ... - NextHopTypeHyperNetGateway NextHopType = "HyperNetGateway" - // NextHopTypeInternet ... - NextHopTypeInternet NextHopType = "Internet" - // NextHopTypeNone ... - NextHopTypeNone NextHopType = "None" - // NextHopTypeVirtualAppliance ... - NextHopTypeVirtualAppliance NextHopType = "VirtualAppliance" - // NextHopTypeVirtualNetworkGateway ... - NextHopTypeVirtualNetworkGateway NextHopType = "VirtualNetworkGateway" - // NextHopTypeVnetLocal ... - NextHopTypeVnetLocal NextHopType = "VnetLocal" -) - -// PossibleNextHopTypeValues returns an array of possible values for the NextHopType const type. -func PossibleNextHopTypeValues() []NextHopType { - return []NextHopType{NextHopTypeHyperNetGateway, NextHopTypeInternet, NextHopTypeNone, NextHopTypeVirtualAppliance, NextHopTypeVirtualNetworkGateway, NextHopTypeVnetLocal} -} - -// NextStep enumerates the values for next step. -type NextStep string - -const ( - // NextStepContinue ... - NextStepContinue NextStep = "Continue" - // NextStepTerminate ... - NextStepTerminate NextStep = "Terminate" - // NextStepUnknown ... - NextStepUnknown NextStep = "Unknown" -) - -// PossibleNextStepValues returns an array of possible values for the NextStep const type. -func PossibleNextStepValues() []NextStep { - return []NextStep{NextStepContinue, NextStepTerminate, NextStepUnknown} -} - -// OfficeTrafficCategory enumerates the values for office traffic category. -type OfficeTrafficCategory string - -const ( - // OfficeTrafficCategoryAll ... - OfficeTrafficCategoryAll OfficeTrafficCategory = "All" - // OfficeTrafficCategoryNone ... - OfficeTrafficCategoryNone OfficeTrafficCategory = "None" - // OfficeTrafficCategoryOptimize ... - OfficeTrafficCategoryOptimize OfficeTrafficCategory = "Optimize" - // OfficeTrafficCategoryOptimizeAndAllow ... - OfficeTrafficCategoryOptimizeAndAllow OfficeTrafficCategory = "OptimizeAndAllow" -) - -// PossibleOfficeTrafficCategoryValues returns an array of possible values for the OfficeTrafficCategory const type. -func PossibleOfficeTrafficCategoryValues() []OfficeTrafficCategory { - return []OfficeTrafficCategory{OfficeTrafficCategoryAll, OfficeTrafficCategoryNone, OfficeTrafficCategoryOptimize, OfficeTrafficCategoryOptimizeAndAllow} -} - -// OperationStatus enumerates the values for operation status. -type OperationStatus string - -const ( - // OperationStatusFailed ... - OperationStatusFailed OperationStatus = "Failed" - // OperationStatusInProgress ... - OperationStatusInProgress OperationStatus = "InProgress" - // OperationStatusSucceeded ... - OperationStatusSucceeded OperationStatus = "Succeeded" -) - -// PossibleOperationStatusValues returns an array of possible values for the OperationStatus const type. -func PossibleOperationStatusValues() []OperationStatus { - return []OperationStatus{OperationStatusFailed, OperationStatusInProgress, OperationStatusSucceeded} -} - -// Origin enumerates the values for origin. -type Origin string - -const ( - // OriginInbound ... - OriginInbound Origin = "Inbound" - // OriginLocal ... - OriginLocal Origin = "Local" - // OriginOutbound ... - OriginOutbound Origin = "Outbound" -) - -// PossibleOriginValues returns an array of possible values for the Origin const type. -func PossibleOriginValues() []Origin { - return []Origin{OriginInbound, OriginLocal, OriginOutbound} -} - -// OutputType enumerates the values for output type. -type OutputType string - -const ( - // Workspace ... - Workspace OutputType = "Workspace" -) - -// PossibleOutputTypeValues returns an array of possible values for the OutputType const type. -func PossibleOutputTypeValues() []OutputType { - return []OutputType{Workspace} -} - -// OwaspCrsExclusionEntryMatchVariable enumerates the values for owasp crs exclusion entry match variable. -type OwaspCrsExclusionEntryMatchVariable string - -const ( - // RequestArgKeys ... - RequestArgKeys OwaspCrsExclusionEntryMatchVariable = "RequestArgKeys" - // RequestArgNames ... - RequestArgNames OwaspCrsExclusionEntryMatchVariable = "RequestArgNames" - // RequestArgValues ... - RequestArgValues OwaspCrsExclusionEntryMatchVariable = "RequestArgValues" - // RequestCookieKeys ... - RequestCookieKeys OwaspCrsExclusionEntryMatchVariable = "RequestCookieKeys" - // RequestCookieNames ... - RequestCookieNames OwaspCrsExclusionEntryMatchVariable = "RequestCookieNames" - // RequestCookieValues ... - RequestCookieValues OwaspCrsExclusionEntryMatchVariable = "RequestCookieValues" - // RequestHeaderKeys ... - RequestHeaderKeys OwaspCrsExclusionEntryMatchVariable = "RequestHeaderKeys" - // RequestHeaderNames ... - RequestHeaderNames OwaspCrsExclusionEntryMatchVariable = "RequestHeaderNames" - // RequestHeaderValues ... - RequestHeaderValues OwaspCrsExclusionEntryMatchVariable = "RequestHeaderValues" -) - -// PossibleOwaspCrsExclusionEntryMatchVariableValues returns an array of possible values for the OwaspCrsExclusionEntryMatchVariable const type. -func PossibleOwaspCrsExclusionEntryMatchVariableValues() []OwaspCrsExclusionEntryMatchVariable { - return []OwaspCrsExclusionEntryMatchVariable{RequestArgKeys, RequestArgNames, RequestArgValues, RequestCookieKeys, RequestCookieNames, RequestCookieValues, RequestHeaderKeys, RequestHeaderNames, RequestHeaderValues} -} - -// OwaspCrsExclusionEntrySelectorMatchOperator enumerates the values for owasp crs exclusion entry selector -// match operator. -type OwaspCrsExclusionEntrySelectorMatchOperator string - -const ( - // OwaspCrsExclusionEntrySelectorMatchOperatorContains ... - OwaspCrsExclusionEntrySelectorMatchOperatorContains OwaspCrsExclusionEntrySelectorMatchOperator = "Contains" - // OwaspCrsExclusionEntrySelectorMatchOperatorEndsWith ... - OwaspCrsExclusionEntrySelectorMatchOperatorEndsWith OwaspCrsExclusionEntrySelectorMatchOperator = "EndsWith" - // OwaspCrsExclusionEntrySelectorMatchOperatorEquals ... - OwaspCrsExclusionEntrySelectorMatchOperatorEquals OwaspCrsExclusionEntrySelectorMatchOperator = "Equals" - // OwaspCrsExclusionEntrySelectorMatchOperatorEqualsAny ... - OwaspCrsExclusionEntrySelectorMatchOperatorEqualsAny OwaspCrsExclusionEntrySelectorMatchOperator = "EqualsAny" - // OwaspCrsExclusionEntrySelectorMatchOperatorStartsWith ... - OwaspCrsExclusionEntrySelectorMatchOperatorStartsWith OwaspCrsExclusionEntrySelectorMatchOperator = "StartsWith" -) - -// PossibleOwaspCrsExclusionEntrySelectorMatchOperatorValues returns an array of possible values for the OwaspCrsExclusionEntrySelectorMatchOperator const type. -func PossibleOwaspCrsExclusionEntrySelectorMatchOperatorValues() []OwaspCrsExclusionEntrySelectorMatchOperator { - return []OwaspCrsExclusionEntrySelectorMatchOperator{OwaspCrsExclusionEntrySelectorMatchOperatorContains, OwaspCrsExclusionEntrySelectorMatchOperatorEndsWith, OwaspCrsExclusionEntrySelectorMatchOperatorEquals, OwaspCrsExclusionEntrySelectorMatchOperatorEqualsAny, OwaspCrsExclusionEntrySelectorMatchOperatorStartsWith} -} - -// PacketCaptureTargetType enumerates the values for packet capture target type. -type PacketCaptureTargetType string - -const ( - // PacketCaptureTargetTypeAzureVM ... - PacketCaptureTargetTypeAzureVM PacketCaptureTargetType = "AzureVM" - // PacketCaptureTargetTypeAzureVMSS ... - PacketCaptureTargetTypeAzureVMSS PacketCaptureTargetType = "AzureVMSS" -) - -// PossiblePacketCaptureTargetTypeValues returns an array of possible values for the PacketCaptureTargetType const type. -func PossiblePacketCaptureTargetTypeValues() []PacketCaptureTargetType { - return []PacketCaptureTargetType{PacketCaptureTargetTypeAzureVM, PacketCaptureTargetTypeAzureVMSS} -} - -// PcError enumerates the values for pc error. -type PcError string - -const ( - // AgentStopped ... - AgentStopped PcError = "AgentStopped" - // CaptureFailed ... - CaptureFailed PcError = "CaptureFailed" - // InternalError ... - InternalError PcError = "InternalError" - // LocalFileFailed ... - LocalFileFailed PcError = "LocalFileFailed" - // StorageFailed ... - StorageFailed PcError = "StorageFailed" -) - -// PossiblePcErrorValues returns an array of possible values for the PcError const type. -func PossiblePcErrorValues() []PcError { - return []PcError{AgentStopped, CaptureFailed, InternalError, LocalFileFailed, StorageFailed} -} - -// PcProtocol enumerates the values for pc protocol. -type PcProtocol string - -const ( - // PcProtocolAny ... - PcProtocolAny PcProtocol = "Any" - // PcProtocolTCP ... - PcProtocolTCP PcProtocol = "TCP" - // PcProtocolUDP ... - PcProtocolUDP PcProtocol = "UDP" -) - -// PossiblePcProtocolValues returns an array of possible values for the PcProtocol const type. -func PossiblePcProtocolValues() []PcProtocol { - return []PcProtocol{PcProtocolAny, PcProtocolTCP, PcProtocolUDP} -} - -// PcStatus enumerates the values for pc status. -type PcStatus string - -const ( - // PcStatusError ... - PcStatusError PcStatus = "Error" - // PcStatusNotStarted ... - PcStatusNotStarted PcStatus = "NotStarted" - // PcStatusRunning ... - PcStatusRunning PcStatus = "Running" - // PcStatusStopped ... - PcStatusStopped PcStatus = "Stopped" - // PcStatusUnknown ... - PcStatusUnknown PcStatus = "Unknown" -) - -// PossiblePcStatusValues returns an array of possible values for the PcStatus const type. -func PossiblePcStatusValues() []PcStatus { - return []PcStatus{PcStatusError, PcStatusNotStarted, PcStatusRunning, PcStatusStopped, PcStatusUnknown} -} - -// PfsGroup enumerates the values for pfs group. -type PfsGroup string - -const ( - // PfsGroupECP256 ... - PfsGroupECP256 PfsGroup = "ECP256" - // PfsGroupECP384 ... - PfsGroupECP384 PfsGroup = "ECP384" - // PfsGroupNone ... - PfsGroupNone PfsGroup = "None" - // PfsGroupPFS1 ... - PfsGroupPFS1 PfsGroup = "PFS1" - // PfsGroupPFS14 ... - PfsGroupPFS14 PfsGroup = "PFS14" - // PfsGroupPFS2 ... - PfsGroupPFS2 PfsGroup = "PFS2" - // PfsGroupPFS2048 ... - PfsGroupPFS2048 PfsGroup = "PFS2048" - // PfsGroupPFS24 ... - PfsGroupPFS24 PfsGroup = "PFS24" - // PfsGroupPFSMM ... - PfsGroupPFSMM PfsGroup = "PFSMM" -) - -// PossiblePfsGroupValues returns an array of possible values for the PfsGroup const type. -func PossiblePfsGroupValues() []PfsGroup { - return []PfsGroup{PfsGroupECP256, PfsGroupECP384, PfsGroupNone, PfsGroupPFS1, PfsGroupPFS14, PfsGroupPFS2, PfsGroupPFS2048, PfsGroupPFS24, PfsGroupPFSMM} -} - -// PreferredIPVersion enumerates the values for preferred ip version. -type PreferredIPVersion string - -const ( - // PreferredIPVersionIPv4 ... - PreferredIPVersionIPv4 PreferredIPVersion = "IPv4" - // PreferredIPVersionIPv6 ... - PreferredIPVersionIPv6 PreferredIPVersion = "IPv6" -) - -// PossiblePreferredIPVersionValues returns an array of possible values for the PreferredIPVersion const type. -func PossiblePreferredIPVersionValues() []PreferredIPVersion { - return []PreferredIPVersion{PreferredIPVersionIPv4, PreferredIPVersionIPv6} -} - -// PreferredRoutingGateway enumerates the values for preferred routing gateway. -type PreferredRoutingGateway string - -const ( - // PreferredRoutingGatewayExpressRoute ... - PreferredRoutingGatewayExpressRoute PreferredRoutingGateway = "ExpressRoute" - // PreferredRoutingGatewayNone ... - PreferredRoutingGatewayNone PreferredRoutingGateway = "None" - // PreferredRoutingGatewayVpnGateway ... - PreferredRoutingGatewayVpnGateway PreferredRoutingGateway = "VpnGateway" -) - -// PossiblePreferredRoutingGatewayValues returns an array of possible values for the PreferredRoutingGateway const type. -func PossiblePreferredRoutingGatewayValues() []PreferredRoutingGateway { - return []PreferredRoutingGateway{PreferredRoutingGatewayExpressRoute, PreferredRoutingGatewayNone, PreferredRoutingGatewayVpnGateway} -} - -// ProbeProtocol enumerates the values for probe protocol. -type ProbeProtocol string - -const ( - // ProbeProtocolHTTP ... - ProbeProtocolHTTP ProbeProtocol = "Http" - // ProbeProtocolHTTPS ... - ProbeProtocolHTTPS ProbeProtocol = "Https" - // ProbeProtocolTCP ... - ProbeProtocolTCP ProbeProtocol = "Tcp" -) - -// PossibleProbeProtocolValues returns an array of possible values for the ProbeProtocol const type. -func PossibleProbeProtocolValues() []ProbeProtocol { - return []ProbeProtocol{ProbeProtocolHTTP, ProbeProtocolHTTPS, ProbeProtocolTCP} -} - -// ProcessorArchitecture enumerates the values for processor architecture. -type ProcessorArchitecture string - -const ( - // Amd64 ... - Amd64 ProcessorArchitecture = "Amd64" - // X86 ... - X86 ProcessorArchitecture = "X86" -) - -// PossibleProcessorArchitectureValues returns an array of possible values for the ProcessorArchitecture const type. -func PossibleProcessorArchitectureValues() []ProcessorArchitecture { - return []ProcessorArchitecture{Amd64, X86} -} - -// Protocol enumerates the values for protocol. -type Protocol string - -const ( - // ProtocolHTTP ... - ProtocolHTTP Protocol = "Http" - // ProtocolHTTPS ... - ProtocolHTTPS Protocol = "Https" - // ProtocolIcmp ... - ProtocolIcmp Protocol = "Icmp" - // ProtocolTCP ... - ProtocolTCP Protocol = "Tcp" -) - -// PossibleProtocolValues returns an array of possible values for the Protocol const type. -func PossibleProtocolValues() []Protocol { - return []Protocol{ProtocolHTTP, ProtocolHTTPS, ProtocolIcmp, ProtocolTCP} -} - -// ProtocolType enumerates the values for protocol type. -type ProtocolType string - -const ( - // ProtocolTypeAh ... - ProtocolTypeAh ProtocolType = "Ah" - // ProtocolTypeAll ... - ProtocolTypeAll ProtocolType = "All" - // ProtocolTypeDoNotUse ... - ProtocolTypeDoNotUse ProtocolType = "DoNotUse" - // ProtocolTypeEsp ... - ProtocolTypeEsp ProtocolType = "Esp" - // ProtocolTypeGre ... - ProtocolTypeGre ProtocolType = "Gre" - // ProtocolTypeIcmp ... - ProtocolTypeIcmp ProtocolType = "Icmp" - // ProtocolTypeTCP ... - ProtocolTypeTCP ProtocolType = "Tcp" - // ProtocolTypeUDP ... - ProtocolTypeUDP ProtocolType = "Udp" - // ProtocolTypeVxlan ... - ProtocolTypeVxlan ProtocolType = "Vxlan" -) - -// PossibleProtocolTypeValues returns an array of possible values for the ProtocolType const type. -func PossibleProtocolTypeValues() []ProtocolType { - return []ProtocolType{ProtocolTypeAh, ProtocolTypeAll, ProtocolTypeDoNotUse, ProtocolTypeEsp, ProtocolTypeGre, ProtocolTypeIcmp, ProtocolTypeTCP, ProtocolTypeUDP, ProtocolTypeVxlan} -} - -// ProvisioningState enumerates the values for provisioning state. -type ProvisioningState string - -const ( - // ProvisioningStateDeleting ... - ProvisioningStateDeleting ProvisioningState = "Deleting" - // ProvisioningStateFailed ... - ProvisioningStateFailed ProvisioningState = "Failed" - // ProvisioningStateSucceeded ... - ProvisioningStateSucceeded ProvisioningState = "Succeeded" - // ProvisioningStateUpdating ... - ProvisioningStateUpdating ProvisioningState = "Updating" -) - -// PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type. -func PossibleProvisioningStateValues() []ProvisioningState { - return []ProvisioningState{ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateSucceeded, ProvisioningStateUpdating} -} - -// PublicIPAddressMigrationPhase enumerates the values for public ip address migration phase. -type PublicIPAddressMigrationPhase string - -const ( - // PublicIPAddressMigrationPhaseAbort ... - PublicIPAddressMigrationPhaseAbort PublicIPAddressMigrationPhase = "Abort" - // PublicIPAddressMigrationPhaseCommit ... - PublicIPAddressMigrationPhaseCommit PublicIPAddressMigrationPhase = "Commit" - // PublicIPAddressMigrationPhaseCommitted ... - PublicIPAddressMigrationPhaseCommitted PublicIPAddressMigrationPhase = "Committed" - // PublicIPAddressMigrationPhaseNone ... - PublicIPAddressMigrationPhaseNone PublicIPAddressMigrationPhase = "None" - // PublicIPAddressMigrationPhasePrepare ... - PublicIPAddressMigrationPhasePrepare PublicIPAddressMigrationPhase = "Prepare" -) - -// PossiblePublicIPAddressMigrationPhaseValues returns an array of possible values for the PublicIPAddressMigrationPhase const type. -func PossiblePublicIPAddressMigrationPhaseValues() []PublicIPAddressMigrationPhase { - return []PublicIPAddressMigrationPhase{PublicIPAddressMigrationPhaseAbort, PublicIPAddressMigrationPhaseCommit, PublicIPAddressMigrationPhaseCommitted, PublicIPAddressMigrationPhaseNone, PublicIPAddressMigrationPhasePrepare} -} - -// PublicIPAddressSkuName enumerates the values for public ip address sku name. -type PublicIPAddressSkuName string - -const ( - // PublicIPAddressSkuNameBasic ... - PublicIPAddressSkuNameBasic PublicIPAddressSkuName = "Basic" - // PublicIPAddressSkuNameStandard ... - PublicIPAddressSkuNameStandard PublicIPAddressSkuName = "Standard" -) - -// PossiblePublicIPAddressSkuNameValues returns an array of possible values for the PublicIPAddressSkuName const type. -func PossiblePublicIPAddressSkuNameValues() []PublicIPAddressSkuName { - return []PublicIPAddressSkuName{PublicIPAddressSkuNameBasic, PublicIPAddressSkuNameStandard} -} - -// PublicIPAddressSkuTier enumerates the values for public ip address sku tier. -type PublicIPAddressSkuTier string - -const ( - // PublicIPAddressSkuTierGlobal ... - PublicIPAddressSkuTierGlobal PublicIPAddressSkuTier = "Global" - // PublicIPAddressSkuTierRegional ... - PublicIPAddressSkuTierRegional PublicIPAddressSkuTier = "Regional" -) - -// PossiblePublicIPAddressSkuTierValues returns an array of possible values for the PublicIPAddressSkuTier const type. -func PossiblePublicIPAddressSkuTierValues() []PublicIPAddressSkuTier { - return []PublicIPAddressSkuTier{PublicIPAddressSkuTierGlobal, PublicIPAddressSkuTierRegional} -} - -// PublicIPPrefixSkuName enumerates the values for public ip prefix sku name. -type PublicIPPrefixSkuName string - -const ( - // PublicIPPrefixSkuNameStandard ... - PublicIPPrefixSkuNameStandard PublicIPPrefixSkuName = "Standard" -) - -// PossiblePublicIPPrefixSkuNameValues returns an array of possible values for the PublicIPPrefixSkuName const type. -func PossiblePublicIPPrefixSkuNameValues() []PublicIPPrefixSkuName { - return []PublicIPPrefixSkuName{PublicIPPrefixSkuNameStandard} -} - -// PublicIPPrefixSkuTier enumerates the values for public ip prefix sku tier. -type PublicIPPrefixSkuTier string - -const ( - // PublicIPPrefixSkuTierGlobal ... - PublicIPPrefixSkuTierGlobal PublicIPPrefixSkuTier = "Global" - // PublicIPPrefixSkuTierRegional ... - PublicIPPrefixSkuTierRegional PublicIPPrefixSkuTier = "Regional" -) - -// PossiblePublicIPPrefixSkuTierValues returns an array of possible values for the PublicIPPrefixSkuTier const type. -func PossiblePublicIPPrefixSkuTierValues() []PublicIPPrefixSkuTier { - return []PublicIPPrefixSkuTier{PublicIPPrefixSkuTierGlobal, PublicIPPrefixSkuTierRegional} -} - -// ResourceIdentityType enumerates the values for resource identity type. -type ResourceIdentityType string - -const ( - // ResourceIdentityTypeNone ... - ResourceIdentityTypeNone ResourceIdentityType = "None" - // ResourceIdentityTypeSystemAssigned ... - ResourceIdentityTypeSystemAssigned ResourceIdentityType = "SystemAssigned" - // ResourceIdentityTypeSystemAssignedUserAssigned ... - ResourceIdentityTypeSystemAssignedUserAssigned ResourceIdentityType = "SystemAssigned, UserAssigned" - // ResourceIdentityTypeUserAssigned ... - ResourceIdentityTypeUserAssigned ResourceIdentityType = "UserAssigned" -) - -// PossibleResourceIdentityTypeValues returns an array of possible values for the ResourceIdentityType const type. -func PossibleResourceIdentityTypeValues() []ResourceIdentityType { - return []ResourceIdentityType{ResourceIdentityTypeNone, ResourceIdentityTypeSystemAssigned, ResourceIdentityTypeSystemAssignedUserAssigned, ResourceIdentityTypeUserAssigned} -} - -// RouteMapActionType enumerates the values for route map action type. -type RouteMapActionType string - -const ( - // RouteMapActionTypeAdd ... - RouteMapActionTypeAdd RouteMapActionType = "Add" - // RouteMapActionTypeDrop ... - RouteMapActionTypeDrop RouteMapActionType = "Drop" - // RouteMapActionTypeRemove ... - RouteMapActionTypeRemove RouteMapActionType = "Remove" - // RouteMapActionTypeReplace ... - RouteMapActionTypeReplace RouteMapActionType = "Replace" - // RouteMapActionTypeUnknown ... - RouteMapActionTypeUnknown RouteMapActionType = "Unknown" -) - -// PossibleRouteMapActionTypeValues returns an array of possible values for the RouteMapActionType const type. -func PossibleRouteMapActionTypeValues() []RouteMapActionType { - return []RouteMapActionType{RouteMapActionTypeAdd, RouteMapActionTypeDrop, RouteMapActionTypeRemove, RouteMapActionTypeReplace, RouteMapActionTypeUnknown} -} - -// RouteMapMatchCondition enumerates the values for route map match condition. -type RouteMapMatchCondition string - -const ( - // RouteMapMatchConditionContains ... - RouteMapMatchConditionContains RouteMapMatchCondition = "Contains" - // RouteMapMatchConditionEquals ... - RouteMapMatchConditionEquals RouteMapMatchCondition = "Equals" - // RouteMapMatchConditionNotContains ... - RouteMapMatchConditionNotContains RouteMapMatchCondition = "NotContains" - // RouteMapMatchConditionNotEquals ... - RouteMapMatchConditionNotEquals RouteMapMatchCondition = "NotEquals" - // RouteMapMatchConditionUnknown ... - RouteMapMatchConditionUnknown RouteMapMatchCondition = "Unknown" -) - -// PossibleRouteMapMatchConditionValues returns an array of possible values for the RouteMapMatchCondition const type. -func PossibleRouteMapMatchConditionValues() []RouteMapMatchCondition { - return []RouteMapMatchCondition{RouteMapMatchConditionContains, RouteMapMatchConditionEquals, RouteMapMatchConditionNotContains, RouteMapMatchConditionNotEquals, RouteMapMatchConditionUnknown} -} - -// RouteNextHopType enumerates the values for route next hop type. -type RouteNextHopType string - -const ( - // RouteNextHopTypeInternet ... - RouteNextHopTypeInternet RouteNextHopType = "Internet" - // RouteNextHopTypeNone ... - RouteNextHopTypeNone RouteNextHopType = "None" - // RouteNextHopTypeVirtualAppliance ... - RouteNextHopTypeVirtualAppliance RouteNextHopType = "VirtualAppliance" - // RouteNextHopTypeVirtualNetworkGateway ... - RouteNextHopTypeVirtualNetworkGateway RouteNextHopType = "VirtualNetworkGateway" - // RouteNextHopTypeVnetLocal ... - RouteNextHopTypeVnetLocal RouteNextHopType = "VnetLocal" -) - -// PossibleRouteNextHopTypeValues returns an array of possible values for the RouteNextHopType const type. -func PossibleRouteNextHopTypeValues() []RouteNextHopType { - return []RouteNextHopType{RouteNextHopTypeInternet, RouteNextHopTypeNone, RouteNextHopTypeVirtualAppliance, RouteNextHopTypeVirtualNetworkGateway, RouteNextHopTypeVnetLocal} -} - -// RoutingState enumerates the values for routing state. -type RoutingState string - -const ( - // RoutingStateFailed ... - RoutingStateFailed RoutingState = "Failed" - // RoutingStateNone ... - RoutingStateNone RoutingState = "None" - // RoutingStateProvisioned ... - RoutingStateProvisioned RoutingState = "Provisioned" - // RoutingStateProvisioning ... - RoutingStateProvisioning RoutingState = "Provisioning" -) - -// PossibleRoutingStateValues returns an array of possible values for the RoutingState const type. -func PossibleRoutingStateValues() []RoutingState { - return []RoutingState{RoutingStateFailed, RoutingStateNone, RoutingStateProvisioned, RoutingStateProvisioning} -} - -// RuleCollectionType enumerates the values for rule collection type. -type RuleCollectionType string - -const ( - // RuleCollectionTypeFirewallPolicyFilterRuleCollection ... - RuleCollectionTypeFirewallPolicyFilterRuleCollection RuleCollectionType = "FirewallPolicyFilterRuleCollection" - // RuleCollectionTypeFirewallPolicyNatRuleCollection ... - RuleCollectionTypeFirewallPolicyNatRuleCollection RuleCollectionType = "FirewallPolicyNatRuleCollection" - // RuleCollectionTypeFirewallPolicyRuleCollection ... - RuleCollectionTypeFirewallPolicyRuleCollection RuleCollectionType = "FirewallPolicyRuleCollection" -) - -// PossibleRuleCollectionTypeValues returns an array of possible values for the RuleCollectionType const type. -func PossibleRuleCollectionTypeValues() []RuleCollectionType { - return []RuleCollectionType{RuleCollectionTypeFirewallPolicyFilterRuleCollection, RuleCollectionTypeFirewallPolicyNatRuleCollection, RuleCollectionTypeFirewallPolicyRuleCollection} -} - -// RuleType enumerates the values for rule type. -type RuleType string - -const ( - // RuleTypeApplicationRule ... - RuleTypeApplicationRule RuleType = "ApplicationRule" - // RuleTypeFirewallPolicyRule ... - RuleTypeFirewallPolicyRule RuleType = "FirewallPolicyRule" - // RuleTypeNatRule ... - RuleTypeNatRule RuleType = "NatRule" - // RuleTypeNetworkRule ... - RuleTypeNetworkRule RuleType = "NetworkRule" -) - -// PossibleRuleTypeValues returns an array of possible values for the RuleType const type. -func PossibleRuleTypeValues() []RuleType { - return []RuleType{RuleTypeApplicationRule, RuleTypeFirewallPolicyRule, RuleTypeNatRule, RuleTypeNetworkRule} -} - -// ScopeConnectionState enumerates the values for scope connection state. -type ScopeConnectionState string - -const ( - // ScopeConnectionStateConflict ... - ScopeConnectionStateConflict ScopeConnectionState = "Conflict" - // ScopeConnectionStateConnected ... - ScopeConnectionStateConnected ScopeConnectionState = "Connected" - // ScopeConnectionStatePending ... - ScopeConnectionStatePending ScopeConnectionState = "Pending" - // ScopeConnectionStateRejected ... - ScopeConnectionStateRejected ScopeConnectionState = "Rejected" - // ScopeConnectionStateRevoked ... - ScopeConnectionStateRevoked ScopeConnectionState = "Revoked" -) - -// PossibleScopeConnectionStateValues returns an array of possible values for the ScopeConnectionState const type. -func PossibleScopeConnectionStateValues() []ScopeConnectionState { - return []ScopeConnectionState{ScopeConnectionStateConflict, ScopeConnectionStateConnected, ScopeConnectionStatePending, ScopeConnectionStateRejected, ScopeConnectionStateRevoked} -} - -// SecurityConfigurationRuleAccess enumerates the values for security configuration rule access. -type SecurityConfigurationRuleAccess string - -const ( - // SecurityConfigurationRuleAccessAllow ... - SecurityConfigurationRuleAccessAllow SecurityConfigurationRuleAccess = "Allow" - // SecurityConfigurationRuleAccessAlwaysAllow ... - SecurityConfigurationRuleAccessAlwaysAllow SecurityConfigurationRuleAccess = "AlwaysAllow" - // SecurityConfigurationRuleAccessDeny ... - SecurityConfigurationRuleAccessDeny SecurityConfigurationRuleAccess = "Deny" -) - -// PossibleSecurityConfigurationRuleAccessValues returns an array of possible values for the SecurityConfigurationRuleAccess const type. -func PossibleSecurityConfigurationRuleAccessValues() []SecurityConfigurationRuleAccess { - return []SecurityConfigurationRuleAccess{SecurityConfigurationRuleAccessAllow, SecurityConfigurationRuleAccessAlwaysAllow, SecurityConfigurationRuleAccessDeny} -} - -// SecurityConfigurationRuleDirection enumerates the values for security configuration rule direction. -type SecurityConfigurationRuleDirection string - -const ( - // SecurityConfigurationRuleDirectionInbound ... - SecurityConfigurationRuleDirectionInbound SecurityConfigurationRuleDirection = "Inbound" - // SecurityConfigurationRuleDirectionOutbound ... - SecurityConfigurationRuleDirectionOutbound SecurityConfigurationRuleDirection = "Outbound" -) - -// PossibleSecurityConfigurationRuleDirectionValues returns an array of possible values for the SecurityConfigurationRuleDirection const type. -func PossibleSecurityConfigurationRuleDirectionValues() []SecurityConfigurationRuleDirection { - return []SecurityConfigurationRuleDirection{SecurityConfigurationRuleDirectionInbound, SecurityConfigurationRuleDirectionOutbound} -} - -// SecurityConfigurationRuleProtocol enumerates the values for security configuration rule protocol. -type SecurityConfigurationRuleProtocol string - -const ( - // SecurityConfigurationRuleProtocolAh ... - SecurityConfigurationRuleProtocolAh SecurityConfigurationRuleProtocol = "Ah" - // SecurityConfigurationRuleProtocolAny ... - SecurityConfigurationRuleProtocolAny SecurityConfigurationRuleProtocol = "Any" - // SecurityConfigurationRuleProtocolEsp ... - SecurityConfigurationRuleProtocolEsp SecurityConfigurationRuleProtocol = "Esp" - // SecurityConfigurationRuleProtocolIcmp ... - SecurityConfigurationRuleProtocolIcmp SecurityConfigurationRuleProtocol = "Icmp" - // SecurityConfigurationRuleProtocolTCP ... - SecurityConfigurationRuleProtocolTCP SecurityConfigurationRuleProtocol = "Tcp" - // SecurityConfigurationRuleProtocolUDP ... - SecurityConfigurationRuleProtocolUDP SecurityConfigurationRuleProtocol = "Udp" -) - -// PossibleSecurityConfigurationRuleProtocolValues returns an array of possible values for the SecurityConfigurationRuleProtocol const type. -func PossibleSecurityConfigurationRuleProtocolValues() []SecurityConfigurationRuleProtocol { - return []SecurityConfigurationRuleProtocol{SecurityConfigurationRuleProtocolAh, SecurityConfigurationRuleProtocolAny, SecurityConfigurationRuleProtocolEsp, SecurityConfigurationRuleProtocolIcmp, SecurityConfigurationRuleProtocolTCP, SecurityConfigurationRuleProtocolUDP} -} - -// SecurityPartnerProviderConnectionStatus enumerates the values for security partner provider connection -// status. -type SecurityPartnerProviderConnectionStatus string - -const ( - // SecurityPartnerProviderConnectionStatusConnected ... - SecurityPartnerProviderConnectionStatusConnected SecurityPartnerProviderConnectionStatus = "Connected" - // SecurityPartnerProviderConnectionStatusNotConnected ... - SecurityPartnerProviderConnectionStatusNotConnected SecurityPartnerProviderConnectionStatus = "NotConnected" - // SecurityPartnerProviderConnectionStatusPartiallyConnected ... - SecurityPartnerProviderConnectionStatusPartiallyConnected SecurityPartnerProviderConnectionStatus = "PartiallyConnected" - // SecurityPartnerProviderConnectionStatusUnknown ... - SecurityPartnerProviderConnectionStatusUnknown SecurityPartnerProviderConnectionStatus = "Unknown" -) - -// PossibleSecurityPartnerProviderConnectionStatusValues returns an array of possible values for the SecurityPartnerProviderConnectionStatus const type. -func PossibleSecurityPartnerProviderConnectionStatusValues() []SecurityPartnerProviderConnectionStatus { - return []SecurityPartnerProviderConnectionStatus{SecurityPartnerProviderConnectionStatusConnected, SecurityPartnerProviderConnectionStatusNotConnected, SecurityPartnerProviderConnectionStatusPartiallyConnected, SecurityPartnerProviderConnectionStatusUnknown} -} - -// SecurityProviderName enumerates the values for security provider name. -type SecurityProviderName string - -const ( - // Checkpoint ... - Checkpoint SecurityProviderName = "Checkpoint" - // IBoss ... - IBoss SecurityProviderName = "IBoss" - // ZScaler ... - ZScaler SecurityProviderName = "ZScaler" -) - -// PossibleSecurityProviderNameValues returns an array of possible values for the SecurityProviderName const type. -func PossibleSecurityProviderNameValues() []SecurityProviderName { - return []SecurityProviderName{Checkpoint, IBoss, ZScaler} -} - -// SecurityRuleAccess enumerates the values for security rule access. -type SecurityRuleAccess string - -const ( - // SecurityRuleAccessAllow ... - SecurityRuleAccessAllow SecurityRuleAccess = "Allow" - // SecurityRuleAccessDeny ... - SecurityRuleAccessDeny SecurityRuleAccess = "Deny" -) - -// PossibleSecurityRuleAccessValues returns an array of possible values for the SecurityRuleAccess const type. -func PossibleSecurityRuleAccessValues() []SecurityRuleAccess { - return []SecurityRuleAccess{SecurityRuleAccessAllow, SecurityRuleAccessDeny} -} - -// SecurityRuleDirection enumerates the values for security rule direction. -type SecurityRuleDirection string - -const ( - // SecurityRuleDirectionInbound ... - SecurityRuleDirectionInbound SecurityRuleDirection = "Inbound" - // SecurityRuleDirectionOutbound ... - SecurityRuleDirectionOutbound SecurityRuleDirection = "Outbound" -) - -// PossibleSecurityRuleDirectionValues returns an array of possible values for the SecurityRuleDirection const type. -func PossibleSecurityRuleDirectionValues() []SecurityRuleDirection { - return []SecurityRuleDirection{SecurityRuleDirectionInbound, SecurityRuleDirectionOutbound} -} - -// SecurityRuleProtocol enumerates the values for security rule protocol. -type SecurityRuleProtocol string - -const ( - // SecurityRuleProtocolAh ... - SecurityRuleProtocolAh SecurityRuleProtocol = "Ah" - // SecurityRuleProtocolAsterisk ... - SecurityRuleProtocolAsterisk SecurityRuleProtocol = "*" - // SecurityRuleProtocolEsp ... - SecurityRuleProtocolEsp SecurityRuleProtocol = "Esp" - // SecurityRuleProtocolIcmp ... - SecurityRuleProtocolIcmp SecurityRuleProtocol = "Icmp" - // SecurityRuleProtocolTCP ... - SecurityRuleProtocolTCP SecurityRuleProtocol = "Tcp" - // SecurityRuleProtocolUDP ... - SecurityRuleProtocolUDP SecurityRuleProtocol = "Udp" -) - -// PossibleSecurityRuleProtocolValues returns an array of possible values for the SecurityRuleProtocol const type. -func PossibleSecurityRuleProtocolValues() []SecurityRuleProtocol { - return []SecurityRuleProtocol{SecurityRuleProtocolAh, SecurityRuleProtocolAsterisk, SecurityRuleProtocolEsp, SecurityRuleProtocolIcmp, SecurityRuleProtocolTCP, SecurityRuleProtocolUDP} -} - -// ServiceProviderProvisioningState enumerates the values for service provider provisioning state. -type ServiceProviderProvisioningState string - -const ( - // ServiceProviderProvisioningStateDeprovisioning ... - ServiceProviderProvisioningStateDeprovisioning ServiceProviderProvisioningState = "Deprovisioning" - // ServiceProviderProvisioningStateNotProvisioned ... - ServiceProviderProvisioningStateNotProvisioned ServiceProviderProvisioningState = "NotProvisioned" - // ServiceProviderProvisioningStateProvisioned ... - ServiceProviderProvisioningStateProvisioned ServiceProviderProvisioningState = "Provisioned" - // ServiceProviderProvisioningStateProvisioning ... - ServiceProviderProvisioningStateProvisioning ServiceProviderProvisioningState = "Provisioning" -) - -// PossibleServiceProviderProvisioningStateValues returns an array of possible values for the ServiceProviderProvisioningState const type. -func PossibleServiceProviderProvisioningStateValues() []ServiceProviderProvisioningState { - return []ServiceProviderProvisioningState{ServiceProviderProvisioningStateDeprovisioning, ServiceProviderProvisioningStateNotProvisioned, ServiceProviderProvisioningStateProvisioned, ServiceProviderProvisioningStateProvisioning} -} - -// Severity enumerates the values for severity. -type Severity string - -const ( - // SeverityError ... - SeverityError Severity = "Error" - // SeverityWarning ... - SeverityWarning Severity = "Warning" -) - -// PossibleSeverityValues returns an array of possible values for the Severity const type. -func PossibleSeverityValues() []Severity { - return []Severity{SeverityError, SeverityWarning} -} - -// SlotType enumerates the values for slot type. -type SlotType string - -const ( - // Production ... - Production SlotType = "Production" - // Staging ... - Staging SlotType = "Staging" -) - -// PossibleSlotTypeValues returns an array of possible values for the SlotType const type. -func PossibleSlotTypeValues() []SlotType { - return []SlotType{Production, Staging} -} - -// SyncRemoteAddressSpace enumerates the values for sync remote address space. -type SyncRemoteAddressSpace string - -const ( - // SyncRemoteAddressSpaceTrue ... - SyncRemoteAddressSpaceTrue SyncRemoteAddressSpace = "true" -) - -// PossibleSyncRemoteAddressSpaceValues returns an array of possible values for the SyncRemoteAddressSpace const type. -func PossibleSyncRemoteAddressSpaceValues() []SyncRemoteAddressSpace { - return []SyncRemoteAddressSpace{SyncRemoteAddressSpaceTrue} -} - -// TransportProtocol enumerates the values for transport protocol. -type TransportProtocol string - -const ( - // TransportProtocolAll ... - TransportProtocolAll TransportProtocol = "All" - // TransportProtocolTCP ... - TransportProtocolTCP TransportProtocol = "Tcp" - // TransportProtocolUDP ... - TransportProtocolUDP TransportProtocol = "Udp" -) - -// PossibleTransportProtocolValues returns an array of possible values for the TransportProtocol const type. -func PossibleTransportProtocolValues() []TransportProtocol { - return []TransportProtocol{TransportProtocolAll, TransportProtocolTCP, TransportProtocolUDP} -} - -// TunnelConnectionStatus enumerates the values for tunnel connection status. -type TunnelConnectionStatus string - -const ( - // TunnelConnectionStatusConnected ... - TunnelConnectionStatusConnected TunnelConnectionStatus = "Connected" - // TunnelConnectionStatusConnecting ... - TunnelConnectionStatusConnecting TunnelConnectionStatus = "Connecting" - // TunnelConnectionStatusNotConnected ... - TunnelConnectionStatusNotConnected TunnelConnectionStatus = "NotConnected" - // TunnelConnectionStatusUnknown ... - TunnelConnectionStatusUnknown TunnelConnectionStatus = "Unknown" -) - -// PossibleTunnelConnectionStatusValues returns an array of possible values for the TunnelConnectionStatus const type. -func PossibleTunnelConnectionStatusValues() []TunnelConnectionStatus { - return []TunnelConnectionStatus{TunnelConnectionStatusConnected, TunnelConnectionStatusConnecting, TunnelConnectionStatusNotConnected, TunnelConnectionStatusUnknown} -} - -// UseHubGateway enumerates the values for use hub gateway. -type UseHubGateway string - -const ( - // UseHubGatewayFalse ... - UseHubGatewayFalse UseHubGateway = "False" - // UseHubGatewayTrue ... - UseHubGatewayTrue UseHubGateway = "True" -) - -// PossibleUseHubGatewayValues returns an array of possible values for the UseHubGateway const type. -func PossibleUseHubGatewayValues() []UseHubGateway { - return []UseHubGateway{UseHubGatewayFalse, UseHubGatewayTrue} -} - -// VerbosityLevel enumerates the values for verbosity level. -type VerbosityLevel string - -const ( - // VerbosityLevelFull ... - VerbosityLevelFull VerbosityLevel = "Full" - // VerbosityLevelMinimum ... - VerbosityLevelMinimum VerbosityLevel = "Minimum" - // VerbosityLevelNormal ... - VerbosityLevelNormal VerbosityLevel = "Normal" -) - -// PossibleVerbosityLevelValues returns an array of possible values for the VerbosityLevel const type. -func PossibleVerbosityLevelValues() []VerbosityLevel { - return []VerbosityLevel{VerbosityLevelFull, VerbosityLevelMinimum, VerbosityLevelNormal} -} - -// VirtualNetworkEncryptionEnforcement enumerates the values for virtual network encryption enforcement. -type VirtualNetworkEncryptionEnforcement string - -const ( - // AllowUnencrypted ... - AllowUnencrypted VirtualNetworkEncryptionEnforcement = "AllowUnencrypted" - // DropUnencrypted ... - DropUnencrypted VirtualNetworkEncryptionEnforcement = "DropUnencrypted" -) - -// PossibleVirtualNetworkEncryptionEnforcementValues returns an array of possible values for the VirtualNetworkEncryptionEnforcement const type. -func PossibleVirtualNetworkEncryptionEnforcementValues() []VirtualNetworkEncryptionEnforcement { - return []VirtualNetworkEncryptionEnforcement{AllowUnencrypted, DropUnencrypted} -} - -// VirtualNetworkGatewayConnectionMode enumerates the values for virtual network gateway connection mode. -type VirtualNetworkGatewayConnectionMode string - -const ( - // VirtualNetworkGatewayConnectionModeDefault ... - VirtualNetworkGatewayConnectionModeDefault VirtualNetworkGatewayConnectionMode = "Default" - // VirtualNetworkGatewayConnectionModeInitiatorOnly ... - VirtualNetworkGatewayConnectionModeInitiatorOnly VirtualNetworkGatewayConnectionMode = "InitiatorOnly" - // VirtualNetworkGatewayConnectionModeResponderOnly ... - VirtualNetworkGatewayConnectionModeResponderOnly VirtualNetworkGatewayConnectionMode = "ResponderOnly" -) - -// PossibleVirtualNetworkGatewayConnectionModeValues returns an array of possible values for the VirtualNetworkGatewayConnectionMode const type. -func PossibleVirtualNetworkGatewayConnectionModeValues() []VirtualNetworkGatewayConnectionMode { - return []VirtualNetworkGatewayConnectionMode{VirtualNetworkGatewayConnectionModeDefault, VirtualNetworkGatewayConnectionModeInitiatorOnly, VirtualNetworkGatewayConnectionModeResponderOnly} -} - -// VirtualNetworkGatewayConnectionProtocol enumerates the values for virtual network gateway connection -// protocol. -type VirtualNetworkGatewayConnectionProtocol string - -const ( - // IKEv1 ... - IKEv1 VirtualNetworkGatewayConnectionProtocol = "IKEv1" - // IKEv2 ... - IKEv2 VirtualNetworkGatewayConnectionProtocol = "IKEv2" -) - -// PossibleVirtualNetworkGatewayConnectionProtocolValues returns an array of possible values for the VirtualNetworkGatewayConnectionProtocol const type. -func PossibleVirtualNetworkGatewayConnectionProtocolValues() []VirtualNetworkGatewayConnectionProtocol { - return []VirtualNetworkGatewayConnectionProtocol{IKEv1, IKEv2} -} - -// VirtualNetworkGatewayConnectionStatus enumerates the values for virtual network gateway connection status. -type VirtualNetworkGatewayConnectionStatus string - -const ( - // VirtualNetworkGatewayConnectionStatusConnected ... - VirtualNetworkGatewayConnectionStatusConnected VirtualNetworkGatewayConnectionStatus = "Connected" - // VirtualNetworkGatewayConnectionStatusConnecting ... - VirtualNetworkGatewayConnectionStatusConnecting VirtualNetworkGatewayConnectionStatus = "Connecting" - // VirtualNetworkGatewayConnectionStatusNotConnected ... - VirtualNetworkGatewayConnectionStatusNotConnected VirtualNetworkGatewayConnectionStatus = "NotConnected" - // VirtualNetworkGatewayConnectionStatusUnknown ... - VirtualNetworkGatewayConnectionStatusUnknown VirtualNetworkGatewayConnectionStatus = "Unknown" -) - -// PossibleVirtualNetworkGatewayConnectionStatusValues returns an array of possible values for the VirtualNetworkGatewayConnectionStatus const type. -func PossibleVirtualNetworkGatewayConnectionStatusValues() []VirtualNetworkGatewayConnectionStatus { - return []VirtualNetworkGatewayConnectionStatus{VirtualNetworkGatewayConnectionStatusConnected, VirtualNetworkGatewayConnectionStatusConnecting, VirtualNetworkGatewayConnectionStatusNotConnected, VirtualNetworkGatewayConnectionStatusUnknown} -} - -// VirtualNetworkGatewayConnectionType enumerates the values for virtual network gateway connection type. -type VirtualNetworkGatewayConnectionType string - -const ( - // ExpressRoute ... - ExpressRoute VirtualNetworkGatewayConnectionType = "ExpressRoute" - // IPsec ... - IPsec VirtualNetworkGatewayConnectionType = "IPsec" - // Vnet2Vnet ... - Vnet2Vnet VirtualNetworkGatewayConnectionType = "Vnet2Vnet" - // VPNClient ... - VPNClient VirtualNetworkGatewayConnectionType = "VPNClient" -) - -// PossibleVirtualNetworkGatewayConnectionTypeValues returns an array of possible values for the VirtualNetworkGatewayConnectionType const type. -func PossibleVirtualNetworkGatewayConnectionTypeValues() []VirtualNetworkGatewayConnectionType { - return []VirtualNetworkGatewayConnectionType{ExpressRoute, IPsec, Vnet2Vnet, VPNClient} -} - -// VirtualNetworkGatewaySkuName enumerates the values for virtual network gateway sku name. -type VirtualNetworkGatewaySkuName string - -const ( - // VirtualNetworkGatewaySkuNameBasic ... - VirtualNetworkGatewaySkuNameBasic VirtualNetworkGatewaySkuName = "Basic" - // VirtualNetworkGatewaySkuNameErGw1AZ ... - VirtualNetworkGatewaySkuNameErGw1AZ VirtualNetworkGatewaySkuName = "ErGw1AZ" - // VirtualNetworkGatewaySkuNameErGw2AZ ... - VirtualNetworkGatewaySkuNameErGw2AZ VirtualNetworkGatewaySkuName = "ErGw2AZ" - // VirtualNetworkGatewaySkuNameErGw3AZ ... - VirtualNetworkGatewaySkuNameErGw3AZ VirtualNetworkGatewaySkuName = "ErGw3AZ" - // VirtualNetworkGatewaySkuNameHighPerformance ... - VirtualNetworkGatewaySkuNameHighPerformance VirtualNetworkGatewaySkuName = "HighPerformance" - // VirtualNetworkGatewaySkuNameStandard ... - VirtualNetworkGatewaySkuNameStandard VirtualNetworkGatewaySkuName = "Standard" - // VirtualNetworkGatewaySkuNameUltraPerformance ... - VirtualNetworkGatewaySkuNameUltraPerformance VirtualNetworkGatewaySkuName = "UltraPerformance" - // VirtualNetworkGatewaySkuNameVpnGw1 ... - VirtualNetworkGatewaySkuNameVpnGw1 VirtualNetworkGatewaySkuName = "VpnGw1" - // VirtualNetworkGatewaySkuNameVpnGw1AZ ... - VirtualNetworkGatewaySkuNameVpnGw1AZ VirtualNetworkGatewaySkuName = "VpnGw1AZ" - // VirtualNetworkGatewaySkuNameVpnGw2 ... - VirtualNetworkGatewaySkuNameVpnGw2 VirtualNetworkGatewaySkuName = "VpnGw2" - // VirtualNetworkGatewaySkuNameVpnGw2AZ ... - VirtualNetworkGatewaySkuNameVpnGw2AZ VirtualNetworkGatewaySkuName = "VpnGw2AZ" - // VirtualNetworkGatewaySkuNameVpnGw3 ... - VirtualNetworkGatewaySkuNameVpnGw3 VirtualNetworkGatewaySkuName = "VpnGw3" - // VirtualNetworkGatewaySkuNameVpnGw3AZ ... - VirtualNetworkGatewaySkuNameVpnGw3AZ VirtualNetworkGatewaySkuName = "VpnGw3AZ" - // VirtualNetworkGatewaySkuNameVpnGw4 ... - VirtualNetworkGatewaySkuNameVpnGw4 VirtualNetworkGatewaySkuName = "VpnGw4" - // VirtualNetworkGatewaySkuNameVpnGw4AZ ... - VirtualNetworkGatewaySkuNameVpnGw4AZ VirtualNetworkGatewaySkuName = "VpnGw4AZ" - // VirtualNetworkGatewaySkuNameVpnGw5 ... - VirtualNetworkGatewaySkuNameVpnGw5 VirtualNetworkGatewaySkuName = "VpnGw5" - // VirtualNetworkGatewaySkuNameVpnGw5AZ ... - VirtualNetworkGatewaySkuNameVpnGw5AZ VirtualNetworkGatewaySkuName = "VpnGw5AZ" -) - -// PossibleVirtualNetworkGatewaySkuNameValues returns an array of possible values for the VirtualNetworkGatewaySkuName const type. -func PossibleVirtualNetworkGatewaySkuNameValues() []VirtualNetworkGatewaySkuName { - return []VirtualNetworkGatewaySkuName{VirtualNetworkGatewaySkuNameBasic, VirtualNetworkGatewaySkuNameErGw1AZ, VirtualNetworkGatewaySkuNameErGw2AZ, VirtualNetworkGatewaySkuNameErGw3AZ, VirtualNetworkGatewaySkuNameHighPerformance, VirtualNetworkGatewaySkuNameStandard, VirtualNetworkGatewaySkuNameUltraPerformance, VirtualNetworkGatewaySkuNameVpnGw1, VirtualNetworkGatewaySkuNameVpnGw1AZ, VirtualNetworkGatewaySkuNameVpnGw2, VirtualNetworkGatewaySkuNameVpnGw2AZ, VirtualNetworkGatewaySkuNameVpnGw3, VirtualNetworkGatewaySkuNameVpnGw3AZ, VirtualNetworkGatewaySkuNameVpnGw4, VirtualNetworkGatewaySkuNameVpnGw4AZ, VirtualNetworkGatewaySkuNameVpnGw5, VirtualNetworkGatewaySkuNameVpnGw5AZ} -} - -// VirtualNetworkGatewaySkuTier enumerates the values for virtual network gateway sku tier. -type VirtualNetworkGatewaySkuTier string - -const ( - // VirtualNetworkGatewaySkuTierBasic ... - VirtualNetworkGatewaySkuTierBasic VirtualNetworkGatewaySkuTier = "Basic" - // VirtualNetworkGatewaySkuTierErGw1AZ ... - VirtualNetworkGatewaySkuTierErGw1AZ VirtualNetworkGatewaySkuTier = "ErGw1AZ" - // VirtualNetworkGatewaySkuTierErGw2AZ ... - VirtualNetworkGatewaySkuTierErGw2AZ VirtualNetworkGatewaySkuTier = "ErGw2AZ" - // VirtualNetworkGatewaySkuTierErGw3AZ ... - VirtualNetworkGatewaySkuTierErGw3AZ VirtualNetworkGatewaySkuTier = "ErGw3AZ" - // VirtualNetworkGatewaySkuTierHighPerformance ... - VirtualNetworkGatewaySkuTierHighPerformance VirtualNetworkGatewaySkuTier = "HighPerformance" - // VirtualNetworkGatewaySkuTierStandard ... - VirtualNetworkGatewaySkuTierStandard VirtualNetworkGatewaySkuTier = "Standard" - // VirtualNetworkGatewaySkuTierUltraPerformance ... - VirtualNetworkGatewaySkuTierUltraPerformance VirtualNetworkGatewaySkuTier = "UltraPerformance" - // VirtualNetworkGatewaySkuTierVpnGw1 ... - VirtualNetworkGatewaySkuTierVpnGw1 VirtualNetworkGatewaySkuTier = "VpnGw1" - // VirtualNetworkGatewaySkuTierVpnGw1AZ ... - VirtualNetworkGatewaySkuTierVpnGw1AZ VirtualNetworkGatewaySkuTier = "VpnGw1AZ" - // VirtualNetworkGatewaySkuTierVpnGw2 ... - VirtualNetworkGatewaySkuTierVpnGw2 VirtualNetworkGatewaySkuTier = "VpnGw2" - // VirtualNetworkGatewaySkuTierVpnGw2AZ ... - VirtualNetworkGatewaySkuTierVpnGw2AZ VirtualNetworkGatewaySkuTier = "VpnGw2AZ" - // VirtualNetworkGatewaySkuTierVpnGw3 ... - VirtualNetworkGatewaySkuTierVpnGw3 VirtualNetworkGatewaySkuTier = "VpnGw3" - // VirtualNetworkGatewaySkuTierVpnGw3AZ ... - VirtualNetworkGatewaySkuTierVpnGw3AZ VirtualNetworkGatewaySkuTier = "VpnGw3AZ" - // VirtualNetworkGatewaySkuTierVpnGw4 ... - VirtualNetworkGatewaySkuTierVpnGw4 VirtualNetworkGatewaySkuTier = "VpnGw4" - // VirtualNetworkGatewaySkuTierVpnGw4AZ ... - VirtualNetworkGatewaySkuTierVpnGw4AZ VirtualNetworkGatewaySkuTier = "VpnGw4AZ" - // VirtualNetworkGatewaySkuTierVpnGw5 ... - VirtualNetworkGatewaySkuTierVpnGw5 VirtualNetworkGatewaySkuTier = "VpnGw5" - // VirtualNetworkGatewaySkuTierVpnGw5AZ ... - VirtualNetworkGatewaySkuTierVpnGw5AZ VirtualNetworkGatewaySkuTier = "VpnGw5AZ" -) - -// PossibleVirtualNetworkGatewaySkuTierValues returns an array of possible values for the VirtualNetworkGatewaySkuTier const type. -func PossibleVirtualNetworkGatewaySkuTierValues() []VirtualNetworkGatewaySkuTier { - return []VirtualNetworkGatewaySkuTier{VirtualNetworkGatewaySkuTierBasic, VirtualNetworkGatewaySkuTierErGw1AZ, VirtualNetworkGatewaySkuTierErGw2AZ, VirtualNetworkGatewaySkuTierErGw3AZ, VirtualNetworkGatewaySkuTierHighPerformance, VirtualNetworkGatewaySkuTierStandard, VirtualNetworkGatewaySkuTierUltraPerformance, VirtualNetworkGatewaySkuTierVpnGw1, VirtualNetworkGatewaySkuTierVpnGw1AZ, VirtualNetworkGatewaySkuTierVpnGw2, VirtualNetworkGatewaySkuTierVpnGw2AZ, VirtualNetworkGatewaySkuTierVpnGw3, VirtualNetworkGatewaySkuTierVpnGw3AZ, VirtualNetworkGatewaySkuTierVpnGw4, VirtualNetworkGatewaySkuTierVpnGw4AZ, VirtualNetworkGatewaySkuTierVpnGw5, VirtualNetworkGatewaySkuTierVpnGw5AZ} -} - -// VirtualNetworkGatewayType enumerates the values for virtual network gateway type. -type VirtualNetworkGatewayType string - -const ( - // VirtualNetworkGatewayTypeExpressRoute ... - VirtualNetworkGatewayTypeExpressRoute VirtualNetworkGatewayType = "ExpressRoute" - // VirtualNetworkGatewayTypeLocalGateway ... - VirtualNetworkGatewayTypeLocalGateway VirtualNetworkGatewayType = "LocalGateway" - // VirtualNetworkGatewayTypeVpn ... - VirtualNetworkGatewayTypeVpn VirtualNetworkGatewayType = "Vpn" -) - -// PossibleVirtualNetworkGatewayTypeValues returns an array of possible values for the VirtualNetworkGatewayType const type. -func PossibleVirtualNetworkGatewayTypeValues() []VirtualNetworkGatewayType { - return []VirtualNetworkGatewayType{VirtualNetworkGatewayTypeExpressRoute, VirtualNetworkGatewayTypeLocalGateway, VirtualNetworkGatewayTypeVpn} -} - -// VirtualNetworkPeeringLevel enumerates the values for virtual network peering level. -type VirtualNetworkPeeringLevel string - -const ( - // FullyInSync ... - FullyInSync VirtualNetworkPeeringLevel = "FullyInSync" - // LocalAndRemoteNotInSync ... - LocalAndRemoteNotInSync VirtualNetworkPeeringLevel = "LocalAndRemoteNotInSync" - // LocalNotInSync ... - LocalNotInSync VirtualNetworkPeeringLevel = "LocalNotInSync" - // RemoteNotInSync ... - RemoteNotInSync VirtualNetworkPeeringLevel = "RemoteNotInSync" -) - -// PossibleVirtualNetworkPeeringLevelValues returns an array of possible values for the VirtualNetworkPeeringLevel const type. -func PossibleVirtualNetworkPeeringLevelValues() []VirtualNetworkPeeringLevel { - return []VirtualNetworkPeeringLevel{FullyInSync, LocalAndRemoteNotInSync, LocalNotInSync, RemoteNotInSync} -} - -// VirtualNetworkPeeringState enumerates the values for virtual network peering state. -type VirtualNetworkPeeringState string - -const ( - // VirtualNetworkPeeringStateConnected ... - VirtualNetworkPeeringStateConnected VirtualNetworkPeeringState = "Connected" - // VirtualNetworkPeeringStateDisconnected ... - VirtualNetworkPeeringStateDisconnected VirtualNetworkPeeringState = "Disconnected" - // VirtualNetworkPeeringStateInitiated ... - VirtualNetworkPeeringStateInitiated VirtualNetworkPeeringState = "Initiated" -) - -// PossibleVirtualNetworkPeeringStateValues returns an array of possible values for the VirtualNetworkPeeringState const type. -func PossibleVirtualNetworkPeeringStateValues() []VirtualNetworkPeeringState { - return []VirtualNetworkPeeringState{VirtualNetworkPeeringStateConnected, VirtualNetworkPeeringStateDisconnected, VirtualNetworkPeeringStateInitiated} -} - -// VirtualNetworkPrivateEndpointNetworkPolicies enumerates the values for virtual network private endpoint -// network policies. -type VirtualNetworkPrivateEndpointNetworkPolicies string - -const ( - // VirtualNetworkPrivateEndpointNetworkPoliciesDisabled ... - VirtualNetworkPrivateEndpointNetworkPoliciesDisabled VirtualNetworkPrivateEndpointNetworkPolicies = "Disabled" - // VirtualNetworkPrivateEndpointNetworkPoliciesEnabled ... - VirtualNetworkPrivateEndpointNetworkPoliciesEnabled VirtualNetworkPrivateEndpointNetworkPolicies = "Enabled" -) - -// PossibleVirtualNetworkPrivateEndpointNetworkPoliciesValues returns an array of possible values for the VirtualNetworkPrivateEndpointNetworkPolicies const type. -func PossibleVirtualNetworkPrivateEndpointNetworkPoliciesValues() []VirtualNetworkPrivateEndpointNetworkPolicies { - return []VirtualNetworkPrivateEndpointNetworkPolicies{VirtualNetworkPrivateEndpointNetworkPoliciesDisabled, VirtualNetworkPrivateEndpointNetworkPoliciesEnabled} -} - -// VirtualNetworkPrivateLinkServiceNetworkPolicies enumerates the values for virtual network private link -// service network policies. -type VirtualNetworkPrivateLinkServiceNetworkPolicies string - -const ( - // VirtualNetworkPrivateLinkServiceNetworkPoliciesDisabled ... - VirtualNetworkPrivateLinkServiceNetworkPoliciesDisabled VirtualNetworkPrivateLinkServiceNetworkPolicies = "Disabled" - // VirtualNetworkPrivateLinkServiceNetworkPoliciesEnabled ... - VirtualNetworkPrivateLinkServiceNetworkPoliciesEnabled VirtualNetworkPrivateLinkServiceNetworkPolicies = "Enabled" -) - -// PossibleVirtualNetworkPrivateLinkServiceNetworkPoliciesValues returns an array of possible values for the VirtualNetworkPrivateLinkServiceNetworkPolicies const type. -func PossibleVirtualNetworkPrivateLinkServiceNetworkPoliciesValues() []VirtualNetworkPrivateLinkServiceNetworkPolicies { - return []VirtualNetworkPrivateLinkServiceNetworkPolicies{VirtualNetworkPrivateLinkServiceNetworkPoliciesDisabled, VirtualNetworkPrivateLinkServiceNetworkPoliciesEnabled} -} - -// VirtualWanSecurityProviderType enumerates the values for virtual wan security provider type. -type VirtualWanSecurityProviderType string - -const ( - // External ... - External VirtualWanSecurityProviderType = "External" - // Native ... - Native VirtualWanSecurityProviderType = "Native" -) - -// PossibleVirtualWanSecurityProviderTypeValues returns an array of possible values for the VirtualWanSecurityProviderType const type. -func PossibleVirtualWanSecurityProviderTypeValues() []VirtualWanSecurityProviderType { - return []VirtualWanSecurityProviderType{External, Native} -} - -// VnetLocalRouteOverrideCriteria enumerates the values for vnet local route override criteria. -type VnetLocalRouteOverrideCriteria string - -const ( - // VnetLocalRouteOverrideCriteriaContains ... - VnetLocalRouteOverrideCriteriaContains VnetLocalRouteOverrideCriteria = "Contains" - // VnetLocalRouteOverrideCriteriaEqual ... - VnetLocalRouteOverrideCriteriaEqual VnetLocalRouteOverrideCriteria = "Equal" -) - -// PossibleVnetLocalRouteOverrideCriteriaValues returns an array of possible values for the VnetLocalRouteOverrideCriteria const type. -func PossibleVnetLocalRouteOverrideCriteriaValues() []VnetLocalRouteOverrideCriteria { - return []VnetLocalRouteOverrideCriteria{VnetLocalRouteOverrideCriteriaContains, VnetLocalRouteOverrideCriteriaEqual} -} - -// VpnAuthenticationType enumerates the values for vpn authentication type. -type VpnAuthenticationType string - -const ( - // AAD ... - AAD VpnAuthenticationType = "AAD" - // Certificate ... - Certificate VpnAuthenticationType = "Certificate" - // Radius ... - Radius VpnAuthenticationType = "Radius" -) - -// PossibleVpnAuthenticationTypeValues returns an array of possible values for the VpnAuthenticationType const type. -func PossibleVpnAuthenticationTypeValues() []VpnAuthenticationType { - return []VpnAuthenticationType{AAD, Certificate, Radius} -} - -// VpnClientProtocol enumerates the values for vpn client protocol. -type VpnClientProtocol string - -const ( - // IkeV2 ... - IkeV2 VpnClientProtocol = "IkeV2" - // OpenVPN ... - OpenVPN VpnClientProtocol = "OpenVPN" - // SSTP ... - SSTP VpnClientProtocol = "SSTP" -) - -// PossibleVpnClientProtocolValues returns an array of possible values for the VpnClientProtocol const type. -func PossibleVpnClientProtocolValues() []VpnClientProtocol { - return []VpnClientProtocol{IkeV2, OpenVPN, SSTP} -} - -// VpnConnectionStatus enumerates the values for vpn connection status. -type VpnConnectionStatus string - -const ( - // VpnConnectionStatusConnected ... - VpnConnectionStatusConnected VpnConnectionStatus = "Connected" - // VpnConnectionStatusConnecting ... - VpnConnectionStatusConnecting VpnConnectionStatus = "Connecting" - // VpnConnectionStatusNotConnected ... - VpnConnectionStatusNotConnected VpnConnectionStatus = "NotConnected" - // VpnConnectionStatusUnknown ... - VpnConnectionStatusUnknown VpnConnectionStatus = "Unknown" -) - -// PossibleVpnConnectionStatusValues returns an array of possible values for the VpnConnectionStatus const type. -func PossibleVpnConnectionStatusValues() []VpnConnectionStatus { - return []VpnConnectionStatus{VpnConnectionStatusConnected, VpnConnectionStatusConnecting, VpnConnectionStatusNotConnected, VpnConnectionStatusUnknown} -} - -// VpnGatewayGeneration enumerates the values for vpn gateway generation. -type VpnGatewayGeneration string - -const ( - // VpnGatewayGenerationGeneration1 ... - VpnGatewayGenerationGeneration1 VpnGatewayGeneration = "Generation1" - // VpnGatewayGenerationGeneration2 ... - VpnGatewayGenerationGeneration2 VpnGatewayGeneration = "Generation2" - // VpnGatewayGenerationNone ... - VpnGatewayGenerationNone VpnGatewayGeneration = "None" -) - -// PossibleVpnGatewayGenerationValues returns an array of possible values for the VpnGatewayGeneration const type. -func PossibleVpnGatewayGenerationValues() []VpnGatewayGeneration { - return []VpnGatewayGeneration{VpnGatewayGenerationGeneration1, VpnGatewayGenerationGeneration2, VpnGatewayGenerationNone} -} - -// VpnGatewayTunnelingProtocol enumerates the values for vpn gateway tunneling protocol. -type VpnGatewayTunnelingProtocol string - -const ( - // VpnGatewayTunnelingProtocolIkeV2 ... - VpnGatewayTunnelingProtocolIkeV2 VpnGatewayTunnelingProtocol = "IkeV2" - // VpnGatewayTunnelingProtocolOpenVPN ... - VpnGatewayTunnelingProtocolOpenVPN VpnGatewayTunnelingProtocol = "OpenVPN" -) - -// PossibleVpnGatewayTunnelingProtocolValues returns an array of possible values for the VpnGatewayTunnelingProtocol const type. -func PossibleVpnGatewayTunnelingProtocolValues() []VpnGatewayTunnelingProtocol { - return []VpnGatewayTunnelingProtocol{VpnGatewayTunnelingProtocolIkeV2, VpnGatewayTunnelingProtocolOpenVPN} -} - -// VpnLinkConnectionMode enumerates the values for vpn link connection mode. -type VpnLinkConnectionMode string - -const ( - // VpnLinkConnectionModeDefault ... - VpnLinkConnectionModeDefault VpnLinkConnectionMode = "Default" - // VpnLinkConnectionModeInitiatorOnly ... - VpnLinkConnectionModeInitiatorOnly VpnLinkConnectionMode = "InitiatorOnly" - // VpnLinkConnectionModeResponderOnly ... - VpnLinkConnectionModeResponderOnly VpnLinkConnectionMode = "ResponderOnly" -) - -// PossibleVpnLinkConnectionModeValues returns an array of possible values for the VpnLinkConnectionMode const type. -func PossibleVpnLinkConnectionModeValues() []VpnLinkConnectionMode { - return []VpnLinkConnectionMode{VpnLinkConnectionModeDefault, VpnLinkConnectionModeInitiatorOnly, VpnLinkConnectionModeResponderOnly} -} - -// VpnNatRuleMode enumerates the values for vpn nat rule mode. -type VpnNatRuleMode string - -const ( - // EgressSnat ... - EgressSnat VpnNatRuleMode = "EgressSnat" - // IngressSnat ... - IngressSnat VpnNatRuleMode = "IngressSnat" -) - -// PossibleVpnNatRuleModeValues returns an array of possible values for the VpnNatRuleMode const type. -func PossibleVpnNatRuleModeValues() []VpnNatRuleMode { - return []VpnNatRuleMode{EgressSnat, IngressSnat} -} - -// VpnNatRuleType enumerates the values for vpn nat rule type. -type VpnNatRuleType string - -const ( - // VpnNatRuleTypeDynamic ... - VpnNatRuleTypeDynamic VpnNatRuleType = "Dynamic" - // VpnNatRuleTypeStatic ... - VpnNatRuleTypeStatic VpnNatRuleType = "Static" -) - -// PossibleVpnNatRuleTypeValues returns an array of possible values for the VpnNatRuleType const type. -func PossibleVpnNatRuleTypeValues() []VpnNatRuleType { - return []VpnNatRuleType{VpnNatRuleTypeDynamic, VpnNatRuleTypeStatic} -} - -// VpnPolicyMemberAttributeType enumerates the values for vpn policy member attribute type. -type VpnPolicyMemberAttributeType string - -const ( - // AADGroupID ... - AADGroupID VpnPolicyMemberAttributeType = "AADGroupId" - // CertificateGroupID ... - CertificateGroupID VpnPolicyMemberAttributeType = "CertificateGroupId" - // RadiusAzureGroupID ... - RadiusAzureGroupID VpnPolicyMemberAttributeType = "RadiusAzureGroupId" -) - -// PossibleVpnPolicyMemberAttributeTypeValues returns an array of possible values for the VpnPolicyMemberAttributeType const type. -func PossibleVpnPolicyMemberAttributeTypeValues() []VpnPolicyMemberAttributeType { - return []VpnPolicyMemberAttributeType{AADGroupID, CertificateGroupID, RadiusAzureGroupID} -} - -// VpnType enumerates the values for vpn type. -type VpnType string - -const ( - // PolicyBased ... - PolicyBased VpnType = "PolicyBased" - // RouteBased ... - RouteBased VpnType = "RouteBased" -) - -// PossibleVpnTypeValues returns an array of possible values for the VpnType const type. -func PossibleVpnTypeValues() []VpnType { - return []VpnType{PolicyBased, RouteBased} -} - -// WebApplicationFirewallAction enumerates the values for web application firewall action. -type WebApplicationFirewallAction string - -const ( - // WebApplicationFirewallActionAllow ... - WebApplicationFirewallActionAllow WebApplicationFirewallAction = "Allow" - // WebApplicationFirewallActionBlock ... - WebApplicationFirewallActionBlock WebApplicationFirewallAction = "Block" - // WebApplicationFirewallActionLog ... - WebApplicationFirewallActionLog WebApplicationFirewallAction = "Log" -) - -// PossibleWebApplicationFirewallActionValues returns an array of possible values for the WebApplicationFirewallAction const type. -func PossibleWebApplicationFirewallActionValues() []WebApplicationFirewallAction { - return []WebApplicationFirewallAction{WebApplicationFirewallActionAllow, WebApplicationFirewallActionBlock, WebApplicationFirewallActionLog} -} - -// WebApplicationFirewallEnabledState enumerates the values for web application firewall enabled state. -type WebApplicationFirewallEnabledState string - -const ( - // WebApplicationFirewallEnabledStateDisabled ... - WebApplicationFirewallEnabledStateDisabled WebApplicationFirewallEnabledState = "Disabled" - // WebApplicationFirewallEnabledStateEnabled ... - WebApplicationFirewallEnabledStateEnabled WebApplicationFirewallEnabledState = "Enabled" -) - -// PossibleWebApplicationFirewallEnabledStateValues returns an array of possible values for the WebApplicationFirewallEnabledState const type. -func PossibleWebApplicationFirewallEnabledStateValues() []WebApplicationFirewallEnabledState { - return []WebApplicationFirewallEnabledState{WebApplicationFirewallEnabledStateDisabled, WebApplicationFirewallEnabledStateEnabled} -} - -// WebApplicationFirewallMatchVariable enumerates the values for web application firewall match variable. -type WebApplicationFirewallMatchVariable string - -const ( - // PostArgs ... - PostArgs WebApplicationFirewallMatchVariable = "PostArgs" - // QueryString ... - QueryString WebApplicationFirewallMatchVariable = "QueryString" - // RemoteAddr ... - RemoteAddr WebApplicationFirewallMatchVariable = "RemoteAddr" - // RequestBody ... - RequestBody WebApplicationFirewallMatchVariable = "RequestBody" - // RequestCookies ... - RequestCookies WebApplicationFirewallMatchVariable = "RequestCookies" - // RequestHeaders ... - RequestHeaders WebApplicationFirewallMatchVariable = "RequestHeaders" - // RequestMethod ... - RequestMethod WebApplicationFirewallMatchVariable = "RequestMethod" - // RequestURI ... - RequestURI WebApplicationFirewallMatchVariable = "RequestUri" -) - -// PossibleWebApplicationFirewallMatchVariableValues returns an array of possible values for the WebApplicationFirewallMatchVariable const type. -func PossibleWebApplicationFirewallMatchVariableValues() []WebApplicationFirewallMatchVariable { - return []WebApplicationFirewallMatchVariable{PostArgs, QueryString, RemoteAddr, RequestBody, RequestCookies, RequestHeaders, RequestMethod, RequestURI} -} - -// WebApplicationFirewallMode enumerates the values for web application firewall mode. -type WebApplicationFirewallMode string - -const ( - // WebApplicationFirewallModeDetection ... - WebApplicationFirewallModeDetection WebApplicationFirewallMode = "Detection" - // WebApplicationFirewallModePrevention ... - WebApplicationFirewallModePrevention WebApplicationFirewallMode = "Prevention" -) - -// PossibleWebApplicationFirewallModeValues returns an array of possible values for the WebApplicationFirewallMode const type. -func PossibleWebApplicationFirewallModeValues() []WebApplicationFirewallMode { - return []WebApplicationFirewallMode{WebApplicationFirewallModeDetection, WebApplicationFirewallModePrevention} -} - -// WebApplicationFirewallOperator enumerates the values for web application firewall operator. -type WebApplicationFirewallOperator string - -const ( - // WebApplicationFirewallOperatorAny ... - WebApplicationFirewallOperatorAny WebApplicationFirewallOperator = "Any" - // WebApplicationFirewallOperatorBeginsWith ... - WebApplicationFirewallOperatorBeginsWith WebApplicationFirewallOperator = "BeginsWith" - // WebApplicationFirewallOperatorContains ... - WebApplicationFirewallOperatorContains WebApplicationFirewallOperator = "Contains" - // WebApplicationFirewallOperatorEndsWith ... - WebApplicationFirewallOperatorEndsWith WebApplicationFirewallOperator = "EndsWith" - // WebApplicationFirewallOperatorEqual ... - WebApplicationFirewallOperatorEqual WebApplicationFirewallOperator = "Equal" - // WebApplicationFirewallOperatorGeoMatch ... - WebApplicationFirewallOperatorGeoMatch WebApplicationFirewallOperator = "GeoMatch" - // WebApplicationFirewallOperatorGreaterThan ... - WebApplicationFirewallOperatorGreaterThan WebApplicationFirewallOperator = "GreaterThan" - // WebApplicationFirewallOperatorGreaterThanOrEqual ... - WebApplicationFirewallOperatorGreaterThanOrEqual WebApplicationFirewallOperator = "GreaterThanOrEqual" - // WebApplicationFirewallOperatorIPMatch ... - WebApplicationFirewallOperatorIPMatch WebApplicationFirewallOperator = "IPMatch" - // WebApplicationFirewallOperatorLessThan ... - WebApplicationFirewallOperatorLessThan WebApplicationFirewallOperator = "LessThan" - // WebApplicationFirewallOperatorLessThanOrEqual ... - WebApplicationFirewallOperatorLessThanOrEqual WebApplicationFirewallOperator = "LessThanOrEqual" - // WebApplicationFirewallOperatorRegex ... - WebApplicationFirewallOperatorRegex WebApplicationFirewallOperator = "Regex" -) - -// PossibleWebApplicationFirewallOperatorValues returns an array of possible values for the WebApplicationFirewallOperator const type. -func PossibleWebApplicationFirewallOperatorValues() []WebApplicationFirewallOperator { - return []WebApplicationFirewallOperator{WebApplicationFirewallOperatorAny, WebApplicationFirewallOperatorBeginsWith, WebApplicationFirewallOperatorContains, WebApplicationFirewallOperatorEndsWith, WebApplicationFirewallOperatorEqual, WebApplicationFirewallOperatorGeoMatch, WebApplicationFirewallOperatorGreaterThan, WebApplicationFirewallOperatorGreaterThanOrEqual, WebApplicationFirewallOperatorIPMatch, WebApplicationFirewallOperatorLessThan, WebApplicationFirewallOperatorLessThanOrEqual, WebApplicationFirewallOperatorRegex} -} - -// WebApplicationFirewallPolicyResourceState enumerates the values for web application firewall policy resource -// state. -type WebApplicationFirewallPolicyResourceState string - -const ( - // WebApplicationFirewallPolicyResourceStateCreating ... - WebApplicationFirewallPolicyResourceStateCreating WebApplicationFirewallPolicyResourceState = "Creating" - // WebApplicationFirewallPolicyResourceStateDeleting ... - WebApplicationFirewallPolicyResourceStateDeleting WebApplicationFirewallPolicyResourceState = "Deleting" - // WebApplicationFirewallPolicyResourceStateDisabled ... - WebApplicationFirewallPolicyResourceStateDisabled WebApplicationFirewallPolicyResourceState = "Disabled" - // WebApplicationFirewallPolicyResourceStateDisabling ... - WebApplicationFirewallPolicyResourceStateDisabling WebApplicationFirewallPolicyResourceState = "Disabling" - // WebApplicationFirewallPolicyResourceStateEnabled ... - WebApplicationFirewallPolicyResourceStateEnabled WebApplicationFirewallPolicyResourceState = "Enabled" - // WebApplicationFirewallPolicyResourceStateEnabling ... - WebApplicationFirewallPolicyResourceStateEnabling WebApplicationFirewallPolicyResourceState = "Enabling" -) - -// PossibleWebApplicationFirewallPolicyResourceStateValues returns an array of possible values for the WebApplicationFirewallPolicyResourceState const type. -func PossibleWebApplicationFirewallPolicyResourceStateValues() []WebApplicationFirewallPolicyResourceState { - return []WebApplicationFirewallPolicyResourceState{WebApplicationFirewallPolicyResourceStateCreating, WebApplicationFirewallPolicyResourceStateDeleting, WebApplicationFirewallPolicyResourceStateDisabled, WebApplicationFirewallPolicyResourceStateDisabling, WebApplicationFirewallPolicyResourceStateEnabled, WebApplicationFirewallPolicyResourceStateEnabling} -} - -// WebApplicationFirewallRuleType enumerates the values for web application firewall rule type. -type WebApplicationFirewallRuleType string - -const ( - // WebApplicationFirewallRuleTypeInvalid ... - WebApplicationFirewallRuleTypeInvalid WebApplicationFirewallRuleType = "Invalid" - // WebApplicationFirewallRuleTypeMatchRule ... - WebApplicationFirewallRuleTypeMatchRule WebApplicationFirewallRuleType = "MatchRule" -) - -// PossibleWebApplicationFirewallRuleTypeValues returns an array of possible values for the WebApplicationFirewallRuleType const type. -func PossibleWebApplicationFirewallRuleTypeValues() []WebApplicationFirewallRuleType { - return []WebApplicationFirewallRuleType{WebApplicationFirewallRuleTypeInvalid, WebApplicationFirewallRuleTypeMatchRule} -} - -// WebApplicationFirewallTransform enumerates the values for web application firewall transform. -type WebApplicationFirewallTransform string - -const ( - // HTMLEntityDecode ... - HTMLEntityDecode WebApplicationFirewallTransform = "HtmlEntityDecode" - // Lowercase ... - Lowercase WebApplicationFirewallTransform = "Lowercase" - // RemoveNulls ... - RemoveNulls WebApplicationFirewallTransform = "RemoveNulls" - // Trim ... - Trim WebApplicationFirewallTransform = "Trim" - // Uppercase ... - Uppercase WebApplicationFirewallTransform = "Uppercase" - // URLDecode ... - URLDecode WebApplicationFirewallTransform = "UrlDecode" - // URLEncode ... - URLEncode WebApplicationFirewallTransform = "UrlEncode" -) - -// PossibleWebApplicationFirewallTransformValues returns an array of possible values for the WebApplicationFirewallTransform const type. -func PossibleWebApplicationFirewallTransformValues() []WebApplicationFirewallTransform { - return []WebApplicationFirewallTransform{HTMLEntityDecode, Lowercase, RemoveNulls, Trim, Uppercase, URLDecode, URLEncode} -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecircuitauthorizations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecircuitauthorizations.go deleted file mode 100644 index 41fdb49908..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecircuitauthorizations.go +++ /dev/null @@ -1,396 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteCircuitAuthorizationsClient is the network Client -type ExpressRouteCircuitAuthorizationsClient struct { - BaseClient -} - -// NewExpressRouteCircuitAuthorizationsClient creates an instance of the ExpressRouteCircuitAuthorizationsClient -// client. -func NewExpressRouteCircuitAuthorizationsClient(subscriptionID string) ExpressRouteCircuitAuthorizationsClient { - return NewExpressRouteCircuitAuthorizationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteCircuitAuthorizationsClientWithBaseURI creates an instance of the -// ExpressRouteCircuitAuthorizationsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewExpressRouteCircuitAuthorizationsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitAuthorizationsClient { - return ExpressRouteCircuitAuthorizationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates an authorization in the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// authorizationName - the name of the authorization. -// authorizationParameters - parameters supplied to the create or update express route circuit authorization -// operation. -func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization) (result ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitAuthorizationsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, circuitName, authorizationName, authorizationParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationName": autorest.Encode("path", authorizationName), - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - authorizationParameters.Etag = nil - authorizationParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters), - autorest.WithJSON(authorizationParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitAuthorization, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified authorization from the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// authorizationName - the name of the authorization. -func (client ExpressRouteCircuitAuthorizationsClient) Delete(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (result ExpressRouteCircuitAuthorizationsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitAuthorizationsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, circuitName, authorizationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteCircuitAuthorizationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationName": autorest.Encode("path", authorizationName), - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitAuthorizationsClient) DeleteSender(req *http.Request) (future ExpressRouteCircuitAuthorizationsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitAuthorizationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified authorization from the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// authorizationName - the name of the authorization. -func (client ExpressRouteCircuitAuthorizationsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (result ExpressRouteCircuitAuthorization, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitAuthorizationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, circuitName, authorizationName) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteCircuitAuthorizationsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string, authorizationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationName": autorest.Encode("path", authorizationName), - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitAuthorizationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitAuthorizationsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitAuthorization, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all authorizations in an express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the circuit. -func (client ExpressRouteCircuitAuthorizationsClient) List(ctx context.Context, resourceGroupName string, circuitName string) (result AuthorizationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitAuthorizationsClient.List") - defer func() { - sc := -1 - if result.alr.Response.Response != nil { - sc = result.alr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, circuitName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.alr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure sending request") - return - } - - result.alr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure responding to request") - return - } - if result.alr.hasNextLink() && result.alr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteCircuitAuthorizationsClient) ListPreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/authorizations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitAuthorizationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitAuthorizationsClient) ListResponder(resp *http.Response) (result AuthorizationListResult, err error) { - err = autorest.Respond( - resp, - 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 ExpressRouteCircuitAuthorizationsClient) listNextResults(ctx context.Context, lastResults AuthorizationListResult) (result AuthorizationListResult, err error) { - req, err := lastResults.authorizationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCircuitAuthorizationsClient) ListComplete(ctx context.Context, resourceGroupName string, circuitName string) (result AuthorizationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitAuthorizationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, circuitName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecircuitconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecircuitconnections.go deleted file mode 100644 index e9f8625d96..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecircuitconnections.go +++ /dev/null @@ -1,403 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteCircuitConnectionsClient is the network Client -type ExpressRouteCircuitConnectionsClient struct { - BaseClient -} - -// NewExpressRouteCircuitConnectionsClient creates an instance of the ExpressRouteCircuitConnectionsClient client. -func NewExpressRouteCircuitConnectionsClient(subscriptionID string) ExpressRouteCircuitConnectionsClient { - return NewExpressRouteCircuitConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteCircuitConnectionsClientWithBaseURI creates an instance of the ExpressRouteCircuitConnectionsClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewExpressRouteCircuitConnectionsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitConnectionsClient { - return ExpressRouteCircuitConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a Express Route Circuit Connection in the specified express route circuits. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// connectionName - the name of the express route circuit connection. -// expressRouteCircuitConnectionParameters - parameters supplied to the create or update express route circuit -// connection operation. -func (client ExpressRouteCircuitConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, expressRouteCircuitConnectionParameters ExpressRouteCircuitConnection) (result ExpressRouteCircuitConnectionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, circuitName, peeringName, connectionName, expressRouteCircuitConnectionParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCircuitConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string, expressRouteCircuitConnectionParameters ExpressRouteCircuitConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "connectionName": autorest.Encode("path", connectionName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - expressRouteCircuitConnectionParameters.Etag = nil - expressRouteCircuitConnectionParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}", pathParameters), - autorest.WithJSON(expressRouteCircuitConnectionParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitConnectionsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCircuitConnectionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified Express Route Circuit Connection from the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// connectionName - the name of the express route circuit connection. -func (client ExpressRouteCircuitConnectionsClient) Delete(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (result ExpressRouteCircuitConnectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, circuitName, peeringName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteCircuitConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "connectionName": autorest.Encode("path", connectionName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitConnectionsClient) DeleteSender(req *http.Request) (future ExpressRouteCircuitConnectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified Express Route Circuit Connection from the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// connectionName - the name of the express route circuit connection. -func (client ExpressRouteCircuitConnectionsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (result ExpressRouteCircuitConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, circuitName, peeringName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "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.ExpressRouteCircuitConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteCircuitConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "connectionName": autorest.Encode("path", connectionName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitConnectionsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all global reach connections associated with a private peering in an express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the circuit. -// peeringName - the name of the peering. -func (client ExpressRouteCircuitConnectionsClient) List(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionsClient.List") - defer func() { - sc := -1 - if result.ercclr.Response.Response != nil { - sc = result.ercclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, circuitName, peeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ercclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.ercclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.ercclr.hasNextLink() && result.ercclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteCircuitConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/peerings/{peeringName}/connections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitConnectionsClient) ListResponder(resp *http.Response) (result ExpressRouteCircuitConnectionListResult, err error) { - err = autorest.Respond( - resp, - 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 ExpressRouteCircuitConnectionsClient) listNextResults(ctx context.Context, lastResults ExpressRouteCircuitConnectionListResult) (result ExpressRouteCircuitConnectionListResult, err error) { - req, err := lastResults.expressRouteCircuitConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCircuitConnectionsClient) ListComplete(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, circuitName, peeringName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecircuitpeerings.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecircuitpeerings.go deleted file mode 100644 index 8e3012a166..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecircuitpeerings.go +++ /dev/null @@ -1,406 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteCircuitPeeringsClient is the network Client -type ExpressRouteCircuitPeeringsClient struct { - BaseClient -} - -// NewExpressRouteCircuitPeeringsClient creates an instance of the ExpressRouteCircuitPeeringsClient client. -func NewExpressRouteCircuitPeeringsClient(subscriptionID string) ExpressRouteCircuitPeeringsClient { - return NewExpressRouteCircuitPeeringsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteCircuitPeeringsClientWithBaseURI creates an instance of the ExpressRouteCircuitPeeringsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewExpressRouteCircuitPeeringsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitPeeringsClient { - return ExpressRouteCircuitPeeringsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a peering in the specified express route circuits. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// peeringParameters - parameters supplied to the create or update express route circuit peering operation. -func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering) (result ExpressRouteCircuitPeeringsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: peeringParameters, - Constraints: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCircuitPeeringPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCircuitPeeringPropertiesFormat.PeerASN", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCircuitPeeringPropertiesFormat.PeerASN", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "peeringParameters.ExpressRouteCircuitPeeringPropertiesFormat.PeerASN", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, circuitName, peeringName, peeringParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - peeringParameters.Etag = nil - peeringParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters), - autorest.WithJSON(peeringParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCircuitPeeringsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified peering from the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -func (client ExpressRouteCircuitPeeringsClient) Delete(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitPeeringsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, circuitName, peeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteCircuitPeeringsClient) DeletePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitPeeringsClient) DeleteSender(req *http.Request) (future ExpressRouteCircuitPeeringsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitPeeringsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified peering for the express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -func (client ExpressRouteCircuitPeeringsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitPeering, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, circuitName, peeringName) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteCircuitPeeringsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitPeeringsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitPeeringsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all peerings in a specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -func (client ExpressRouteCircuitPeeringsClient) List(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuitPeeringListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringsClient.List") - defer func() { - sc := -1 - if result.ercplr.Response.Response != nil { - sc = result.ercplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, circuitName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ercplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure sending request") - return - } - - result.ercplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure responding to request") - return - } - if result.ercplr.hasNextLink() && result.ercplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteCircuitPeeringsClient) ListPreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/peerings", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitPeeringsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitPeeringsClient) ListResponder(resp *http.Response) (result ExpressRouteCircuitPeeringListResult, err error) { - err = autorest.Respond( - resp, - 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 ExpressRouteCircuitPeeringsClient) listNextResults(ctx context.Context, lastResults ExpressRouteCircuitPeeringListResult) (result ExpressRouteCircuitPeeringListResult, err error) { - req, err := lastResults.expressRouteCircuitPeeringListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCircuitPeeringsClient) ListComplete(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuitPeeringListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, circuitName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecircuits.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecircuits.go deleted file mode 100644 index 6bf7737c2c..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecircuits.go +++ /dev/null @@ -1,982 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteCircuitsClient is the network Client -type ExpressRouteCircuitsClient struct { - BaseClient -} - -// NewExpressRouteCircuitsClient creates an instance of the ExpressRouteCircuitsClient client. -func NewExpressRouteCircuitsClient(subscriptionID string) ExpressRouteCircuitsClient { - return NewExpressRouteCircuitsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteCircuitsClientWithBaseURI creates an instance of the ExpressRouteCircuitsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewExpressRouteCircuitsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitsClient { - return ExpressRouteCircuitsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates an express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the circuit. -// parameters - parameters supplied to the create or update express route circuit operation. -func (client ExpressRouteCircuitsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, circuitName string, parameters ExpressRouteCircuit) (result ExpressRouteCircuitsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, circuitName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCircuitsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, circuitName string, parameters ExpressRouteCircuit) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCircuitsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuit, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -func (client ExpressRouteCircuitsClient) Delete(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuitsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, circuitName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteCircuitsClient) DeletePreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) DeleteSender(req *http.Request) (future ExpressRouteCircuitsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets information about the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of express route circuit. -func (client ExpressRouteCircuitsClient) Get(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuit, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, circuitName) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteCircuitsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuit, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetPeeringStats gets all stats from an express route circuit in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -func (client ExpressRouteCircuitsClient) GetPeeringStats(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitStats, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.GetPeeringStats") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPeeringStatsPreparer(ctx, resourceGroupName, circuitName, peeringName) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", resp, "Failure sending request") - return - } - - result, err = client.GetPeeringStatsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", resp, "Failure responding to request") - return - } - - return -} - -// GetPeeringStatsPreparer prepares the GetPeeringStats request. -func (client ExpressRouteCircuitsClient) GetPeeringStatsPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/peerings/{peeringName}/stats", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetPeeringStatsSender sends the GetPeeringStats request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) GetPeeringStatsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetPeeringStatsResponder handles the response to the GetPeeringStats request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) GetPeeringStatsResponder(resp *http.Response) (result ExpressRouteCircuitStats, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetStats gets all the stats from an express route circuit in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -func (client ExpressRouteCircuitsClient) GetStats(ctx context.Context, resourceGroupName string, circuitName string) (result ExpressRouteCircuitStats, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.GetStats") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetStatsPreparer(ctx, resourceGroupName, circuitName) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", resp, "Failure sending request") - return - } - - result, err = client.GetStatsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", resp, "Failure responding to request") - return - } - - return -} - -// GetStatsPreparer prepares the GetStats request. -func (client ExpressRouteCircuitsClient) GetStatsPreparer(ctx context.Context, resourceGroupName string, circuitName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/stats", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetStatsSender sends the GetStats request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) GetStatsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetStatsResponder handles the response to the GetStats request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) GetStatsResponder(resp *http.Response) (result ExpressRouteCircuitStats, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the express route circuits in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ExpressRouteCircuitsClient) List(ctx context.Context, resourceGroupName string) (result ExpressRouteCircuitListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.List") - defer func() { - sc := -1 - if result.erclr.Response.Response != nil { - sc = result.erclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.erclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure sending request") - return - } - - result.erclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure responding to request") - return - } - if result.erclr.hasNextLink() && result.erclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteCircuitsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) ListResponder(resp *http.Response) (result ExpressRouteCircuitListResult, err error) { - err = autorest.Respond( - resp, - 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 ExpressRouteCircuitsClient) listNextResults(ctx context.Context, lastResults ExpressRouteCircuitListResult) (result ExpressRouteCircuitListResult, err error) { - req, err := lastResults.expressRouteCircuitListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCircuitsClient) ListComplete(ctx context.Context, resourceGroupName string) (result ExpressRouteCircuitListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the express route circuits in a subscription. -func (client ExpressRouteCircuitsClient) ListAll(ctx context.Context) (result ExpressRouteCircuitListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.ListAll") - defer func() { - sc := -1 - if result.erclr.Response.Response != nil { - sc = result.erclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.erclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure sending request") - return - } - - result.erclr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure responding to request") - return - } - if result.erclr.hasNextLink() && result.erclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client ExpressRouteCircuitsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteCircuits", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) ListAllResponder(resp *http.Response) (result ExpressRouteCircuitListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client ExpressRouteCircuitsClient) listAllNextResults(ctx context.Context, lastResults ExpressRouteCircuitListResult) (result ExpressRouteCircuitListResult, err error) { - req, err := lastResults.expressRouteCircuitListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCircuitsClient) ListAllComplete(ctx context.Context) (result ExpressRouteCircuitListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListArpTable gets the currently advertised ARP table associated with the express route circuit in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// devicePath - the path of the device. -func (client ExpressRouteCircuitsClient) ListArpTable(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (result ExpressRouteCircuitsListArpTableFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.ListArpTable") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListArpTablePreparer(ctx, resourceGroupName, circuitName, peeringName, devicePath) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", nil, "Failure preparing request") - return - } - - result, err = client.ListArpTableSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", result.Response(), "Failure sending request") - return - } - - return -} - -// ListArpTablePreparer prepares the ListArpTable request. -func (client ExpressRouteCircuitsClient) ListArpTablePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "devicePath": autorest.Encode("path", devicePath), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/peerings/{peeringName}/arpTables/{devicePath}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListArpTableSender sends the ListArpTable request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) ListArpTableSender(req *http.Request) (future ExpressRouteCircuitsListArpTableFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListArpTableResponder handles the response to the ListArpTable request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) ListArpTableResponder(resp *http.Response) (result ExpressRouteCircuitsArpTableListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListRoutesTable gets the currently advertised routes table associated with the express route circuit in a resource -// group. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// devicePath - the path of the device. -func (client ExpressRouteCircuitsClient) ListRoutesTable(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (result ExpressRouteCircuitsListRoutesTableFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.ListRoutesTable") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListRoutesTablePreparer(ctx, resourceGroupName, circuitName, peeringName, devicePath) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", nil, "Failure preparing request") - return - } - - result, err = client.ListRoutesTableSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", result.Response(), "Failure sending request") - return - } - - return -} - -// ListRoutesTablePreparer prepares the ListRoutesTable request. -func (client ExpressRouteCircuitsClient) ListRoutesTablePreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "devicePath": autorest.Encode("path", devicePath), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/peerings/{peeringName}/routeTables/{devicePath}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListRoutesTableSender sends the ListRoutesTable request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) ListRoutesTableSender(req *http.Request) (future ExpressRouteCircuitsListRoutesTableFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListRoutesTableResponder handles the response to the ListRoutesTable request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) ListRoutesTableResponder(resp *http.Response) (result ExpressRouteCircuitsRoutesTableListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListRoutesTableSummary gets the currently advertised routes table summary associated with the express route circuit -// in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// devicePath - the path of the device. -func (client ExpressRouteCircuitsClient) ListRoutesTableSummary(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (result ExpressRouteCircuitsListRoutesTableSummaryFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.ListRoutesTableSummary") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListRoutesTableSummaryPreparer(ctx, resourceGroupName, circuitName, peeringName, devicePath) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", nil, "Failure preparing request") - return - } - - result, err = client.ListRoutesTableSummarySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", result.Response(), "Failure sending request") - return - } - - return -} - -// ListRoutesTableSummaryPreparer prepares the ListRoutesTableSummary request. -func (client ExpressRouteCircuitsClient) ListRoutesTableSummaryPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, devicePath string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "devicePath": autorest.Encode("path", devicePath), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/peerings/{peeringName}/routeTablesSummary/{devicePath}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListRoutesTableSummarySender sends the ListRoutesTableSummary request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) ListRoutesTableSummarySender(req *http.Request) (future ExpressRouteCircuitsListRoutesTableSummaryFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListRoutesTableSummaryResponder handles the response to the ListRoutesTableSummary request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) ListRoutesTableSummaryResponder(resp *http.Response) (result ExpressRouteCircuitsRoutesTableSummaryListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates an express route circuit tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the circuit. -// parameters - parameters supplied to update express route circuit tags. -func (client ExpressRouteCircuitsClient) UpdateTags(ctx context.Context, resourceGroupName string, circuitName string, parameters TagsObject) (result ExpressRouteCircuit, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitsClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, circuitName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ExpressRouteCircuitsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, circuitName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCircuitsClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ExpressRouteCircuitsClient) UpdateTagsResponder(resp *http.Response) (result ExpressRouteCircuit, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteconnections.go deleted file mode 100644 index d033ecb9b8..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteconnections.go +++ /dev/null @@ -1,359 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteConnectionsClient is the network Client -type ExpressRouteConnectionsClient struct { - BaseClient -} - -// NewExpressRouteConnectionsClient creates an instance of the ExpressRouteConnectionsClient client. -func NewExpressRouteConnectionsClient(subscriptionID string) ExpressRouteConnectionsClient { - return NewExpressRouteConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteConnectionsClientWithBaseURI creates an instance of the ExpressRouteConnectionsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewExpressRouteConnectionsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteConnectionsClient { - return ExpressRouteConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a connection between an ExpressRoute gateway and an ExpressRoute circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -// connectionName - the name of the connection subresource. -// putExpressRouteConnectionParameters - parameters required in an ExpressRouteConnection PUT operation. -func (client ExpressRouteConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string, putExpressRouteConnectionParameters ExpressRouteConnection) (result ExpressRouteConnectionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: putExpressRouteConnectionParameters, - Constraints: []validation.Constraint{{Target: "putExpressRouteConnectionParameters.ExpressRouteConnectionProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "putExpressRouteConnectionParameters.ExpressRouteConnectionProperties.ExpressRouteCircuitPeering", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "putExpressRouteConnectionParameters.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.ExpressRouteConnectionsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, expressRouteGatewayName, connectionName, putExpressRouteConnectionParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string, putExpressRouteConnectionParameters ExpressRouteConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}/expressRouteConnections/{connectionName}", pathParameters), - autorest.WithJSON(putExpressRouteConnectionParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteConnectionsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteConnectionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a connection to a ExpressRoute circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -// connectionName - the name of the connection subresource. -func (client ExpressRouteConnectionsClient) Delete(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string) (result ExpressRouteConnectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteConnectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, expressRouteGatewayName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteGateways/{expressRouteGatewayName}/expressRouteConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteConnectionsClient) DeleteSender(req *http.Request) (future ExpressRouteConnectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified ExpressRouteConnection. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -// connectionName - the name of the ExpressRoute connection. -func (client ExpressRouteConnectionsClient) Get(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string) (result ExpressRouteConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, expressRouteGatewayName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "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.ExpressRouteConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteGateways/{expressRouteGatewayName}/expressRouteConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteConnectionsClient) GetResponder(resp *http.Response) (result ExpressRouteConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists ExpressRouteConnections. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -func (client ExpressRouteConnectionsClient) List(ctx context.Context, resourceGroupName string, expressRouteGatewayName string) (result ExpressRouteConnectionList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteConnectionsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, expressRouteGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "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.ExpressRouteConnectionsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteGateways/{expressRouteGatewayName}/expressRouteConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteConnectionsClient) ListResponder(resp *http.Response) (result ExpressRouteConnectionList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecrossconnectionpeerings.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecrossconnectionpeerings.go deleted file mode 100644 index ad4b71bd4e..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecrossconnectionpeerings.go +++ /dev/null @@ -1,407 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteCrossConnectionPeeringsClient is the network Client -type ExpressRouteCrossConnectionPeeringsClient struct { - BaseClient -} - -// NewExpressRouteCrossConnectionPeeringsClient creates an instance of the ExpressRouteCrossConnectionPeeringsClient -// client. -func NewExpressRouteCrossConnectionPeeringsClient(subscriptionID string) ExpressRouteCrossConnectionPeeringsClient { - return NewExpressRouteCrossConnectionPeeringsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteCrossConnectionPeeringsClientWithBaseURI creates an instance of the -// ExpressRouteCrossConnectionPeeringsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewExpressRouteCrossConnectionPeeringsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCrossConnectionPeeringsClient { - return ExpressRouteCrossConnectionPeeringsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a peering in the specified ExpressRouteCrossConnection. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// peeringName - the name of the peering. -// peeringParameters - parameters supplied to the create or update ExpressRouteCrossConnection peering -// operation. -func (client ExpressRouteCrossConnectionPeeringsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, peeringParameters ExpressRouteCrossConnectionPeering) (result ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: peeringParameters, - Constraints: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCrossConnectionPeeringProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCrossConnectionPeeringProperties.PeerASN", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "peeringParameters.ExpressRouteCrossConnectionPeeringProperties.PeerASN", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "peeringParameters.ExpressRouteCrossConnectionPeeringProperties.PeerASN", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.ExpressRouteCrossConnectionPeeringsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, crossConnectionName, peeringName, peeringParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCrossConnectionPeeringsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, peeringParameters ExpressRouteCrossConnectionPeering) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - peeringParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}", pathParameters), - autorest.WithJSON(peeringParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionPeeringsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCrossConnectionPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified peering from the ExpressRouteCrossConnection. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// peeringName - the name of the peering. -func (client ExpressRouteCrossConnectionPeeringsClient) Delete(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string) (result ExpressRouteCrossConnectionPeeringsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, crossConnectionName, peeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteCrossConnectionPeeringsClient) DeletePreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionPeeringsClient) DeleteSender(req *http.Request) (future ExpressRouteCrossConnectionPeeringsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionPeeringsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified peering for the ExpressRouteCrossConnection. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// peeringName - the name of the peering. -func (client ExpressRouteCrossConnectionPeeringsClient) Get(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string) (result ExpressRouteCrossConnectionPeering, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, crossConnectionName, peeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "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.ExpressRouteCrossConnectionPeeringsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteCrossConnectionPeeringsClient) GetPreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionPeeringsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionPeeringsClient) GetResponder(resp *http.Response) (result ExpressRouteCrossConnectionPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all peerings in a specified ExpressRouteCrossConnection. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -func (client ExpressRouteCrossConnectionPeeringsClient) List(ctx context.Context, resourceGroupName string, crossConnectionName string) (result ExpressRouteCrossConnectionPeeringListPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringsClient.List") - defer func() { - sc := -1 - if result.erccpl.Response.Response != nil { - sc = result.erccpl.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, crossConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.erccpl.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "List", resp, "Failure sending request") - return - } - - result.erccpl, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "List", resp, "Failure responding to request") - return - } - if result.erccpl.hasNextLink() && result.erccpl.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteCrossConnectionPeeringsClient) ListPreparer(ctx context.Context, resourceGroupName string, crossConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCrossConnections/{crossConnectionName}/peerings", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionPeeringsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionPeeringsClient) ListResponder(resp *http.Response) (result ExpressRouteCrossConnectionPeeringList, err error) { - err = autorest.Respond( - resp, - 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 ExpressRouteCrossConnectionPeeringsClient) listNextResults(ctx context.Context, lastResults ExpressRouteCrossConnectionPeeringList) (result ExpressRouteCrossConnectionPeeringList, err error) { - req, err := lastResults.expressRouteCrossConnectionPeeringListPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCrossConnectionPeeringsClient) ListComplete(ctx context.Context, resourceGroupName string, crossConnectionName string) (result ExpressRouteCrossConnectionPeeringListIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, crossConnectionName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecrossconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecrossconnections.go deleted file mode 100644 index 2db798b888..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutecrossconnections.go +++ /dev/null @@ -1,751 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteCrossConnectionsClient is the network Client -type ExpressRouteCrossConnectionsClient struct { - BaseClient -} - -// NewExpressRouteCrossConnectionsClient creates an instance of the ExpressRouteCrossConnectionsClient client. -func NewExpressRouteCrossConnectionsClient(subscriptionID string) ExpressRouteCrossConnectionsClient { - return NewExpressRouteCrossConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteCrossConnectionsClientWithBaseURI creates an instance of the ExpressRouteCrossConnectionsClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewExpressRouteCrossConnectionsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCrossConnectionsClient { - return ExpressRouteCrossConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate update the specified ExpressRouteCrossConnection. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// parameters - parameters supplied to the update express route crossConnection operation. -func (client ExpressRouteCrossConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, crossConnectionName string, parameters ExpressRouteCrossConnection) (result ExpressRouteCrossConnectionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, crossConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCrossConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, parameters ExpressRouteCrossConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteCrossConnectionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCrossConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get gets details about the specified ExpressRouteCrossConnection. -// Parameters: -// resourceGroupName - the name of the resource group (peering location of the circuit). -// crossConnectionName - the name of the ExpressRouteCrossConnection (service key of the circuit). -func (client ExpressRouteCrossConnectionsClient) Get(ctx context.Context, resourceGroupName string, crossConnectionName string) (result ExpressRouteCrossConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, crossConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "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.ExpressRouteCrossConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteCrossConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, crossConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCrossConnections/{crossConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) GetResponder(resp *http.Response) (result ExpressRouteCrossConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List retrieves all the ExpressRouteCrossConnections in a subscription. -func (client ExpressRouteCrossConnectionsClient) List(ctx context.Context) (result ExpressRouteCrossConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.List") - defer func() { - sc := -1 - if result.ercclr.Response.Response != nil { - sc = result.ercclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ercclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.ercclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.ercclr.hasNextLink() && result.ercclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteCrossConnectionsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteCrossConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) ListResponder(resp *http.Response) (result ExpressRouteCrossConnectionListResult, err error) { - err = autorest.Respond( - resp, - 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 ExpressRouteCrossConnectionsClient) listNextResults(ctx context.Context, lastResults ExpressRouteCrossConnectionListResult) (result ExpressRouteCrossConnectionListResult, err error) { - req, err := lastResults.expressRouteCrossConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCrossConnectionsClient) ListComplete(ctx context.Context) (result ExpressRouteCrossConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListArpTable gets the currently advertised ARP table associated with the express route cross connection in a -// resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// peeringName - the name of the peering. -// devicePath - the path of the device. -func (client ExpressRouteCrossConnectionsClient) ListArpTable(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string) (result ExpressRouteCrossConnectionsListArpTableFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.ListArpTable") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListArpTablePreparer(ctx, resourceGroupName, crossConnectionName, peeringName, devicePath) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListArpTable", nil, "Failure preparing request") - return - } - - result, err = client.ListArpTableSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListArpTable", result.Response(), "Failure sending request") - return - } - - return -} - -// ListArpTablePreparer prepares the ListArpTable request. -func (client ExpressRouteCrossConnectionsClient) ListArpTablePreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "devicePath": autorest.Encode("path", devicePath), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/arpTables/{devicePath}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListArpTableSender sends the ListArpTable request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) ListArpTableSender(req *http.Request) (future ExpressRouteCrossConnectionsListArpTableFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListArpTableResponder handles the response to the ListArpTable request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) ListArpTableResponder(resp *http.Response) (result ExpressRouteCircuitsArpTableListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByResourceGroup retrieves all the ExpressRouteCrossConnections in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ExpressRouteCrossConnectionsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ExpressRouteCrossConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.ercclr.Response.Response != nil { - sc = result.ercclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.ercclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.ercclr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.ercclr.hasNextLink() && result.ercclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ExpressRouteCrossConnectionsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCrossConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) ListByResourceGroupResponder(resp *http.Response) (result ExpressRouteCrossConnectionListResult, err error) { - err = autorest.Respond( - resp, - 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 ExpressRouteCrossConnectionsClient) listByResourceGroupNextResults(ctx context.Context, lastResults ExpressRouteCrossConnectionListResult) (result ExpressRouteCrossConnectionListResult, err error) { - req, err := lastResults.expressRouteCrossConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteCrossConnectionsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ExpressRouteCrossConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// ListRoutesTable gets the currently advertised routes table associated with the express route cross connection in a -// resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// peeringName - the name of the peering. -// devicePath - the path of the device. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTable(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string) (result ExpressRouteCrossConnectionsListRoutesTableFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.ListRoutesTable") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListRoutesTablePreparer(ctx, resourceGroupName, crossConnectionName, peeringName, devicePath) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListRoutesTable", nil, "Failure preparing request") - return - } - - result, err = client.ListRoutesTableSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListRoutesTable", result.Response(), "Failure sending request") - return - } - - return -} - -// ListRoutesTablePreparer prepares the ListRoutesTable request. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTablePreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "devicePath": autorest.Encode("path", devicePath), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTables/{devicePath}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListRoutesTableSender sends the ListRoutesTable request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTableSender(req *http.Request) (future ExpressRouteCrossConnectionsListRoutesTableFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListRoutesTableResponder handles the response to the ListRoutesTable request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTableResponder(resp *http.Response) (result ExpressRouteCircuitsRoutesTableListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListRoutesTableSummary gets the route table summary associated with the express route cross connection in a resource -// group. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the ExpressRouteCrossConnection. -// peeringName - the name of the peering. -// devicePath - the path of the device. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTableSummary(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string) (result ExpressRouteCrossConnectionsListRoutesTableSummaryFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.ListRoutesTableSummary") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListRoutesTableSummaryPreparer(ctx, resourceGroupName, crossConnectionName, peeringName, devicePath) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListRoutesTableSummary", nil, "Failure preparing request") - return - } - - result, err = client.ListRoutesTableSummarySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "ListRoutesTableSummary", result.Response(), "Failure sending request") - return - } - - return -} - -// ListRoutesTableSummaryPreparer prepares the ListRoutesTableSummary request. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTableSummaryPreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, peeringName string, devicePath string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "devicePath": autorest.Encode("path", devicePath), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTablesSummary/{devicePath}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListRoutesTableSummarySender sends the ListRoutesTableSummary request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTableSummarySender(req *http.Request) (future ExpressRouteCrossConnectionsListRoutesTableSummaryFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListRoutesTableSummaryResponder handles the response to the ListRoutesTableSummary request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) ListRoutesTableSummaryResponder(resp *http.Response) (result ExpressRouteCrossConnectionsRoutesTableSummaryListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates an express route cross connection tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// crossConnectionName - the name of the cross connection. -// crossConnectionParameters - parameters supplied to update express route cross connection tags. -func (client ExpressRouteCrossConnectionsClient) UpdateTags(ctx context.Context, resourceGroupName string, crossConnectionName string, crossConnectionParameters TagsObject) (result ExpressRouteCrossConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionsClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, crossConnectionName, crossConnectionParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ExpressRouteCrossConnectionsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, crossConnectionName string, crossConnectionParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "crossConnectionName": autorest.Encode("path", crossConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}", pathParameters), - autorest.WithJSON(crossConnectionParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteCrossConnectionsClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ExpressRouteCrossConnectionsClient) UpdateTagsResponder(resp *http.Response) (result ExpressRouteCrossConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutegateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutegateways.go deleted file mode 100644 index d321a29400..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutegateways.go +++ /dev/null @@ -1,505 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteGatewaysClient is the network Client -type ExpressRouteGatewaysClient struct { - BaseClient -} - -// NewExpressRouteGatewaysClient creates an instance of the ExpressRouteGatewaysClient client. -func NewExpressRouteGatewaysClient(subscriptionID string) ExpressRouteGatewaysClient { - return NewExpressRouteGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteGatewaysClientWithBaseURI creates an instance of the ExpressRouteGatewaysClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewExpressRouteGatewaysClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteGatewaysClient { - return ExpressRouteGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a ExpressRoute gateway in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -// putExpressRouteGatewayParameters - parameters required in an ExpressRoute gateway PUT operation. -func (client ExpressRouteGatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, putExpressRouteGatewayParameters ExpressRouteGateway) (result ExpressRouteGatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteGatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: putExpressRouteGatewayParameters, - Constraints: []validation.Constraint{{Target: "putExpressRouteGatewayParameters.ExpressRouteGatewayProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "putExpressRouteGatewayParameters.ExpressRouteGatewayProperties.VirtualHub", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { - return result, validation.NewError("network.ExpressRouteGatewaysClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, expressRouteGatewayName, putExpressRouteGatewayParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteGatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, putExpressRouteGatewayParameters ExpressRouteGateway) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - putExpressRouteGatewayParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}", pathParameters), - autorest.WithJSON(putExpressRouteGatewayParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteGatewaysClient) CreateOrUpdateSender(req *http.Request) (future ExpressRouteGatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRouteGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified ExpressRoute gateway in a resource group. An ExpressRoute gateway resource can only be -// deleted when there are no connection subresources. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -func (client ExpressRouteGatewaysClient) Delete(ctx context.Context, resourceGroupName string, expressRouteGatewayName string) (result ExpressRouteGatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteGatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, expressRouteGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRouteGatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteGateways/{expressRouteGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteGatewaysClient) DeleteSender(req *http.Request) (future ExpressRouteGatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRouteGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get fetches the details of a ExpressRoute gateway in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRouteGatewayName - the name of the ExpressRoute gateway. -func (client ExpressRouteGatewaysClient) Get(ctx context.Context, resourceGroupName string, expressRouteGatewayName string) (result ExpressRouteGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteGatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, expressRouteGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "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.ExpressRouteGatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteGatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteGateways/{expressRouteGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteGatewaysClient) GetResponder(resp *http.Response) (result ExpressRouteGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByResourceGroup lists ExpressRoute gateways in a given resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ExpressRouteGatewaysClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ExpressRouteGatewayList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteGatewaysClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "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.ExpressRouteGatewaysClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ExpressRouteGatewaysClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteGatewaysClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ExpressRouteGatewaysClient) ListByResourceGroupResponder(resp *http.Response) (result ExpressRouteGatewayList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListBySubscription lists ExpressRoute gateways under a given subscription. -func (client ExpressRouteGatewaysClient) ListBySubscription(ctx context.Context) (result ExpressRouteGatewayList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteGatewaysClient.ListBySubscription") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListBySubscriptionPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "ListBySubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "ListBySubscription", resp, "Failure sending request") - return - } - - result, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "ListBySubscription", resp, "Failure responding to request") - return - } - - return -} - -// ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client ExpressRouteGatewaysClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBySubscriptionSender sends the ListBySubscription request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteGatewaysClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always -// closes the http.Response Body. -func (client ExpressRouteGatewaysClient) ListBySubscriptionResponder(resp *http.Response) (result ExpressRouteGatewayList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates express route gateway tags. -// Parameters: -// resourceGroupName - the resource group name of the ExpressRouteGateway. -// expressRouteGatewayName - the name of the gateway. -// expressRouteGatewayParameters - parameters supplied to update a virtual wan express route gateway tags. -func (client ExpressRouteGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, expressRouteGatewayParameters TagsObject) (result ExpressRouteGatewaysUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteGatewaysClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, expressRouteGatewayName, expressRouteGatewayParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ExpressRouteGatewaysClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, expressRouteGatewayName string, expressRouteGatewayParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRouteGatewayName": autorest.Encode("path", expressRouteGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}", pathParameters), - autorest.WithJSON(expressRouteGatewayParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteGatewaysClient) UpdateTagsSender(req *http.Request) (future ExpressRouteGatewaysUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ExpressRouteGatewaysClient) UpdateTagsResponder(resp *http.Response) (result ExpressRouteGateway, err error) { - err = autorest.Respond( - resp, - 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/services/network/mgmt/2022-07-01/network/expressroutelinks.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutelinks.go deleted file mode 100644 index 04657f3a8e..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressroutelinks.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteLinksClient is the network Client -type ExpressRouteLinksClient struct { - BaseClient -} - -// NewExpressRouteLinksClient creates an instance of the ExpressRouteLinksClient client. -func NewExpressRouteLinksClient(subscriptionID string) ExpressRouteLinksClient { - return NewExpressRouteLinksClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteLinksClientWithBaseURI creates an instance of the ExpressRouteLinksClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewExpressRouteLinksClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteLinksClient { - return ExpressRouteLinksClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get retrieves the specified ExpressRouteLink resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the ExpressRoutePort resource. -// linkName - the name of the ExpressRouteLink resource. -func (client ExpressRouteLinksClient) Get(ctx context.Context, resourceGroupName string, expressRoutePortName string, linkName string) (result ExpressRouteLink, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteLinksClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, expressRoutePortName, linkName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "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.ExpressRouteLinksClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRouteLinksClient) GetPreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string, linkName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "linkName": autorest.Encode("path", linkName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ExpressRoutePorts/{expressRoutePortName}/links/{linkName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteLinksClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRouteLinksClient) GetResponder(resp *http.Response) (result ExpressRouteLink, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List retrieve the ExpressRouteLink sub-resources of the specified ExpressRoutePort resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the ExpressRoutePort resource. -func (client ExpressRouteLinksClient) List(ctx context.Context, resourceGroupName string, expressRoutePortName string) (result ExpressRouteLinkListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteLinksClient.List") - defer func() { - sc := -1 - if result.erllr.Response.Response != nil { - sc = result.erllr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, expressRoutePortName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.erllr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "List", resp, "Failure sending request") - return - } - - result.erllr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "List", resp, "Failure responding to request") - return - } - if result.erllr.hasNextLink() && result.erllr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteLinksClient) ListPreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ExpressRoutePorts/{expressRoutePortName}/links", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteLinksClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteLinksClient) ListResponder(resp *http.Response) (result ExpressRouteLinkListResult, err error) { - err = autorest.Respond( - resp, - 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 ExpressRouteLinksClient) listNextResults(ctx context.Context, lastResults ExpressRouteLinkListResult) (result ExpressRouteLinkListResult, err error) { - req, err := lastResults.expressRouteLinkListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteLinksClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteLinksClient) ListComplete(ctx context.Context, resourceGroupName string, expressRoutePortName string) (result ExpressRouteLinkListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteLinksClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, expressRoutePortName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteportauthorizations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteportauthorizations.go deleted file mode 100644 index 401e7cba69..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteportauthorizations.go +++ /dev/null @@ -1,395 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRoutePortAuthorizationsClient is the network Client -type ExpressRoutePortAuthorizationsClient struct { - BaseClient -} - -// NewExpressRoutePortAuthorizationsClient creates an instance of the ExpressRoutePortAuthorizationsClient client. -func NewExpressRoutePortAuthorizationsClient(subscriptionID string) ExpressRoutePortAuthorizationsClient { - return NewExpressRoutePortAuthorizationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRoutePortAuthorizationsClientWithBaseURI creates an instance of the ExpressRoutePortAuthorizationsClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewExpressRoutePortAuthorizationsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRoutePortAuthorizationsClient { - return ExpressRoutePortAuthorizationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates an authorization in the specified express route port. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the express route port. -// authorizationName - the name of the authorization. -// authorizationParameters - parameters supplied to the create or update express route port authorization -// operation. -func (client ExpressRoutePortAuthorizationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string, authorizationParameters ExpressRoutePortAuthorization) (result ExpressRoutePortAuthorizationsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortAuthorizationsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, expressRoutePortName, authorizationName, authorizationParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRoutePortAuthorizationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string, authorizationParameters ExpressRoutePortAuthorization) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationName": autorest.Encode("path", authorizationName), - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - authorizationParameters.Etag = nil - authorizationParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRoutePorts/{expressRoutePortName}/authorizations/{authorizationName}", pathParameters), - autorest.WithJSON(authorizationParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortAuthorizationsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRoutePortAuthorizationsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortAuthorizationsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRoutePortAuthorization, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified authorization from the specified express route port. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the express route port. -// authorizationName - the name of the authorization. -func (client ExpressRoutePortAuthorizationsClient) Delete(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string) (result ExpressRoutePortAuthorizationsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortAuthorizationsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, expressRoutePortName, authorizationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRoutePortAuthorizationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationName": autorest.Encode("path", authorizationName), - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRoutePorts/{expressRoutePortName}/authorizations/{authorizationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortAuthorizationsClient) DeleteSender(req *http.Request) (future ExpressRoutePortAuthorizationsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortAuthorizationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified authorization from the specified express route port. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the express route port. -// authorizationName - the name of the authorization. -func (client ExpressRoutePortAuthorizationsClient) Get(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string) (result ExpressRoutePortAuthorization, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortAuthorizationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, expressRoutePortName, authorizationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsClient", "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.ExpressRoutePortAuthorizationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRoutePortAuthorizationsClient) GetPreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string, authorizationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "authorizationName": autorest.Encode("path", authorizationName), - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRoutePorts/{expressRoutePortName}/authorizations/{authorizationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortAuthorizationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortAuthorizationsClient) GetResponder(resp *http.Response) (result ExpressRoutePortAuthorization, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all authorizations in an express route port. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the express route port. -func (client ExpressRoutePortAuthorizationsClient) List(ctx context.Context, resourceGroupName string, expressRoutePortName string) (result ExpressRoutePortAuthorizationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortAuthorizationsClient.List") - defer func() { - sc := -1 - if result.erpalr.Response.Response != nil { - sc = result.erpalr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, expressRoutePortName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.erpalr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsClient", "List", resp, "Failure sending request") - return - } - - result.erpalr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsClient", "List", resp, "Failure responding to request") - return - } - if result.erpalr.hasNextLink() && result.erpalr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRoutePortAuthorizationsClient) ListPreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRoutePorts/{expressRoutePortName}/authorizations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortAuthorizationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortAuthorizationsClient) ListResponder(resp *http.Response) (result ExpressRoutePortAuthorizationListResult, err error) { - err = autorest.Respond( - resp, - 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 ExpressRoutePortAuthorizationsClient) listNextResults(ctx context.Context, lastResults ExpressRoutePortAuthorizationListResult) (result ExpressRoutePortAuthorizationListResult, err error) { - req, err := lastResults.expressRoutePortAuthorizationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRoutePortAuthorizationsClient) ListComplete(ctx context.Context, resourceGroupName string, expressRoutePortName string) (result ExpressRoutePortAuthorizationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortAuthorizationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, expressRoutePortName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteports.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteports.go deleted file mode 100644 index d722d3ad13..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteports.go +++ /dev/null @@ -1,663 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRoutePortsClient is the network Client -type ExpressRoutePortsClient struct { - BaseClient -} - -// NewExpressRoutePortsClient creates an instance of the ExpressRoutePortsClient client. -func NewExpressRoutePortsClient(subscriptionID string) ExpressRoutePortsClient { - return NewExpressRoutePortsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRoutePortsClientWithBaseURI creates an instance of the ExpressRoutePortsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewExpressRoutePortsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRoutePortsClient { - return ExpressRoutePortsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates the specified ExpressRoutePort resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the ExpressRoutePort resource. -// parameters - parameters supplied to the create ExpressRoutePort operation. -func (client ExpressRoutePortsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters ExpressRoutePort) (result ExpressRoutePortsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, expressRoutePortName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRoutePortsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters ExpressRoutePort) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRoutePortsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRoutePort, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified ExpressRoutePort resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the ExpressRoutePort resource. -func (client ExpressRoutePortsClient) Delete(ctx context.Context, resourceGroupName string, expressRoutePortName string) (result ExpressRoutePortsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, expressRoutePortName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ExpressRoutePortsClient) DeletePreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ExpressRoutePorts/{expressRoutePortName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsClient) DeleteSender(req *http.Request) (future ExpressRoutePortsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// GenerateLOA generate a letter of authorization for the requested ExpressRoutePort resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of ExpressRoutePort. -// request - request parameters supplied to generate a letter of authorization. -func (client ExpressRoutePortsClient) GenerateLOA(ctx context.Context, resourceGroupName string, expressRoutePortName string, request GenerateExpressRoutePortsLOARequest) (result GenerateExpressRoutePortsLOAResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.GenerateLOA") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: request, - Constraints: []validation.Constraint{{Target: "request.CustomerName", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.ExpressRoutePortsClient", "GenerateLOA", err.Error()) - } - - req, err := client.GenerateLOAPreparer(ctx, resourceGroupName, expressRoutePortName, request) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "GenerateLOA", nil, "Failure preparing request") - return - } - - resp, err := client.GenerateLOASender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "GenerateLOA", resp, "Failure sending request") - return - } - - result, err = client.GenerateLOAResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "GenerateLOA", resp, "Failure responding to request") - return - } - - return -} - -// GenerateLOAPreparer prepares the GenerateLOA request. -func (client ExpressRoutePortsClient) GenerateLOAPreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string, request GenerateExpressRoutePortsLOARequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRoutePorts/{expressRoutePortName}/generateLoa", pathParameters), - autorest.WithJSON(request), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GenerateLOASender sends the GenerateLOA request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsClient) GenerateLOASender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GenerateLOAResponder handles the response to the GenerateLOA request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsClient) GenerateLOAResponder(resp *http.Response) (result GenerateExpressRoutePortsLOAResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get retrieves the requested ExpressRoutePort resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of ExpressRoutePort. -func (client ExpressRoutePortsClient) Get(ctx context.Context, resourceGroupName string, expressRoutePortName string) (result ExpressRoutePort, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, expressRoutePortName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "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.ExpressRoutePortsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRoutePortsClient) GetPreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ExpressRoutePorts/{expressRoutePortName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsClient) GetResponder(resp *http.Response) (result ExpressRoutePort, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all the ExpressRoutePort resources in the specified subscription. -func (client ExpressRoutePortsClient) List(ctx context.Context) (result ExpressRoutePortListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.List") - defer func() { - sc := -1 - if result.erplr.Response.Response != nil { - sc = result.erplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.erplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "List", resp, "Failure sending request") - return - } - - result.erplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "List", resp, "Failure responding to request") - return - } - if result.erplr.hasNextLink() && result.erplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRoutePortsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePorts", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsClient) ListResponder(resp *http.Response) (result ExpressRoutePortListResult, err error) { - err = autorest.Respond( - resp, - 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 ExpressRoutePortsClient) listNextResults(ctx context.Context, lastResults ExpressRoutePortListResult) (result ExpressRoutePortListResult, err error) { - req, err := lastResults.expressRoutePortListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRoutePortsClient) ListComplete(ctx context.Context) (result ExpressRoutePortListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup list all the ExpressRoutePort resources in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ExpressRoutePortsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ExpressRoutePortListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.erplr.Response.Response != nil { - sc = result.erplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.erplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.erplr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.erplr.hasNextLink() && result.erplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ExpressRoutePortsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ExpressRoutePorts", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsClient) ListByResourceGroupResponder(resp *http.Response) (result ExpressRoutePortListResult, err error) { - err = autorest.Respond( - resp, - 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 ExpressRoutePortsClient) listByResourceGroupNextResults(ctx context.Context, lastResults ExpressRoutePortListResult) (result ExpressRoutePortListResult, err error) { - req, err := lastResults.expressRoutePortListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRoutePortsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ExpressRoutePortListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags update ExpressRoutePort tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// expressRoutePortName - the name of the ExpressRoutePort resource. -// parameters - parameters supplied to update ExpressRoutePort resource tags. -func (client ExpressRoutePortsClient) UpdateTags(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters TagsObject) (result ExpressRoutePort, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, expressRoutePortName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ExpressRoutePortsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "expressRoutePortName": autorest.Encode("path", expressRoutePortName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsClient) UpdateTagsResponder(resp *http.Response) (result ExpressRoutePort, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteportslocations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteportslocations.go deleted file mode 100644 index 0fd21f2208..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteportslocations.go +++ /dev/null @@ -1,221 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRoutePortsLocationsClient is the network Client -type ExpressRoutePortsLocationsClient struct { - BaseClient -} - -// NewExpressRoutePortsLocationsClient creates an instance of the ExpressRoutePortsLocationsClient client. -func NewExpressRoutePortsLocationsClient(subscriptionID string) ExpressRoutePortsLocationsClient { - return NewExpressRoutePortsLocationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRoutePortsLocationsClientWithBaseURI creates an instance of the ExpressRoutePortsLocationsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewExpressRoutePortsLocationsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRoutePortsLocationsClient { - return ExpressRoutePortsLocationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get retrieves a single ExpressRoutePort peering location, including the list of available bandwidths available at -// said peering location. -// Parameters: -// locationName - name of the requested ExpressRoutePort peering location. -func (client ExpressRoutePortsLocationsClient) Get(ctx context.Context, locationName string) (result ExpressRoutePortsLocation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsLocationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, locationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "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.ExpressRoutePortsLocationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ExpressRoutePortsLocationsClient) GetPreparer(ctx context.Context, locationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "locationName": autorest.Encode("path", locationName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations/{locationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsLocationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsLocationsClient) GetResponder(resp *http.Response) (result ExpressRoutePortsLocation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List retrieves all ExpressRoutePort peering locations. Does not return available bandwidths for each location. -// Available bandwidths can only be obtained when retrieving a specific peering location. -func (client ExpressRoutePortsLocationsClient) List(ctx context.Context) (result ExpressRoutePortsLocationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsLocationsClient.List") - defer func() { - sc := -1 - if result.erpllr.Response.Response != nil { - sc = result.erpllr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.erpllr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "List", resp, "Failure sending request") - return - } - - result.erpllr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "List", resp, "Failure responding to request") - return - } - if result.erpllr.hasNextLink() && result.erpllr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRoutePortsLocationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRoutePortsLocationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRoutePortsLocationsClient) ListResponder(resp *http.Response) (result ExpressRoutePortsLocationListResult, err error) { - err = autorest.Respond( - resp, - 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 ExpressRoutePortsLocationsClient) listNextResults(ctx context.Context, lastResults ExpressRoutePortsLocationListResult) (result ExpressRoutePortsLocationListResult, err error) { - req, err := lastResults.expressRoutePortsLocationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRoutePortsLocationsClient) ListComplete(ctx context.Context) (result ExpressRoutePortsLocationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsLocationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteproviderportslocation.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteproviderportslocation.go deleted file mode 100644 index c4671c00ae..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteproviderportslocation.go +++ /dev/null @@ -1,109 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteProviderPortsLocationClient is the network Client -type ExpressRouteProviderPortsLocationClient struct { - BaseClient -} - -// NewExpressRouteProviderPortsLocationClient creates an instance of the ExpressRouteProviderPortsLocationClient -// client. -func NewExpressRouteProviderPortsLocationClient(subscriptionID string) ExpressRouteProviderPortsLocationClient { - return NewExpressRouteProviderPortsLocationClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteProviderPortsLocationClientWithBaseURI creates an instance of the -// ExpressRouteProviderPortsLocationClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewExpressRouteProviderPortsLocationClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteProviderPortsLocationClient { - return ExpressRouteProviderPortsLocationClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List retrieves all the ExpressRouteProviderPorts in a subscription. -// Parameters: -// filter - the filter to apply on the operation. For example, you can use $filter=location eq '{state}'. -func (client ExpressRouteProviderPortsLocationClient) List(ctx context.Context, filter string) (result ExpressRouteProviderPortListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteProviderPortsLocationClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, filter) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteProviderPortsLocationClient", "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.ExpressRouteProviderPortsLocationClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteProviderPortsLocationClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteProviderPortsLocationClient) ListPreparer(ctx context.Context, filter string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(filter) > 0 { - queryParameters["$filter"] = autorest.Encode("query", filter) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteProviderPorts", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteProviderPortsLocationClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteProviderPortsLocationClient) ListResponder(resp *http.Response) (result ExpressRouteProviderPortListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteserviceproviders.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteserviceproviders.go deleted file mode 100644 index b76714e641..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/expressrouteserviceproviders.go +++ /dev/null @@ -1,145 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ExpressRouteServiceProvidersClient is the network Client -type ExpressRouteServiceProvidersClient struct { - BaseClient -} - -// NewExpressRouteServiceProvidersClient creates an instance of the ExpressRouteServiceProvidersClient client. -func NewExpressRouteServiceProvidersClient(subscriptionID string) ExpressRouteServiceProvidersClient { - return NewExpressRouteServiceProvidersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewExpressRouteServiceProvidersClientWithBaseURI creates an instance of the ExpressRouteServiceProvidersClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewExpressRouteServiceProvidersClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteServiceProvidersClient { - return ExpressRouteServiceProvidersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets all the available express route service providers. -func (client ExpressRouteServiceProvidersClient) List(ctx context.Context) (result ExpressRouteServiceProviderListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteServiceProvidersClient.List") - defer func() { - sc := -1 - if result.ersplr.Response.Response != nil { - sc = result.ersplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ersplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure sending request") - return - } - - result.ersplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure responding to request") - return - } - if result.ersplr.hasNextLink() && result.ersplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ExpressRouteServiceProvidersClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteServiceProviders", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ExpressRouteServiceProvidersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ExpressRouteServiceProvidersClient) ListResponder(resp *http.Response) (result ExpressRouteServiceProviderListResult, err error) { - err = autorest.Respond( - resp, - 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 ExpressRouteServiceProvidersClient) listNextResults(ctx context.Context, lastResults ExpressRouteServiceProviderListResult) (result ExpressRouteServiceProviderListResult, err error) { - req, err := lastResults.expressRouteServiceProviderListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ExpressRouteServiceProvidersClient) ListComplete(ctx context.Context) (result ExpressRouteServiceProviderListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteServiceProvidersClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicies.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicies.go deleted file mode 100644 index 44ec477c20..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicies.go +++ /dev/null @@ -1,603 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// FirewallPoliciesClient is the network Client -type FirewallPoliciesClient struct { - BaseClient -} - -// NewFirewallPoliciesClient creates an instance of the FirewallPoliciesClient client. -func NewFirewallPoliciesClient(subscriptionID string) FirewallPoliciesClient { - return NewFirewallPoliciesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewFirewallPoliciesClientWithBaseURI creates an instance of the FirewallPoliciesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewFirewallPoliciesClientWithBaseURI(baseURI string, subscriptionID string) FirewallPoliciesClient { - return FirewallPoliciesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates the specified Firewall Policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -// parameters - parameters supplied to the create or update Firewall Policy operation. -func (client FirewallPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters FirewallPolicy) (result FirewallPoliciesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPoliciesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.FirewallPolicyPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.FirewallPolicyPropertiesFormat.ExplicitProxy", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.FirewallPolicyPropertiesFormat.ExplicitProxy.HTTPPort", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.FirewallPolicyPropertiesFormat.ExplicitProxy.HTTPPort", Name: validation.InclusiveMaximum, Rule: int64(64000), Chain: nil}, - {Target: "parameters.FirewallPolicyPropertiesFormat.ExplicitProxy.HTTPPort", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - {Target: "parameters.FirewallPolicyPropertiesFormat.ExplicitProxy.HTTPSPort", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.FirewallPolicyPropertiesFormat.ExplicitProxy.HTTPSPort", Name: validation.InclusiveMaximum, Rule: int64(64000), Chain: nil}, - {Target: "parameters.FirewallPolicyPropertiesFormat.ExplicitProxy.HTTPSPort", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - {Target: "parameters.FirewallPolicyPropertiesFormat.ExplicitProxy.PacFilePort", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.FirewallPolicyPropertiesFormat.ExplicitProxy.PacFilePort", Name: validation.InclusiveMaximum, Rule: int64(64000), Chain: nil}, - {Target: "parameters.FirewallPolicyPropertiesFormat.ExplicitProxy.PacFilePort", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.FirewallPoliciesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, firewallPolicyName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client FirewallPoliciesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters FirewallPolicy) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPoliciesClient) CreateOrUpdateSender(req *http.Request) (future FirewallPoliciesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client FirewallPoliciesClient) CreateOrUpdateResponder(resp *http.Response) (result FirewallPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified Firewall Policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -func (client FirewallPoliciesClient) Delete(ctx context.Context, resourceGroupName string, firewallPolicyName string) (result FirewallPoliciesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPoliciesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, firewallPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client FirewallPoliciesClient) DeletePreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/firewallPolicies/{firewallPolicyName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPoliciesClient) DeleteSender(req *http.Request) (future FirewallPoliciesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client FirewallPoliciesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified Firewall Policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -// expand - expands referenced resources. -func (client FirewallPoliciesClient) Get(ctx context.Context, resourceGroupName string, firewallPolicyName string, expand string) (result FirewallPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPoliciesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, firewallPolicyName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "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.FirewallPoliciesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client FirewallPoliciesClient) GetPreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/firewallPolicies/{firewallPolicyName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPoliciesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client FirewallPoliciesClient) GetResponder(resp *http.Response) (result FirewallPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all Firewall Policies in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client FirewallPoliciesClient) List(ctx context.Context, resourceGroupName string) (result FirewallPolicyListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPoliciesClient.List") - defer func() { - sc := -1 - if result.fplr.Response.Response != nil { - sc = result.fplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.fplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "List", resp, "Failure sending request") - return - } - - result.fplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "List", resp, "Failure responding to request") - return - } - if result.fplr.hasNextLink() && result.fplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client FirewallPoliciesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/firewallPolicies", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPoliciesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client FirewallPoliciesClient) ListResponder(resp *http.Response) (result FirewallPolicyListResult, err error) { - err = autorest.Respond( - resp, - 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 FirewallPoliciesClient) listNextResults(ctx context.Context, lastResults FirewallPolicyListResult) (result FirewallPolicyListResult, err error) { - req, err := lastResults.firewallPolicyListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client FirewallPoliciesClient) ListComplete(ctx context.Context, resourceGroupName string) (result FirewallPolicyListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPoliciesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the Firewall Policies in a subscription. -func (client FirewallPoliciesClient) ListAll(ctx context.Context) (result FirewallPolicyListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPoliciesClient.ListAll") - defer func() { - sc := -1 - if result.fplr.Response.Response != nil { - sc = result.fplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.fplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "ListAll", resp, "Failure sending request") - return - } - - result.fplr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.fplr.hasNextLink() && result.fplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client FirewallPoliciesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/firewallPolicies", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPoliciesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client FirewallPoliciesClient) ListAllResponder(resp *http.Response) (result FirewallPolicyListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client FirewallPoliciesClient) listAllNextResults(ctx context.Context, lastResults FirewallPolicyListResult) (result FirewallPolicyListResult, err error) { - req, err := lastResults.firewallPolicyListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client FirewallPoliciesClient) ListAllComplete(ctx context.Context) (result FirewallPolicyListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPoliciesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// UpdateTags updates tags of a Azure Firewall Policy resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -// parameters - parameters supplied to update Azure Firewall Policy tags. -func (client FirewallPoliciesClient) UpdateTags(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters TagsObject) (result FirewallPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPoliciesClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, firewallPolicyName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client FirewallPoliciesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPoliciesClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client FirewallPoliciesClient) UpdateTagsResponder(resp *http.Response) (result FirewallPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicyidpssignatures.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicyidpssignatures.go deleted file mode 100644 index 851178b0d8..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicyidpssignatures.go +++ /dev/null @@ -1,120 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// FirewallPolicyIdpsSignaturesClient is the network Client -type FirewallPolicyIdpsSignaturesClient struct { - BaseClient -} - -// NewFirewallPolicyIdpsSignaturesClient creates an instance of the FirewallPolicyIdpsSignaturesClient client. -func NewFirewallPolicyIdpsSignaturesClient(subscriptionID string) FirewallPolicyIdpsSignaturesClient { - return NewFirewallPolicyIdpsSignaturesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewFirewallPolicyIdpsSignaturesClientWithBaseURI creates an instance of the FirewallPolicyIdpsSignaturesClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewFirewallPolicyIdpsSignaturesClientWithBaseURI(baseURI string, subscriptionID string) FirewallPolicyIdpsSignaturesClient { - return FirewallPolicyIdpsSignaturesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List retrieves the current status of IDPS signatures for the relevant policy -// Parameters: -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -func (client FirewallPolicyIdpsSignaturesClient) List(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters IDPSQueryObject) (result QueryResults, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyIdpsSignaturesClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.ResultsPerPage", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ResultsPerPage", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil}, - {Target: "parameters.ResultsPerPage", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.FirewallPolicyIdpsSignaturesClient", "List", err.Error()) - } - - req, err := client.ListPreparer(ctx, resourceGroupName, firewallPolicyName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesClient", "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.FirewallPolicyIdpsSignaturesClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client FirewallPolicyIdpsSignaturesClient) ListPreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string, parameters IDPSQueryObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/listIdpsSignatures", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPolicyIdpsSignaturesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client FirewallPolicyIdpsSignaturesClient) ListResponder(resp *http.Response) (result QueryResults, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicyidpssignaturesfiltervalues.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicyidpssignaturesfiltervalues.go deleted file mode 100644 index 00a994c89a..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicyidpssignaturesfiltervalues.go +++ /dev/null @@ -1,111 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// FirewallPolicyIdpsSignaturesFilterValuesClient is the network Client -type FirewallPolicyIdpsSignaturesFilterValuesClient struct { - BaseClient -} - -// NewFirewallPolicyIdpsSignaturesFilterValuesClient creates an instance of the -// FirewallPolicyIdpsSignaturesFilterValuesClient client. -func NewFirewallPolicyIdpsSignaturesFilterValuesClient(subscriptionID string) FirewallPolicyIdpsSignaturesFilterValuesClient { - return NewFirewallPolicyIdpsSignaturesFilterValuesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewFirewallPolicyIdpsSignaturesFilterValuesClientWithBaseURI creates an instance of the -// FirewallPolicyIdpsSignaturesFilterValuesClient client using a custom endpoint. Use this when interacting with an -// Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewFirewallPolicyIdpsSignaturesFilterValuesClientWithBaseURI(baseURI string, subscriptionID string) FirewallPolicyIdpsSignaturesFilterValuesClient { - return FirewallPolicyIdpsSignaturesFilterValuesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List retrieves the current filter values for the signatures overrides -// Parameters: -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -func (client FirewallPolicyIdpsSignaturesFilterValuesClient) List(ctx context.Context, parameters SignatureOverridesFilterValuesQuery, resourceGroupName string, firewallPolicyName string) (result SignatureOverridesFilterValuesResponse, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyIdpsSignaturesFilterValuesClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, parameters, resourceGroupName, firewallPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesFilterValuesClient", "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.FirewallPolicyIdpsSignaturesFilterValuesClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesFilterValuesClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client FirewallPolicyIdpsSignaturesFilterValuesClient) ListPreparer(ctx context.Context, parameters SignatureOverridesFilterValuesQuery, resourceGroupName string, firewallPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/listIdpsFilterOptions", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPolicyIdpsSignaturesFilterValuesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client FirewallPolicyIdpsSignaturesFilterValuesClient) ListResponder(resp *http.Response) (result SignatureOverridesFilterValuesResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicyidpssignaturesoverrides.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicyidpssignaturesoverrides.go deleted file mode 100644 index b0bc6814f8..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicyidpssignaturesoverrides.go +++ /dev/null @@ -1,343 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// FirewallPolicyIdpsSignaturesOverridesClient is the network Client -type FirewallPolicyIdpsSignaturesOverridesClient struct { - BaseClient -} - -// NewFirewallPolicyIdpsSignaturesOverridesClient creates an instance of the -// FirewallPolicyIdpsSignaturesOverridesClient client. -func NewFirewallPolicyIdpsSignaturesOverridesClient(subscriptionID string) FirewallPolicyIdpsSignaturesOverridesClient { - return NewFirewallPolicyIdpsSignaturesOverridesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewFirewallPolicyIdpsSignaturesOverridesClientWithBaseURI creates an instance of the -// FirewallPolicyIdpsSignaturesOverridesClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewFirewallPolicyIdpsSignaturesOverridesClientWithBaseURI(baseURI string, subscriptionID string) FirewallPolicyIdpsSignaturesOverridesClient { - return FirewallPolicyIdpsSignaturesOverridesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get returns all signatures overrides for a specific policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -func (client FirewallPolicyIdpsSignaturesOverridesClient) Get(ctx context.Context, resourceGroupName string, firewallPolicyName string) (result SignaturesOverrides, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyIdpsSignaturesOverridesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, firewallPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesOverridesClient", "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.FirewallPolicyIdpsSignaturesOverridesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesOverridesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client FirewallPolicyIdpsSignaturesOverridesClient) GetPreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/firewallPolicies/{firewallPolicyName}/signatureOverrides/default", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPolicyIdpsSignaturesOverridesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client FirewallPolicyIdpsSignaturesOverridesClient) GetResponder(resp *http.Response) (result SignaturesOverrides, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List returns all signatures overrides objects for a specific policy as a list containing a single value. -// Parameters: -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -func (client FirewallPolicyIdpsSignaturesOverridesClient) List(ctx context.Context, resourceGroupName string, firewallPolicyName string) (result SignaturesOverridesList, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyIdpsSignaturesOverridesClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, firewallPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesOverridesClient", "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.FirewallPolicyIdpsSignaturesOverridesClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesOverridesClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client FirewallPolicyIdpsSignaturesOverridesClient) ListPreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/firewallPolicies/{firewallPolicyName}/signatureOverrides", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPolicyIdpsSignaturesOverridesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client FirewallPolicyIdpsSignaturesOverridesClient) ListResponder(resp *http.Response) (result SignaturesOverridesList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Patch will update the status of policy's signature overrides for IDPS -// Parameters: -// parameters - will contain all properties of the object to put -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -func (client FirewallPolicyIdpsSignaturesOverridesClient) Patch(ctx context.Context, parameters SignaturesOverrides, resourceGroupName string, firewallPolicyName string) (result SignaturesOverrides, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyIdpsSignaturesOverridesClient.Patch") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PatchPreparer(ctx, parameters, resourceGroupName, firewallPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesOverridesClient", "Patch", nil, "Failure preparing request") - return - } - - resp, err := client.PatchSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesOverridesClient", "Patch", resp, "Failure sending request") - return - } - - result, err = client.PatchResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesOverridesClient", "Patch", resp, "Failure responding to request") - return - } - - return -} - -// PatchPreparer prepares the Patch request. -func (client FirewallPolicyIdpsSignaturesOverridesClient) PatchPreparer(ctx context.Context, parameters SignaturesOverrides, resourceGroupName string, firewallPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/signatureOverrides/default", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PatchSender sends the Patch request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPolicyIdpsSignaturesOverridesClient) PatchSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// PatchResponder handles the response to the Patch request. The method always -// closes the http.Response Body. -func (client FirewallPolicyIdpsSignaturesOverridesClient) PatchResponder(resp *http.Response) (result SignaturesOverrides, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Put will override/create a new signature overrides for the policy's IDPS -// Parameters: -// parameters - will contain all properties of the object to put -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -func (client FirewallPolicyIdpsSignaturesOverridesClient) Put(ctx context.Context, parameters SignaturesOverrides, resourceGroupName string, firewallPolicyName string) (result SignaturesOverrides, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyIdpsSignaturesOverridesClient.Put") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PutPreparer(ctx, parameters, resourceGroupName, firewallPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesOverridesClient", "Put", nil, "Failure preparing request") - return - } - - resp, err := client.PutSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesOverridesClient", "Put", resp, "Failure sending request") - return - } - - result, err = client.PutResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyIdpsSignaturesOverridesClient", "Put", resp, "Failure responding to request") - return - } - - return -} - -// PutPreparer prepares the Put request. -func (client FirewallPolicyIdpsSignaturesOverridesClient) PutPreparer(ctx context.Context, parameters SignaturesOverrides, resourceGroupName string, firewallPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/signatureOverrides/default", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PutSender sends the Put request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPolicyIdpsSignaturesOverridesClient) PutSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// PutResponder handles the response to the Put request. The method always -// closes the http.Response Body. -func (client FirewallPolicyIdpsSignaturesOverridesClient) PutResponder(resp *http.Response) (result SignaturesOverrides, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicyrulecollectiongroups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicyrulecollectiongroups.go deleted file mode 100644 index bb71e0b964..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/firewallpolicyrulecollectiongroups.go +++ /dev/null @@ -1,407 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// FirewallPolicyRuleCollectionGroupsClient is the network Client -type FirewallPolicyRuleCollectionGroupsClient struct { - BaseClient -} - -// NewFirewallPolicyRuleCollectionGroupsClient creates an instance of the FirewallPolicyRuleCollectionGroupsClient -// client. -func NewFirewallPolicyRuleCollectionGroupsClient(subscriptionID string) FirewallPolicyRuleCollectionGroupsClient { - return NewFirewallPolicyRuleCollectionGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewFirewallPolicyRuleCollectionGroupsClientWithBaseURI creates an instance of the -// FirewallPolicyRuleCollectionGroupsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewFirewallPolicyRuleCollectionGroupsClientWithBaseURI(baseURI string, subscriptionID string) FirewallPolicyRuleCollectionGroupsClient { - return FirewallPolicyRuleCollectionGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates the specified FirewallPolicyRuleCollectionGroup. -// Parameters: -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -// ruleCollectionGroupName - the name of the FirewallPolicyRuleCollectionGroup. -// parameters - parameters supplied to the create or update FirewallPolicyRuleCollectionGroup operation. -func (client FirewallPolicyRuleCollectionGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string, parameters FirewallPolicyRuleCollectionGroup) (result FirewallPolicyRuleCollectionGroupsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyRuleCollectionGroupsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.FirewallPolicyRuleCollectionGroupProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.FirewallPolicyRuleCollectionGroupProperties.Priority", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.FirewallPolicyRuleCollectionGroupProperties.Priority", Name: validation.InclusiveMaximum, Rule: int64(65000), Chain: nil}, - {Target: "parameters.FirewallPolicyRuleCollectionGroupProperties.Priority", Name: validation.InclusiveMinimum, Rule: int64(100), Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.FirewallPolicyRuleCollectionGroupsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, firewallPolicyName, ruleCollectionGroupName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client FirewallPolicyRuleCollectionGroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string, parameters FirewallPolicyRuleCollectionGroup) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "ruleCollectionGroupName": autorest.Encode("path", ruleCollectionGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - parameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/ruleCollectionGroups/{ruleCollectionGroupName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPolicyRuleCollectionGroupsClient) CreateOrUpdateSender(req *http.Request) (future FirewallPolicyRuleCollectionGroupsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client FirewallPolicyRuleCollectionGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result FirewallPolicyRuleCollectionGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified FirewallPolicyRuleCollectionGroup. -// Parameters: -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -// ruleCollectionGroupName - the name of the FirewallPolicyRuleCollectionGroup. -func (client FirewallPolicyRuleCollectionGroupsClient) Delete(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string) (result FirewallPolicyRuleCollectionGroupsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyRuleCollectionGroupsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, firewallPolicyName, ruleCollectionGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client FirewallPolicyRuleCollectionGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "ruleCollectionGroupName": autorest.Encode("path", ruleCollectionGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/firewallPolicies/{firewallPolicyName}/ruleCollectionGroups/{ruleCollectionGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPolicyRuleCollectionGroupsClient) DeleteSender(req *http.Request) (future FirewallPolicyRuleCollectionGroupsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client FirewallPolicyRuleCollectionGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified FirewallPolicyRuleCollectionGroup. -// Parameters: -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -// ruleCollectionGroupName - the name of the FirewallPolicyRuleCollectionGroup. -func (client FirewallPolicyRuleCollectionGroupsClient) Get(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string) (result FirewallPolicyRuleCollectionGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyRuleCollectionGroupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, firewallPolicyName, ruleCollectionGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsClient", "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.FirewallPolicyRuleCollectionGroupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client FirewallPolicyRuleCollectionGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleCollectionGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "ruleCollectionGroupName": autorest.Encode("path", ruleCollectionGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/firewallPolicies/{firewallPolicyName}/ruleCollectionGroups/{ruleCollectionGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPolicyRuleCollectionGroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client FirewallPolicyRuleCollectionGroupsClient) GetResponder(resp *http.Response) (result FirewallPolicyRuleCollectionGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all FirewallPolicyRuleCollectionGroups in a FirewallPolicy resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// firewallPolicyName - the name of the Firewall Policy. -func (client FirewallPolicyRuleCollectionGroupsClient) List(ctx context.Context, resourceGroupName string, firewallPolicyName string) (result FirewallPolicyRuleCollectionGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyRuleCollectionGroupsClient.List") - defer func() { - sc := -1 - if result.fprcglr.Response.Response != nil { - sc = result.fprcglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, firewallPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.fprcglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsClient", "List", resp, "Failure sending request") - return - } - - result.fprcglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsClient", "List", resp, "Failure responding to request") - return - } - if result.fprcglr.hasNextLink() && result.fprcglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client FirewallPolicyRuleCollectionGroupsClient) ListPreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "firewallPolicyName": autorest.Encode("path", firewallPolicyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/firewallPolicies/{firewallPolicyName}/ruleCollectionGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client FirewallPolicyRuleCollectionGroupsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client FirewallPolicyRuleCollectionGroupsClient) ListResponder(resp *http.Response) (result FirewallPolicyRuleCollectionGroupListResult, err error) { - err = autorest.Respond( - resp, - 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 FirewallPolicyRuleCollectionGroupsClient) listNextResults(ctx context.Context, lastResults FirewallPolicyRuleCollectionGroupListResult) (result FirewallPolicyRuleCollectionGroupListResult, err error) { - req, err := lastResults.firewallPolicyRuleCollectionGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client FirewallPolicyRuleCollectionGroupsClient) ListComplete(ctx context.Context, resourceGroupName string, firewallPolicyName string) (result FirewallPolicyRuleCollectionGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyRuleCollectionGroupsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, firewallPolicyName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/flowlogs.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/flowlogs.go deleted file mode 100644 index d1567ce5aa..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/flowlogs.go +++ /dev/null @@ -1,483 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// FlowLogsClient is the network Client -type FlowLogsClient struct { - BaseClient -} - -// NewFlowLogsClient creates an instance of the FlowLogsClient client. -func NewFlowLogsClient(subscriptionID string) FlowLogsClient { - return NewFlowLogsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewFlowLogsClientWithBaseURI creates an instance of the FlowLogsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewFlowLogsClientWithBaseURI(baseURI string, subscriptionID string) FlowLogsClient { - return FlowLogsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or update a flow log for the specified network security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// flowLogName - the name of the flow log. -// parameters - parameters that define the create or update flow log resource. -func (client FlowLogsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, parameters FlowLog) (result FlowLogsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FlowLogsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.FlowLogPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.FlowLogPropertiesFormat.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.FlowLogPropertiesFormat.StorageID", Name: validation.Null, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.FlowLogsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkWatcherName, flowLogName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client FlowLogsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, parameters FlowLog) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "flowLogName": autorest.Encode("path", flowLogName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/flowLogs/{flowLogName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client FlowLogsClient) CreateOrUpdateSender(req *http.Request) (future FlowLogsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client FlowLogsClient) CreateOrUpdateResponder(resp *http.Response) (result FlowLog, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified flow log resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// flowLogName - the name of the flow log resource. -func (client FlowLogsClient) Delete(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string) (result FlowLogsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FlowLogsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkWatcherName, flowLogName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client FlowLogsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "flowLogName": autorest.Encode("path", flowLogName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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}/flowLogs/{flowLogName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client FlowLogsClient) DeleteSender(req *http.Request) (future FlowLogsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client FlowLogsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a flow log resource by name. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// flowLogName - the name of the flow log resource. -func (client FlowLogsClient) Get(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string) (result FlowLog, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FlowLogsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkWatcherName, flowLogName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsClient", "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.FlowLogsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client FlowLogsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "flowLogName": autorest.Encode("path", flowLogName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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}/flowLogs/{flowLogName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client FlowLogsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client FlowLogsClient) GetResponder(resp *http.Response) (result FlowLog, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all flow log resources for the specified Network Watcher. -// Parameters: -// resourceGroupName - the name of the resource group containing Network Watcher. -// networkWatcherName - the name of the Network Watcher resource. -func (client FlowLogsClient) List(ctx context.Context, resourceGroupName string, networkWatcherName string) (result FlowLogListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FlowLogsClient.List") - defer func() { - sc := -1 - if result.fllr.Response.Response != nil { - sc = result.fllr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkWatcherName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.fllr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.FlowLogsClient", "List", resp, "Failure sending request") - return - } - - result.fllr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsClient", "List", resp, "Failure responding to request") - return - } - if result.fllr.hasNextLink() && result.fllr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client FlowLogsClient) ListPreparer(ctx context.Context, 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 = "2022-07-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}/flowLogs", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client FlowLogsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client FlowLogsClient) ListResponder(resp *http.Response) (result FlowLogListResult, err error) { - err = autorest.Respond( - resp, - 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 FlowLogsClient) listNextResults(ctx context.Context, lastResults FlowLogListResult) (result FlowLogListResult, err error) { - req, err := lastResults.flowLogListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.FlowLogsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.FlowLogsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client FlowLogsClient) ListComplete(ctx context.Context, resourceGroupName string, networkWatcherName string) (result FlowLogListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FlowLogsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkWatcherName) - return -} - -// UpdateTags update tags of the specified flow log. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// flowLogName - the name of the flow log. -// parameters - parameters supplied to update flow log tags. -func (client FlowLogsClient) UpdateTags(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, parameters TagsObject) (result FlowLog, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FlowLogsClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, networkWatcherName, flowLogName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.FlowLogsClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client FlowLogsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, flowLogName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "flowLogName": autorest.Encode("path", flowLogName), - "networkWatcherName": autorest.Encode("path", networkWatcherName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/flowLogs/{flowLogName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client FlowLogsClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client FlowLogsClient) UpdateTagsResponder(resp *http.Response) (result FlowLog, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/groups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/groups.go deleted file mode 100644 index 4028e1173e..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/groups.go +++ /dev/null @@ -1,421 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// GroupsClient is the network Client -type GroupsClient struct { - BaseClient -} - -// NewGroupsClient creates an instance of the GroupsClient client. -func NewGroupsClient(subscriptionID string) GroupsClient { - return NewGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewGroupsClientWithBaseURI creates an instance of the GroupsClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewGroupsClientWithBaseURI(baseURI string, subscriptionID string) GroupsClient { - return GroupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a network group. -// Parameters: -// parameters - parameters supplied to the specify which network group need to create -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// networkGroupName - the name of the network group. -// ifMatch - the ETag of the transformation. Omit this value to always overwrite the current resource. Specify -// the last-seen ETag value to prevent accidentally overwriting concurrent changes. -func (client GroupsClient) CreateOrUpdate(ctx context.Context, parameters Group, resourceGroupName string, networkManagerName string, networkGroupName string, ifMatch string) (result Group, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, parameters, resourceGroupName, networkManagerName, networkGroupName, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GroupsClient", "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.GroupsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GroupsClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client GroupsClient) CreateOrUpdatePreparer(ctx context.Context, parameters Group, resourceGroupName string, networkManagerName string, networkGroupName string, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkGroupName": autorest.Encode("path", networkGroupName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - if len(ifMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-Match", autorest.String(ifMatch))) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client GroupsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client GroupsClient) CreateOrUpdateResponder(resp *http.Response) (result Group, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a network group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// networkGroupName - the name of the network group. -// force - deletes the resource even if it is part of a deployed configuration. If the configuration has been -// deployed, the service will do a cleanup deployment in the background, prior to the delete. -func (client GroupsClient) Delete(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, force *bool) (result GroupsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkManagerName, networkGroupName, force) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GroupsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GroupsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client GroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, force *bool) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkGroupName": autorest.Encode("path", networkGroupName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if force != nil { - queryParameters["force"] = autorest.Encode("query", *force) - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client GroupsClient) DeleteSender(req *http.Request) (future GroupsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client GroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified network group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// networkGroupName - the name of the network group. -func (client GroupsClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string) (result Group, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkManagerName, networkGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GroupsClient", "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.GroupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GroupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client GroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkGroupName": autorest.Encode("path", networkGroupName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client GroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client GroupsClient) GetResponder(resp *http.Response) (result Group, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists the specified network group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -// skipToken - skipToken is only used if a previous operation returned a partial result. If a previous response -// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that -// specifies a starting point to use for subsequent calls. -func (client GroupsClient) List(ctx context.Context, resourceGroupName string, networkManagerName string, top *int32, skipToken string) (result GroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.List") - defer func() { - sc := -1 - if result.glr.Response.Response != nil { - sc = result.glr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.GroupsClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkManagerName, top, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GroupsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.glr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.GroupsClient", "List", resp, "Failure sending request") - return - } - - result.glr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GroupsClient", "List", resp, "Failure responding to request") - return - } - if result.glr.hasNextLink() && result.glr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client GroupsClient) ListPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, top *int32, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(skipToken) > 0 { - queryParameters["$skipToken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/networkGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client GroupsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client GroupsClient) ListResponder(resp *http.Response) (result GroupListResult, err error) { - err = autorest.Respond( - resp, - 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 GroupsClient) listNextResults(ctx context.Context, lastResults GroupListResult) (result GroupListResult, err error) { - req, err := lastResults.groupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.GroupsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.GroupsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GroupsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client GroupsClient) ListComplete(ctx context.Context, resourceGroupName string, networkManagerName string, top *int32, skipToken string) (result GroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkManagerName, top, skipToken) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/hubroutetables.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/hubroutetables.go deleted file mode 100644 index e2b54ffada..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/hubroutetables.go +++ /dev/null @@ -1,393 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// HubRouteTablesClient is the network Client -type HubRouteTablesClient struct { - BaseClient -} - -// NewHubRouteTablesClient creates an instance of the HubRouteTablesClient client. -func NewHubRouteTablesClient(subscriptionID string) HubRouteTablesClient { - return NewHubRouteTablesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewHubRouteTablesClientWithBaseURI creates an instance of the HubRouteTablesClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewHubRouteTablesClientWithBaseURI(baseURI string, subscriptionID string) HubRouteTablesClient { - return HubRouteTablesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a RouteTable resource if it doesn't exist else updates the existing RouteTable. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// routeTableName - the name of the RouteTable. -// routeTableParameters - parameters supplied to create or update RouteTable. -func (client HubRouteTablesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, routeTableParameters HubRouteTable) (result HubRouteTablesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/HubRouteTablesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualHubName, routeTableName, routeTableParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubRouteTablesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubRouteTablesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client HubRouteTablesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, routeTableParameters HubRouteTable) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - routeTableParameters.Etag = nil - routeTableParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubRouteTables/{routeTableName}", pathParameters), - autorest.WithJSON(routeTableParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client HubRouteTablesClient) CreateOrUpdateSender(req *http.Request) (future HubRouteTablesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client HubRouteTablesClient) CreateOrUpdateResponder(resp *http.Response) (result HubRouteTable, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a RouteTable. -// Parameters: -// resourceGroupName - the resource group name of the RouteTable. -// virtualHubName - the name of the VirtualHub. -// routeTableName - the name of the RouteTable. -func (client HubRouteTablesClient) Delete(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string) (result HubRouteTablesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/HubRouteTablesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualHubName, routeTableName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubRouteTablesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubRouteTablesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client HubRouteTablesClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/hubRouteTables/{routeTableName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client HubRouteTablesClient) DeleteSender(req *http.Request) (future HubRouteTablesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client HubRouteTablesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a RouteTable. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// routeTableName - the name of the RouteTable. -func (client HubRouteTablesClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string) (result HubRouteTable, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/HubRouteTablesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualHubName, routeTableName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubRouteTablesClient", "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.HubRouteTablesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubRouteTablesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client HubRouteTablesClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/hubRouteTables/{routeTableName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client HubRouteTablesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client HubRouteTablesClient) GetResponder(resp *http.Response) (result HubRouteTable, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List retrieves the details of all RouteTables. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -func (client HubRouteTablesClient) List(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListHubRouteTablesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/HubRouteTablesClient.List") - defer func() { - sc := -1 - if result.lhrtr.Response.Response != nil { - sc = result.lhrtr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualHubName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubRouteTablesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lhrtr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.HubRouteTablesClient", "List", resp, "Failure sending request") - return - } - - result.lhrtr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubRouteTablesClient", "List", resp, "Failure responding to request") - return - } - if result.lhrtr.hasNextLink() && result.lhrtr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client HubRouteTablesClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/hubRouteTables", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client HubRouteTablesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client HubRouteTablesClient) ListResponder(resp *http.Response) (result ListHubRouteTablesResult, err error) { - err = autorest.Respond( - resp, - 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 HubRouteTablesClient) listNextResults(ctx context.Context, lastResults ListHubRouteTablesResult) (result ListHubRouteTablesResult, err error) { - req, err := lastResults.listHubRouteTablesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.HubRouteTablesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.HubRouteTablesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubRouteTablesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client HubRouteTablesClient) ListComplete(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListHubRouteTablesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/HubRouteTablesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualHubName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/hubvirtualnetworkconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/hubvirtualnetworkconnections.go deleted file mode 100644 index 02031271f7..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/hubvirtualnetworkconnections.go +++ /dev/null @@ -1,394 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// HubVirtualNetworkConnectionsClient is the network Client -type HubVirtualNetworkConnectionsClient struct { - BaseClient -} - -// NewHubVirtualNetworkConnectionsClient creates an instance of the HubVirtualNetworkConnectionsClient client. -func NewHubVirtualNetworkConnectionsClient(subscriptionID string) HubVirtualNetworkConnectionsClient { - return NewHubVirtualNetworkConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewHubVirtualNetworkConnectionsClientWithBaseURI creates an instance of the HubVirtualNetworkConnectionsClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewHubVirtualNetworkConnectionsClientWithBaseURI(baseURI string, subscriptionID string) HubVirtualNetworkConnectionsClient { - return HubVirtualNetworkConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a hub virtual network connection if it doesn't exist else updates the existing one. -// Parameters: -// resourceGroupName - the resource group name of the HubVirtualNetworkConnection. -// virtualHubName - the name of the VirtualHub. -// connectionName - the name of the HubVirtualNetworkConnection. -// hubVirtualNetworkConnectionParameters - parameters supplied to create or update a hub virtual network -// connection. -func (client HubVirtualNetworkConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, hubVirtualNetworkConnectionParameters HubVirtualNetworkConnection) (result HubVirtualNetworkConnectionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualHubName, connectionName, hubVirtualNetworkConnectionParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client HubVirtualNetworkConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, hubVirtualNetworkConnectionParameters HubVirtualNetworkConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - hubVirtualNetworkConnectionParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections/{connectionName}", pathParameters), - autorest.WithJSON(hubVirtualNetworkConnectionParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client HubVirtualNetworkConnectionsClient) CreateOrUpdateSender(req *http.Request) (future HubVirtualNetworkConnectionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client HubVirtualNetworkConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result HubVirtualNetworkConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a HubVirtualNetworkConnection. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// connectionName - the name of the HubVirtualNetworkConnection. -func (client HubVirtualNetworkConnectionsClient) Delete(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (result HubVirtualNetworkConnectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualHubName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client HubVirtualNetworkConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client HubVirtualNetworkConnectionsClient) DeleteSender(req *http.Request) (future HubVirtualNetworkConnectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client HubVirtualNetworkConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a HubVirtualNetworkConnection. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// connectionName - the name of the vpn connection. -func (client HubVirtualNetworkConnectionsClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (result HubVirtualNetworkConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualHubName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "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.HubVirtualNetworkConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client HubVirtualNetworkConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client HubVirtualNetworkConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client HubVirtualNetworkConnectionsClient) GetResponder(resp *http.Response) (result HubVirtualNetworkConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List retrieves the details of all HubVirtualNetworkConnections. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -func (client HubVirtualNetworkConnectionsClient) List(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListHubVirtualNetworkConnectionsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.List") - defer func() { - sc := -1 - if result.lhvncr.Response.Response != nil { - sc = result.lhvncr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualHubName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lhvncr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.lhvncr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.lhvncr.hasNextLink() && result.lhvncr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client HubVirtualNetworkConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/hubVirtualNetworkConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client HubVirtualNetworkConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client HubVirtualNetworkConnectionsClient) ListResponder(resp *http.Response) (result ListHubVirtualNetworkConnectionsResult, err error) { - err = autorest.Respond( - resp, - 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 HubVirtualNetworkConnectionsClient) listNextResults(ctx context.Context, lastResults ListHubVirtualNetworkConnectionsResult) (result ListHubVirtualNetworkConnectionsResult, err error) { - req, err := lastResults.listHubVirtualNetworkConnectionsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client HubVirtualNetworkConnectionsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListHubVirtualNetworkConnectionsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/HubVirtualNetworkConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualHubName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/inboundnatrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/inboundnatrules.go deleted file mode 100644 index e0dfa3bd65..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/inboundnatrules.go +++ /dev/null @@ -1,419 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// InboundNatRulesClient is the network Client -type InboundNatRulesClient struct { - BaseClient -} - -// NewInboundNatRulesClient creates an instance of the InboundNatRulesClient client. -func NewInboundNatRulesClient(subscriptionID string) InboundNatRulesClient { - return NewInboundNatRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewInboundNatRulesClientWithBaseURI creates an instance of the InboundNatRulesClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewInboundNatRulesClientWithBaseURI(baseURI string, subscriptionID string) InboundNatRulesClient { - return InboundNatRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a load balancer inbound NAT rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// inboundNatRuleName - the name of the inbound NAT rule. -// inboundNatRuleParameters - parameters supplied to the create or update inbound NAT rule operation. -func (client InboundNatRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, inboundNatRuleParameters InboundNatRule) (result InboundNatRulesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRulesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: inboundNatRuleParameters, - Constraints: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, - }}, - {Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.ServicePublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - {Target: "inboundNatRuleParameters.InboundNatRulePropertiesFormat.BackendIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.LinkedPublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - }}, - }}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.InboundNatRulesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client InboundNatRulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, inboundNatRuleParameters InboundNatRule) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "inboundNatRuleName": autorest.Encode("path", inboundNatRuleName), - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - inboundNatRuleParameters.Etag = nil - inboundNatRuleParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}", pathParameters), - autorest.WithJSON(inboundNatRuleParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client InboundNatRulesClient) CreateOrUpdateSender(req *http.Request) (future InboundNatRulesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client InboundNatRulesClient) CreateOrUpdateResponder(resp *http.Response) (result InboundNatRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified load balancer inbound NAT rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// inboundNatRuleName - the name of the inbound NAT rule. -func (client InboundNatRulesClient) Delete(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string) (result InboundNatRulesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRulesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, loadBalancerName, inboundNatRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client InboundNatRulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "inboundNatRuleName": autorest.Encode("path", inboundNatRuleName), - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client InboundNatRulesClient) DeleteSender(req *http.Request) (future InboundNatRulesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client InboundNatRulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified load balancer inbound NAT rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// inboundNatRuleName - the name of the inbound NAT rule. -// expand - expands referenced resources. -func (client InboundNatRulesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, expand string) (result InboundNatRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, inboundNatRuleName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "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.InboundNatRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client InboundNatRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, inboundNatRuleName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "inboundNatRuleName": autorest.Encode("path", inboundNatRuleName), - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client InboundNatRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client InboundNatRulesClient) GetResponder(resp *http.Response) (result InboundNatRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the inbound NAT rules in a load balancer. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client InboundNatRulesClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result InboundNatRuleListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRulesClient.List") - defer func() { - sc := -1 - if result.inrlr.Response.Response != nil { - sc = result.inrlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.inrlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "List", resp, "Failure sending request") - return - } - - result.inrlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "List", resp, "Failure responding to request") - return - } - if result.inrlr.hasNextLink() && result.inrlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client InboundNatRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/inboundNatRules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client InboundNatRulesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client InboundNatRulesClient) ListResponder(resp *http.Response) (result InboundNatRuleListResult, err error) { - err = autorest.Respond( - resp, - 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 InboundNatRulesClient) listNextResults(ctx context.Context, lastResults InboundNatRuleListResult) (result InboundNatRuleListResult, err error) { - req, err := lastResults.inboundNatRuleListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client InboundNatRulesClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result InboundNatRuleListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRulesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/inboundsecurityrule.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/inboundsecurityrule.go deleted file mode 100644 index eb1144376d..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/inboundsecurityrule.go +++ /dev/null @@ -1,119 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// InboundSecurityRuleClient is the network Client -type InboundSecurityRuleClient struct { - BaseClient -} - -// NewInboundSecurityRuleClient creates an instance of the InboundSecurityRuleClient client. -func NewInboundSecurityRuleClient(subscriptionID string) InboundSecurityRuleClient { - return NewInboundSecurityRuleClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewInboundSecurityRuleClientWithBaseURI creates an instance of the InboundSecurityRuleClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewInboundSecurityRuleClientWithBaseURI(baseURI string, subscriptionID string) InboundSecurityRuleClient { - return InboundSecurityRuleClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates the specified Network Virtual Appliance Inbound Security Rules. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkVirtualApplianceName - the name of the Network Virtual Appliance. -// ruleCollectionName - the name of security rule collection. -// parameters - parameters supplied to the create or update Network Virtual Appliance Inbound Security Rules -// operation. -func (client InboundSecurityRuleClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, ruleCollectionName string, parameters InboundSecurityRule) (result InboundSecurityRuleCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundSecurityRuleClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkVirtualApplianceName, ruleCollectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundSecurityRuleClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundSecurityRuleClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client InboundSecurityRuleClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, ruleCollectionName string, parameters InboundSecurityRule) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkVirtualApplianceName": autorest.Encode("path", networkVirtualApplianceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "ruleCollectionName": autorest.Encode("path", ruleCollectionName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - parameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}/inboundSecurityRules/{ruleCollectionName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client InboundSecurityRuleClient) CreateOrUpdateSender(req *http.Request) (future InboundSecurityRuleCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client InboundSecurityRuleClient) CreateOrUpdateResponder(resp *http.Response) (result InboundSecurityRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/interfaceipconfigurations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/interfaceipconfigurations.go deleted file mode 100644 index 38d87b3d5a..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/interfaceipconfigurations.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// InterfaceIPConfigurationsClient is the network Client -type InterfaceIPConfigurationsClient struct { - BaseClient -} - -// NewInterfaceIPConfigurationsClient creates an instance of the InterfaceIPConfigurationsClient client. -func NewInterfaceIPConfigurationsClient(subscriptionID string) InterfaceIPConfigurationsClient { - return NewInterfaceIPConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewInterfaceIPConfigurationsClientWithBaseURI creates an instance of the InterfaceIPConfigurationsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewInterfaceIPConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) InterfaceIPConfigurationsClient { - return InterfaceIPConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets the specified network interface ip configuration. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// IPConfigurationName - the name of the ip configuration name. -func (client InterfaceIPConfigurationsClient) Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, IPConfigurationName string) (result InterfaceIPConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceIPConfigurationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkInterfaceName, IPConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "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.InterfaceIPConfigurationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client InterfaceIPConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, IPConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipConfigurationName": autorest.Encode("path", IPConfigurationName), - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkInterfaces/{networkInterfaceName}/ipConfigurations/{ipConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceIPConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client InterfaceIPConfigurationsClient) GetResponder(resp *http.Response) (result InterfaceIPConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List get all ip configurations in a network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -func (client InterfaceIPConfigurationsClient) List(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceIPConfigurationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceIPConfigurationsClient.List") - defer func() { - sc := -1 - if result.iiclr.Response.Response != nil { - sc = result.iiclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkInterfaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.iiclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "List", resp, "Failure sending request") - return - } - - result.iiclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "List", resp, "Failure responding to request") - return - } - if result.iiclr.hasNextLink() && result.iiclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client InterfaceIPConfigurationsClient) ListPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkInterfaces/{networkInterfaceName}/ipConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceIPConfigurationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client InterfaceIPConfigurationsClient) ListResponder(resp *http.Response) (result InterfaceIPConfigurationListResult, err error) { - err = autorest.Respond( - resp, - 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 InterfaceIPConfigurationsClient) listNextResults(ctx context.Context, lastResults InterfaceIPConfigurationListResult) (result InterfaceIPConfigurationListResult, err error) { - req, err := lastResults.interfaceIPConfigurationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceIPConfigurationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfaceIPConfigurationsClient) ListComplete(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceIPConfigurationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceIPConfigurationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkInterfaceName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/interfaceloadbalancers.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/interfaceloadbalancers.go deleted file mode 100644 index a7b2666852..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/interfaceloadbalancers.go +++ /dev/null @@ -1,150 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// InterfaceLoadBalancersClient is the network Client -type InterfaceLoadBalancersClient struct { - BaseClient -} - -// NewInterfaceLoadBalancersClient creates an instance of the InterfaceLoadBalancersClient client. -func NewInterfaceLoadBalancersClient(subscriptionID string) InterfaceLoadBalancersClient { - return NewInterfaceLoadBalancersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewInterfaceLoadBalancersClientWithBaseURI creates an instance of the InterfaceLoadBalancersClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewInterfaceLoadBalancersClientWithBaseURI(baseURI string, subscriptionID string) InterfaceLoadBalancersClient { - return InterfaceLoadBalancersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List list all load balancers in a network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -func (client InterfaceLoadBalancersClient) List(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceLoadBalancerListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceLoadBalancersClient.List") - defer func() { - sc := -1 - if result.ilblr.Response.Response != nil { - sc = result.ilblr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkInterfaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceLoadBalancersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ilblr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfaceLoadBalancersClient", "List", resp, "Failure sending request") - return - } - - result.ilblr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceLoadBalancersClient", "List", resp, "Failure responding to request") - return - } - if result.ilblr.hasNextLink() && result.ilblr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client InterfaceLoadBalancersClient) ListPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkInterfaces/{networkInterfaceName}/loadBalancers", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceLoadBalancersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client InterfaceLoadBalancersClient) ListResponder(resp *http.Response) (result InterfaceLoadBalancerListResult, err error) { - err = autorest.Respond( - resp, - 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 InterfaceLoadBalancersClient) listNextResults(ctx context.Context, lastResults InterfaceLoadBalancerListResult) (result InterfaceLoadBalancerListResult, err error) { - req, err := lastResults.interfaceLoadBalancerListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfaceLoadBalancersClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfaceLoadBalancersClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceLoadBalancersClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfaceLoadBalancersClient) ListComplete(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceLoadBalancerListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceLoadBalancersClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkInterfaceName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/interfacesgroup.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/interfacesgroup.go deleted file mode 100644 index 9e95b95955..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/interfacesgroup.go +++ /dev/null @@ -1,1598 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// InterfacesClient is the network Client -type InterfacesClient struct { - BaseClient -} - -// NewInterfacesClient creates an instance of the InterfacesClient client. -func NewInterfacesClient(subscriptionID string) InterfacesClient { - return NewInterfacesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewInterfacesClientWithBaseURI creates an instance of the InterfacesClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewInterfacesClientWithBaseURI(baseURI string, subscriptionID string) InterfacesClient { - return InterfacesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// parameters - parameters supplied to the create or update network interface operation. -func (client InterfacesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters Interface) (result InterfacesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkInterfaceName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client InterfacesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters Interface) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) CreateOrUpdateSender(req *http.Request) (future InterfacesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client InterfacesClient) CreateOrUpdateResponder(resp *http.Response) (result Interface, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -func (client InterfacesClient) Delete(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfacesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkInterfaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client InterfacesClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkInterfaces/{networkInterfaceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) DeleteSender(req *http.Request) (future InterfacesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client InterfacesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets information about the specified network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// expand - expands referenced resources. -func (client InterfacesClient) Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, expand string) (result Interface, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkInterfaceName, expand) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client InterfacesClient) GetPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkInterfaces/{networkInterfaceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client InterfacesClient) GetResponder(resp *http.Response) (result Interface, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetCloudServiceNetworkInterface get the specified network interface in a cloud service. -// Parameters: -// resourceGroupName - the name of the resource group. -// cloudServiceName - the name of the cloud service. -// roleInstanceName - the name of role instance. -// networkInterfaceName - the name of the network interface. -// expand - expands referenced resources. -func (client InterfacesClient) GetCloudServiceNetworkInterface(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string, networkInterfaceName string, expand string) (result Interface, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.GetCloudServiceNetworkInterface") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetCloudServiceNetworkInterfacePreparer(ctx, resourceGroupName, cloudServiceName, roleInstanceName, networkInterfaceName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetCloudServiceNetworkInterface", nil, "Failure preparing request") - return - } - - resp, err := client.GetCloudServiceNetworkInterfaceSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetCloudServiceNetworkInterface", resp, "Failure sending request") - return - } - - result, err = client.GetCloudServiceNetworkInterfaceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetCloudServiceNetworkInterface", resp, "Failure responding to request") - return - } - - return -} - -// GetCloudServiceNetworkInterfacePreparer prepares the GetCloudServiceNetworkInterface request. -func (client InterfacesClient) GetCloudServiceNetworkInterfacePreparer(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string, networkInterfaceName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "cloudServiceName": autorest.Encode("path", cloudServiceName), - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "roleInstanceName": autorest.Encode("path", roleInstanceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/networkInterfaces/{networkInterfaceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetCloudServiceNetworkInterfaceSender sends the GetCloudServiceNetworkInterface request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) GetCloudServiceNetworkInterfaceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetCloudServiceNetworkInterfaceResponder handles the response to the GetCloudServiceNetworkInterface request. The method always -// closes the http.Response Body. -func (client InterfacesClient) GetCloudServiceNetworkInterfaceResponder(resp *http.Response) (result Interface, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetEffectiveRouteTable gets all route tables applied to a network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -func (client InterfacesClient) GetEffectiveRouteTable(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfacesGetEffectiveRouteTableFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.GetEffectiveRouteTable") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetEffectiveRouteTablePreparer(ctx, resourceGroupName, networkInterfaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetEffectiveRouteTable", nil, "Failure preparing request") - return - } - - result, err = client.GetEffectiveRouteTableSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetEffectiveRouteTable", result.Response(), "Failure sending request") - return - } - - return -} - -// GetEffectiveRouteTablePreparer prepares the GetEffectiveRouteTable request. -func (client InterfacesClient) GetEffectiveRouteTablePreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkInterfaces/{networkInterfaceName}/effectiveRouteTable", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetEffectiveRouteTableSender sends the GetEffectiveRouteTable request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) GetEffectiveRouteTableSender(req *http.Request) (future InterfacesGetEffectiveRouteTableFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetEffectiveRouteTableResponder handles the response to the GetEffectiveRouteTable request. The method always -// closes the http.Response Body. -func (client InterfacesClient) GetEffectiveRouteTableResponder(resp *http.Response) (result EffectiveRouteListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetVirtualMachineScaleSetIPConfiguration get the specified network interface ip configuration in a virtual machine -// scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -// virtualmachineIndex - the virtual machine index. -// networkInterfaceName - the name of the network interface. -// IPConfigurationName - the name of the ip configuration. -// expand - expands referenced resources. -func (client InterfacesClient) GetVirtualMachineScaleSetIPConfiguration(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, expand string) (result InterfaceIPConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.GetVirtualMachineScaleSetIPConfiguration") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetVirtualMachineScaleSetIPConfigurationPreparer(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetIPConfiguration", nil, "Failure preparing request") - return - } - - resp, err := client.GetVirtualMachineScaleSetIPConfigurationSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetIPConfiguration", resp, "Failure sending request") - return - } - - result, err = client.GetVirtualMachineScaleSetIPConfigurationResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetIPConfiguration", resp, "Failure responding to request") - return - } - - return -} - -// GetVirtualMachineScaleSetIPConfigurationPreparer prepares the GetVirtualMachineScaleSetIPConfiguration request. -func (client InterfacesClient) GetVirtualMachineScaleSetIPConfigurationPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipConfigurationName": autorest.Encode("path", IPConfigurationName), - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2018-10-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.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipConfigurations/{ipConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetVirtualMachineScaleSetIPConfigurationSender sends the GetVirtualMachineScaleSetIPConfiguration request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) GetVirtualMachineScaleSetIPConfigurationSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetVirtualMachineScaleSetIPConfigurationResponder handles the response to the GetVirtualMachineScaleSetIPConfiguration request. The method always -// closes the http.Response Body. -func (client InterfacesClient) GetVirtualMachineScaleSetIPConfigurationResponder(resp *http.Response) (result InterfaceIPConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetVirtualMachineScaleSetNetworkInterface get the specified network interface in a virtual machine scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -// virtualmachineIndex - the virtual machine index. -// networkInterfaceName - the name of the network interface. -// expand - expands referenced resources. -func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (result Interface, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.GetVirtualMachineScaleSetNetworkInterface") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetVirtualMachineScaleSetNetworkInterfacePreparer(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", resp, "Failure sending request") - return - } - - result, err = client.GetVirtualMachineScaleSetNetworkInterfaceResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", resp, "Failure responding to request") - return - } - - return -} - -// GetVirtualMachineScaleSetNetworkInterfacePreparer prepares the GetVirtualMachineScaleSetNetworkInterface request. -func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfacePreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2018-10-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.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetVirtualMachineScaleSetNetworkInterfaceSender sends the GetVirtualMachineScaleSetNetworkInterface request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfaceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetVirtualMachineScaleSetNetworkInterfaceResponder handles the response to the GetVirtualMachineScaleSetNetworkInterface request. The method always -// closes the http.Response Body. -func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfaceResponder(resp *http.Response) (result Interface, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all network interfaces in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client InterfacesClient) List(ctx context.Context, resourceGroupName string) (result InterfaceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.List") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client InterfacesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkInterfaces", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListResponder(resp *http.Response) (result InterfaceListResult, err error) { - err = autorest.Respond( - resp, - 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 InterfacesClient) listNextResults(ctx context.Context, lastResults InterfaceListResult) (result InterfaceListResult, err error) { - req, err := lastResults.interfaceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfacesClient) ListComplete(ctx context.Context, resourceGroupName string) (result InterfaceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all network interfaces in a subscription. -func (client InterfacesClient) ListAll(ctx context.Context) (result InterfaceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListAll") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client InterfacesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkInterfaces", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListAllResponder(resp *http.Response) (result InterfaceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client InterfacesClient) listAllNextResults(ctx context.Context, lastResults InterfaceListResult) (result InterfaceListResult, err error) { - req, err := lastResults.interfaceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfacesClient) ListAllComplete(ctx context.Context) (result InterfaceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListCloudServiceNetworkInterfaces gets all network interfaces in a cloud service. -// Parameters: -// resourceGroupName - the name of the resource group. -// cloudServiceName - the name of the cloud service. -func (client InterfacesClient) ListCloudServiceNetworkInterfaces(ctx context.Context, resourceGroupName string, cloudServiceName string) (result InterfaceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListCloudServiceNetworkInterfaces") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listCloudServiceNetworkInterfacesNextResults - req, err := client.ListCloudServiceNetworkInterfacesPreparer(ctx, resourceGroupName, cloudServiceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListCloudServiceNetworkInterfaces", nil, "Failure preparing request") - return - } - - resp, err := client.ListCloudServiceNetworkInterfacesSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListCloudServiceNetworkInterfaces", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListCloudServiceNetworkInterfacesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListCloudServiceNetworkInterfaces", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListCloudServiceNetworkInterfacesPreparer prepares the ListCloudServiceNetworkInterfaces request. -func (client InterfacesClient) ListCloudServiceNetworkInterfacesPreparer(ctx context.Context, resourceGroupName string, cloudServiceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "cloudServiceName": autorest.Encode("path", cloudServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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.Compute/cloudServices/{cloudServiceName}/networkInterfaces", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListCloudServiceNetworkInterfacesSender sends the ListCloudServiceNetworkInterfaces request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListCloudServiceNetworkInterfacesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListCloudServiceNetworkInterfacesResponder handles the response to the ListCloudServiceNetworkInterfaces request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListCloudServiceNetworkInterfacesResponder(resp *http.Response) (result InterfaceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listCloudServiceNetworkInterfacesNextResults retrieves the next set of results, if any. -func (client InterfacesClient) listCloudServiceNetworkInterfacesNextResults(ctx context.Context, lastResults InterfaceListResult) (result InterfaceListResult, err error) { - req, err := lastResults.interfaceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listCloudServiceNetworkInterfacesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListCloudServiceNetworkInterfacesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listCloudServiceNetworkInterfacesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListCloudServiceNetworkInterfacesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "listCloudServiceNetworkInterfacesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListCloudServiceNetworkInterfacesComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfacesClient) ListCloudServiceNetworkInterfacesComplete(ctx context.Context, resourceGroupName string, cloudServiceName string) (result InterfaceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListCloudServiceNetworkInterfaces") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListCloudServiceNetworkInterfaces(ctx, resourceGroupName, cloudServiceName) - return -} - -// ListCloudServiceRoleInstanceNetworkInterfaces gets information about all network interfaces in a role instance in a -// cloud service. -// Parameters: -// resourceGroupName - the name of the resource group. -// cloudServiceName - the name of the cloud service. -// roleInstanceName - the name of role instance. -func (client InterfacesClient) ListCloudServiceRoleInstanceNetworkInterfaces(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string) (result InterfaceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListCloudServiceRoleInstanceNetworkInterfaces") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listCloudServiceRoleInstanceNetworkInterfacesNextResults - req, err := client.ListCloudServiceRoleInstanceNetworkInterfacesPreparer(ctx, resourceGroupName, cloudServiceName, roleInstanceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListCloudServiceRoleInstanceNetworkInterfaces", nil, "Failure preparing request") - return - } - - resp, err := client.ListCloudServiceRoleInstanceNetworkInterfacesSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListCloudServiceRoleInstanceNetworkInterfaces", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListCloudServiceRoleInstanceNetworkInterfacesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListCloudServiceRoleInstanceNetworkInterfaces", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListCloudServiceRoleInstanceNetworkInterfacesPreparer prepares the ListCloudServiceRoleInstanceNetworkInterfaces request. -func (client InterfacesClient) ListCloudServiceRoleInstanceNetworkInterfacesPreparer(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "cloudServiceName": autorest.Encode("path", cloudServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "roleInstanceName": autorest.Encode("path", roleInstanceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/networkInterfaces", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListCloudServiceRoleInstanceNetworkInterfacesSender sends the ListCloudServiceRoleInstanceNetworkInterfaces request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListCloudServiceRoleInstanceNetworkInterfacesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListCloudServiceRoleInstanceNetworkInterfacesResponder handles the response to the ListCloudServiceRoleInstanceNetworkInterfaces request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListCloudServiceRoleInstanceNetworkInterfacesResponder(resp *http.Response) (result InterfaceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listCloudServiceRoleInstanceNetworkInterfacesNextResults retrieves the next set of results, if any. -func (client InterfacesClient) listCloudServiceRoleInstanceNetworkInterfacesNextResults(ctx context.Context, lastResults InterfaceListResult) (result InterfaceListResult, err error) { - req, err := lastResults.interfaceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listCloudServiceRoleInstanceNetworkInterfacesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListCloudServiceRoleInstanceNetworkInterfacesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listCloudServiceRoleInstanceNetworkInterfacesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListCloudServiceRoleInstanceNetworkInterfacesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "listCloudServiceRoleInstanceNetworkInterfacesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListCloudServiceRoleInstanceNetworkInterfacesComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfacesClient) ListCloudServiceRoleInstanceNetworkInterfacesComplete(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string) (result InterfaceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListCloudServiceRoleInstanceNetworkInterfaces") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListCloudServiceRoleInstanceNetworkInterfaces(ctx, resourceGroupName, cloudServiceName, roleInstanceName) - return -} - -// ListEffectiveNetworkSecurityGroups gets all network security groups applied to a network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -func (client InterfacesClient) ListEffectiveNetworkSecurityGroups(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfacesListEffectiveNetworkSecurityGroupsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListEffectiveNetworkSecurityGroups") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListEffectiveNetworkSecurityGroupsPreparer(ctx, resourceGroupName, networkInterfaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListEffectiveNetworkSecurityGroups", nil, "Failure preparing request") - return - } - - result, err = client.ListEffectiveNetworkSecurityGroupsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListEffectiveNetworkSecurityGroups", result.Response(), "Failure sending request") - return - } - - return -} - -// ListEffectiveNetworkSecurityGroupsPreparer prepares the ListEffectiveNetworkSecurityGroups request. -func (client InterfacesClient) ListEffectiveNetworkSecurityGroupsPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkInterfaces/{networkInterfaceName}/effectiveNetworkSecurityGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListEffectiveNetworkSecurityGroupsSender sends the ListEffectiveNetworkSecurityGroups request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListEffectiveNetworkSecurityGroupsSender(req *http.Request) (future InterfacesListEffectiveNetworkSecurityGroupsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListEffectiveNetworkSecurityGroupsResponder handles the response to the ListEffectiveNetworkSecurityGroups request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListEffectiveNetworkSecurityGroupsResponder(resp *http.Response) (result EffectiveNetworkSecurityGroupListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListVirtualMachineScaleSetIPConfigurations get the specified network interface ip configuration in a virtual machine -// scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -// virtualmachineIndex - the virtual machine index. -// networkInterfaceName - the name of the network interface. -// expand - expands referenced resources. -func (client InterfacesClient) ListVirtualMachineScaleSetIPConfigurations(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (result InterfaceIPConfigurationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListVirtualMachineScaleSetIPConfigurations") - defer func() { - sc := -1 - if result.iiclr.Response.Response != nil { - sc = result.iiclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listVirtualMachineScaleSetIPConfigurationsNextResults - req, err := client.ListVirtualMachineScaleSetIPConfigurationsPreparer(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetIPConfigurations", nil, "Failure preparing request") - return - } - - resp, err := client.ListVirtualMachineScaleSetIPConfigurationsSender(req) - if err != nil { - result.iiclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetIPConfigurations", resp, "Failure sending request") - return - } - - result.iiclr, err = client.ListVirtualMachineScaleSetIPConfigurationsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetIPConfigurations", resp, "Failure responding to request") - return - } - if result.iiclr.hasNextLink() && result.iiclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListVirtualMachineScaleSetIPConfigurationsPreparer prepares the ListVirtualMachineScaleSetIPConfigurations request. -func (client InterfacesClient) ListVirtualMachineScaleSetIPConfigurationsPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2018-10-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.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListVirtualMachineScaleSetIPConfigurationsSender sends the ListVirtualMachineScaleSetIPConfigurations request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListVirtualMachineScaleSetIPConfigurationsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListVirtualMachineScaleSetIPConfigurationsResponder handles the response to the ListVirtualMachineScaleSetIPConfigurations request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListVirtualMachineScaleSetIPConfigurationsResponder(resp *http.Response) (result InterfaceIPConfigurationListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listVirtualMachineScaleSetIPConfigurationsNextResults retrieves the next set of results, if any. -func (client InterfacesClient) listVirtualMachineScaleSetIPConfigurationsNextResults(ctx context.Context, lastResults InterfaceIPConfigurationListResult) (result InterfaceIPConfigurationListResult, err error) { - req, err := lastResults.interfaceIPConfigurationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetIPConfigurationsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListVirtualMachineScaleSetIPConfigurationsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetIPConfigurationsNextResults", resp, "Failure sending next results request") - } - result, err = client.ListVirtualMachineScaleSetIPConfigurationsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetIPConfigurationsNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListVirtualMachineScaleSetIPConfigurationsComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfacesClient) ListVirtualMachineScaleSetIPConfigurationsComplete(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (result InterfaceIPConfigurationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListVirtualMachineScaleSetIPConfigurations") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListVirtualMachineScaleSetIPConfigurations(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand) - return -} - -// ListVirtualMachineScaleSetNetworkInterfaces gets all network interfaces in a virtual machine scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfaces(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) (result InterfaceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListVirtualMachineScaleSetNetworkInterfaces") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listVirtualMachineScaleSetNetworkInterfacesNextResults - req, err := client.ListVirtualMachineScaleSetNetworkInterfacesPreparer(ctx, resourceGroupName, virtualMachineScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", nil, "Failure preparing request") - return - } - - resp, err := client.ListVirtualMachineScaleSetNetworkInterfacesSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListVirtualMachineScaleSetNetworkInterfacesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListVirtualMachineScaleSetNetworkInterfacesPreparer prepares the ListVirtualMachineScaleSetNetworkInterfaces request. -func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2018-10-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.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/networkInterfaces", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListVirtualMachineScaleSetNetworkInterfacesSender sends the ListVirtualMachineScaleSetNetworkInterfaces request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListVirtualMachineScaleSetNetworkInterfacesResponder handles the response to the ListVirtualMachineScaleSetNetworkInterfaces request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesResponder(resp *http.Response) (result InterfaceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listVirtualMachineScaleSetNetworkInterfacesNextResults retrieves the next set of results, if any. -func (client InterfacesClient) listVirtualMachineScaleSetNetworkInterfacesNextResults(ctx context.Context, lastResults InterfaceListResult) (result InterfaceListResult, err error) { - req, err := lastResults.interfaceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetNetworkInterfacesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListVirtualMachineScaleSetNetworkInterfacesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetNetworkInterfacesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListVirtualMachineScaleSetNetworkInterfacesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetNetworkInterfacesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListVirtualMachineScaleSetNetworkInterfacesComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesComplete(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) (result InterfaceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListVirtualMachineScaleSetNetworkInterfaces") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListVirtualMachineScaleSetNetworkInterfaces(ctx, resourceGroupName, virtualMachineScaleSetName) - return -} - -// ListVirtualMachineScaleSetVMNetworkInterfaces gets information about all network interfaces in a virtual machine in -// a virtual machine scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -// virtualmachineIndex - the virtual machine index. -func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfaces(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string) (result InterfaceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListVirtualMachineScaleSetVMNetworkInterfaces") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listVirtualMachineScaleSetVMNetworkInterfacesNextResults - req, err := client.ListVirtualMachineScaleSetVMNetworkInterfacesPreparer(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", nil, "Failure preparing request") - return - } - - resp, err := client.ListVirtualMachineScaleSetVMNetworkInterfacesSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListVirtualMachineScaleSetVMNetworkInterfacesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListVirtualMachineScaleSetVMNetworkInterfacesPreparer prepares the ListVirtualMachineScaleSetVMNetworkInterfaces request. -func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2018-10-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.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListVirtualMachineScaleSetVMNetworkInterfacesSender sends the ListVirtualMachineScaleSetVMNetworkInterfaces request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListVirtualMachineScaleSetVMNetworkInterfacesResponder handles the response to the ListVirtualMachineScaleSetVMNetworkInterfaces request. The method always -// closes the http.Response Body. -func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesResponder(resp *http.Response) (result InterfaceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listVirtualMachineScaleSetVMNetworkInterfacesNextResults retrieves the next set of results, if any. -func (client InterfacesClient) listVirtualMachineScaleSetVMNetworkInterfacesNextResults(ctx context.Context, lastResults InterfaceListResult) (result InterfaceListResult, err error) { - req, err := lastResults.interfaceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetVMNetworkInterfacesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListVirtualMachineScaleSetVMNetworkInterfacesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetVMNetworkInterfacesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListVirtualMachineScaleSetVMNetworkInterfacesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "listVirtualMachineScaleSetVMNetworkInterfacesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListVirtualMachineScaleSetVMNetworkInterfacesComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesComplete(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string) (result InterfaceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.ListVirtualMachineScaleSetVMNetworkInterfaces") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListVirtualMachineScaleSetVMNetworkInterfaces(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex) - return -} - -// UpdateTags updates a network interface tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// parameters - parameters supplied to update network interface tags. -func (client InterfacesClient) UpdateTags(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters TagsObject) (result Interface, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfacesClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, networkInterfaceName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client InterfacesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client InterfacesClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client InterfacesClient) UpdateTagsResponder(resp *http.Response) (result Interface, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/interfacetapconfigurations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/interfacetapconfigurations.go deleted file mode 100644 index 12b4a11028..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/interfacetapconfigurations.go +++ /dev/null @@ -1,434 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// InterfaceTapConfigurationsClient is the network Client -type InterfaceTapConfigurationsClient struct { - BaseClient -} - -// NewInterfaceTapConfigurationsClient creates an instance of the InterfaceTapConfigurationsClient client. -func NewInterfaceTapConfigurationsClient(subscriptionID string) InterfaceTapConfigurationsClient { - return NewInterfaceTapConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewInterfaceTapConfigurationsClientWithBaseURI creates an instance of the InterfaceTapConfigurationsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewInterfaceTapConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) InterfaceTapConfigurationsClient { - return InterfaceTapConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a Tap configuration in the specified NetworkInterface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// tapConfigurationName - the name of the tap configuration. -// tapConfigurationParameters - parameters supplied to the create or update tap configuration operation. -func (client InterfaceTapConfigurationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, tapConfigurationParameters InterfaceTapConfiguration) (result InterfaceTapConfigurationsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: tapConfigurationParameters, - Constraints: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, - }}, - {Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.ServicePublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - {Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.LinkedPublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - }}, - }}, - }}, - }}, - {Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, - }}, - {Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.ServicePublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - {Target: "tapConfigurationParameters.InterfaceTapConfigurationPropertiesFormat.VirtualNetworkTap.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.LinkedPublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - }}, - }}, - }}, - }}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.InterfaceTapConfigurationsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkInterfaceName, tapConfigurationName, tapConfigurationParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client InterfaceTapConfigurationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string, tapConfigurationParameters InterfaceTapConfiguration) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapConfigurationName": autorest.Encode("path", tapConfigurationName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - tapConfigurationParameters.Etag = nil - tapConfigurationParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/tapConfigurations/{tapConfigurationName}", pathParameters), - autorest.WithJSON(tapConfigurationParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceTapConfigurationsClient) CreateOrUpdateSender(req *http.Request) (future InterfaceTapConfigurationsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client InterfaceTapConfigurationsClient) CreateOrUpdateResponder(resp *http.Response) (result InterfaceTapConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified tap configuration from the NetworkInterface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// tapConfigurationName - the name of the tap configuration. -func (client InterfaceTapConfigurationsClient) Delete(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string) (result InterfaceTapConfigurationsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkInterfaceName, tapConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client InterfaceTapConfigurationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapConfigurationName": autorest.Encode("path", tapConfigurationName), - } - - const APIVersion = "2022-07-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/networkInterfaces/{networkInterfaceName}/tapConfigurations/{tapConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceTapConfigurationsClient) DeleteSender(req *http.Request) (future InterfaceTapConfigurationsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client InterfaceTapConfigurationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the specified tap configuration on a network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -// tapConfigurationName - the name of the tap configuration. -func (client InterfaceTapConfigurationsClient) Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string) (result InterfaceTapConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkInterfaceName, tapConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "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.InterfaceTapConfigurationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client InterfaceTapConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string, tapConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapConfigurationName": autorest.Encode("path", tapConfigurationName), - } - - const APIVersion = "2022-07-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/networkInterfaces/{networkInterfaceName}/tapConfigurations/{tapConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceTapConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client InterfaceTapConfigurationsClient) GetResponder(resp *http.Response) (result InterfaceTapConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List get all Tap configurations in a network interface. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkInterfaceName - the name of the network interface. -func (client InterfaceTapConfigurationsClient) List(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceTapConfigurationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.List") - defer func() { - sc := -1 - if result.itclr.Response.Response != nil { - sc = result.itclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkInterfaceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.itclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "List", resp, "Failure sending request") - return - } - - result.itclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "List", resp, "Failure responding to request") - return - } - if result.itclr.hasNextLink() && result.itclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client InterfaceTapConfigurationsClient) ListPreparer(ctx context.Context, resourceGroupName string, networkInterfaceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkInterfaces/{networkInterfaceName}/tapConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client InterfaceTapConfigurationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client InterfaceTapConfigurationsClient) ListResponder(resp *http.Response) (result InterfaceTapConfigurationListResult, err error) { - err = autorest.Respond( - resp, - 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 InterfaceTapConfigurationsClient) listNextResults(ctx context.Context, lastResults InterfaceTapConfigurationListResult) (result InterfaceTapConfigurationListResult, err error) { - req, err := lastResults.interfaceTapConfigurationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client InterfaceTapConfigurationsClient) ListComplete(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result InterfaceTapConfigurationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkInterfaceName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/ipallocations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/ipallocations.go deleted file mode 100644 index 5cfbec8391..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/ipallocations.go +++ /dev/null @@ -1,580 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// IPAllocationsClient is the network Client -type IPAllocationsClient struct { - BaseClient -} - -// NewIPAllocationsClient creates an instance of the IPAllocationsClient client. -func NewIPAllocationsClient(subscriptionID string) IPAllocationsClient { - return NewIPAllocationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewIPAllocationsClientWithBaseURI creates an instance of the IPAllocationsClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewIPAllocationsClientWithBaseURI(baseURI string, subscriptionID string) IPAllocationsClient { - return IPAllocationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates an IpAllocation in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// IPAllocationName - the name of the IpAllocation. -// parameters - parameters supplied to the create or update virtual network operation. -func (client IPAllocationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, IPAllocationName string, parameters IPAllocation) (result IPAllocationsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPAllocationsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, IPAllocationName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client IPAllocationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, IPAllocationName string, parameters IPAllocation) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipAllocationName": autorest.Encode("path", IPAllocationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/IpAllocations/{ipAllocationName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client IPAllocationsClient) CreateOrUpdateSender(req *http.Request) (future IPAllocationsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client IPAllocationsClient) CreateOrUpdateResponder(resp *http.Response) (result IPAllocation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified IpAllocation. -// Parameters: -// resourceGroupName - the name of the resource group. -// IPAllocationName - the name of the IpAllocation. -func (client IPAllocationsClient) Delete(ctx context.Context, resourceGroupName string, IPAllocationName string) (result IPAllocationsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPAllocationsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, IPAllocationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client IPAllocationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, IPAllocationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipAllocationName": autorest.Encode("path", IPAllocationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/IpAllocations/{ipAllocationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client IPAllocationsClient) DeleteSender(req *http.Request) (future IPAllocationsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client IPAllocationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified IpAllocation by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// IPAllocationName - the name of the IpAllocation. -// expand - expands referenced resources. -func (client IPAllocationsClient) Get(ctx context.Context, resourceGroupName string, IPAllocationName string, expand string) (result IPAllocation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPAllocationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, IPAllocationName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "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.IPAllocationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client IPAllocationsClient) GetPreparer(ctx context.Context, resourceGroupName string, IPAllocationName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipAllocationName": autorest.Encode("path", IPAllocationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/IpAllocations/{ipAllocationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client IPAllocationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client IPAllocationsClient) GetResponder(resp *http.Response) (result IPAllocation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all IpAllocations in a subscription. -func (client IPAllocationsClient) List(ctx context.Context) (result IPAllocationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPAllocationsClient.List") - defer func() { - sc := -1 - if result.ialr.Response.Response != nil { - sc = result.ialr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ialr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "List", resp, "Failure sending request") - return - } - - result.ialr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "List", resp, "Failure responding to request") - return - } - if result.ialr.hasNextLink() && result.ialr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client IPAllocationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/IpAllocations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client IPAllocationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client IPAllocationsClient) ListResponder(resp *http.Response) (result IPAllocationListResult, err error) { - err = autorest.Respond( - resp, - 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 IPAllocationsClient) listNextResults(ctx context.Context, lastResults IPAllocationListResult) (result IPAllocationListResult, err error) { - req, err := lastResults.iPAllocationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.IPAllocationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.IPAllocationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client IPAllocationsClient) ListComplete(ctx context.Context) (result IPAllocationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPAllocationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup gets all IpAllocations in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client IPAllocationsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result IPAllocationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPAllocationsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.ialr.Response.Response != nil { - sc = result.ialr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.ialr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.ialr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.ialr.hasNextLink() && result.ialr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client IPAllocationsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/IpAllocations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client IPAllocationsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client IPAllocationsClient) ListByResourceGroupResponder(resp *http.Response) (result IPAllocationListResult, err error) { - err = autorest.Respond( - resp, - 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 IPAllocationsClient) listByResourceGroupNextResults(ctx context.Context, lastResults IPAllocationListResult) (result IPAllocationListResult, err error) { - req, err := lastResults.iPAllocationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.IPAllocationsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.IPAllocationsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client IPAllocationsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result IPAllocationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPAllocationsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates a IpAllocation tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// IPAllocationName - the name of the IpAllocation. -// parameters - parameters supplied to update IpAllocation tags. -func (client IPAllocationsClient) UpdateTags(ctx context.Context, resourceGroupName string, IPAllocationName string, parameters TagsObject) (result IPAllocation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPAllocationsClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, IPAllocationName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client IPAllocationsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, IPAllocationName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipAllocationName": autorest.Encode("path", IPAllocationName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/IpAllocations/{ipAllocationName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client IPAllocationsClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client IPAllocationsClient) UpdateTagsResponder(resp *http.Response) (result IPAllocation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/ipgroups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/ipgroups.go deleted file mode 100644 index 16ff0075a0..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/ipgroups.go +++ /dev/null @@ -1,581 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// IPGroupsClient is the network Client -type IPGroupsClient struct { - BaseClient -} - -// NewIPGroupsClient creates an instance of the IPGroupsClient client. -func NewIPGroupsClient(subscriptionID string) IPGroupsClient { - return NewIPGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewIPGroupsClientWithBaseURI creates an instance of the IPGroupsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewIPGroupsClientWithBaseURI(baseURI string, subscriptionID string) IPGroupsClient { - return IPGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates an ipGroups in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// IPGroupsName - the name of the ipGroups. -// parameters - parameters supplied to the create or update IpGroups operation. -func (client IPGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, IPGroupsName string, parameters IPGroup) (result IPGroupsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPGroupsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, IPGroupsName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client IPGroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, IPGroupsName string, parameters IPGroup) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipGroupsName": autorest.Encode("path", IPGroupsName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client IPGroupsClient) CreateOrUpdateSender(req *http.Request) (future IPGroupsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client IPGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result IPGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified ipGroups. -// Parameters: -// resourceGroupName - the name of the resource group. -// IPGroupsName - the name of the ipGroups. -func (client IPGroupsClient) Delete(ctx context.Context, resourceGroupName string, IPGroupsName string) (result IPGroupsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPGroupsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, IPGroupsName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client IPGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, IPGroupsName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipGroupsName": autorest.Encode("path", IPGroupsName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ipGroups/{ipGroupsName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client IPGroupsClient) DeleteSender(req *http.Request) (future IPGroupsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client IPGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified ipGroups. -// Parameters: -// resourceGroupName - the name of the resource group. -// IPGroupsName - the name of the ipGroups. -// expand - expands resourceIds (of Firewalls/Network Security Groups etc.) back referenced by the IpGroups -// resource. -func (client IPGroupsClient) Get(ctx context.Context, resourceGroupName string, IPGroupsName string, expand string) (result IPGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPGroupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, IPGroupsName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "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.IPGroupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client IPGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, IPGroupsName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipGroupsName": autorest.Encode("path", IPGroupsName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ipGroups/{ipGroupsName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client IPGroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client IPGroupsClient) GetResponder(resp *http.Response) (result IPGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all IpGroups in a subscription. -func (client IPGroupsClient) List(ctx context.Context) (result IPGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPGroupsClient.List") - defer func() { - sc := -1 - if result.iglr.Response.Response != nil { - sc = result.iglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.iglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "List", resp, "Failure sending request") - return - } - - result.iglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "List", resp, "Failure responding to request") - return - } - if result.iglr.hasNextLink() && result.iglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client IPGroupsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ipGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client IPGroupsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client IPGroupsClient) ListResponder(resp *http.Response) (result IPGroupListResult, err error) { - err = autorest.Respond( - resp, - 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 IPGroupsClient) listNextResults(ctx context.Context, lastResults IPGroupListResult) (result IPGroupListResult, err error) { - req, err := lastResults.iPGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.IPGroupsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.IPGroupsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client IPGroupsClient) ListComplete(ctx context.Context) (result IPGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPGroupsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup gets all IpGroups in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client IPGroupsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result IPGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPGroupsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.iglr.Response.Response != nil { - sc = result.iglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.iglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.iglr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.iglr.hasNextLink() && result.iglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client IPGroupsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ipGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client IPGroupsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client IPGroupsClient) ListByResourceGroupResponder(resp *http.Response) (result IPGroupListResult, err error) { - err = autorest.Respond( - resp, - 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 IPGroupsClient) listByResourceGroupNextResults(ctx context.Context, lastResults IPGroupListResult) (result IPGroupListResult, err error) { - req, err := lastResults.iPGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.IPGroupsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.IPGroupsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client IPGroupsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result IPGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPGroupsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateGroups updates tags of an IpGroups resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// IPGroupsName - the name of the ipGroups. -// parameters - parameters supplied to the update ipGroups operation. -func (client IPGroupsClient) UpdateGroups(ctx context.Context, resourceGroupName string, IPGroupsName string, parameters TagsObject) (result IPGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPGroupsClient.UpdateGroups") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateGroupsPreparer(ctx, resourceGroupName, IPGroupsName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "UpdateGroups", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateGroupsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "UpdateGroups", resp, "Failure sending request") - return - } - - result, err = client.UpdateGroupsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsClient", "UpdateGroups", resp, "Failure responding to request") - return - } - - return -} - -// UpdateGroupsPreparer prepares the UpdateGroups request. -func (client IPGroupsClient) UpdateGroupsPreparer(ctx context.Context, resourceGroupName string, IPGroupsName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipGroupsName": autorest.Encode("path", IPGroupsName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateGroupsSender sends the UpdateGroups request. The method will close the -// http.Response Body if it receives an error. -func (client IPGroupsClient) UpdateGroupsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateGroupsResponder handles the response to the UpdateGroups request. The method always -// closes the http.Response Body. -func (client IPGroupsClient) UpdateGroupsResponder(resp *http.Response) (result IPGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancerbackendaddresspools.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancerbackendaddresspools.go deleted file mode 100644 index 4ba059657d..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancerbackendaddresspools.go +++ /dev/null @@ -1,394 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancerBackendAddressPoolsClient is the network Client -type LoadBalancerBackendAddressPoolsClient struct { - BaseClient -} - -// NewLoadBalancerBackendAddressPoolsClient creates an instance of the LoadBalancerBackendAddressPoolsClient client. -func NewLoadBalancerBackendAddressPoolsClient(subscriptionID string) LoadBalancerBackendAddressPoolsClient { - return NewLoadBalancerBackendAddressPoolsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancerBackendAddressPoolsClientWithBaseURI creates an instance of the LoadBalancerBackendAddressPoolsClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewLoadBalancerBackendAddressPoolsClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerBackendAddressPoolsClient { - return LoadBalancerBackendAddressPoolsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a load balancer backend address pool. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// backendAddressPoolName - the name of the backend address pool. -// parameters - parameters supplied to the create or update load balancer backend address pool operation. -func (client LoadBalancerBackendAddressPoolsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string, parameters BackendAddressPool) (result LoadBalancerBackendAddressPoolsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerBackendAddressPoolsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, loadBalancerName, backendAddressPoolName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client LoadBalancerBackendAddressPoolsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string, parameters BackendAddressPool) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "backendAddressPoolName": autorest.Encode("path", backendAddressPoolName), - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - parameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerBackendAddressPoolsClient) CreateOrUpdateSender(req *http.Request) (future LoadBalancerBackendAddressPoolsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client LoadBalancerBackendAddressPoolsClient) CreateOrUpdateResponder(resp *http.Response) (result BackendAddressPool, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified load balancer backend address pool. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// backendAddressPoolName - the name of the backend address pool. -func (client LoadBalancerBackendAddressPoolsClient) Delete(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string) (result LoadBalancerBackendAddressPoolsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerBackendAddressPoolsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, loadBalancerName, backendAddressPoolName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client LoadBalancerBackendAddressPoolsClient) DeletePreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "backendAddressPoolName": autorest.Encode("path", backendAddressPoolName), - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerBackendAddressPoolsClient) DeleteSender(req *http.Request) (future LoadBalancerBackendAddressPoolsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client LoadBalancerBackendAddressPoolsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets load balancer backend address pool. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// backendAddressPoolName - the name of the backend address pool. -func (client LoadBalancerBackendAddressPoolsClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string) (result BackendAddressPool, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerBackendAddressPoolsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, backendAddressPoolName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "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.LoadBalancerBackendAddressPoolsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LoadBalancerBackendAddressPoolsClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, backendAddressPoolName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "backendAddressPoolName": autorest.Encode("path", backendAddressPoolName), - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerBackendAddressPoolsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LoadBalancerBackendAddressPoolsClient) GetResponder(resp *http.Response) (result BackendAddressPool, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the load balancer backed address pools. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancerBackendAddressPoolsClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerBackendAddressPoolListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerBackendAddressPoolsClient.List") - defer func() { - sc := -1 - if result.lbbaplr.Response.Response != nil { - sc = result.lbbaplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lbbaplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "List", resp, "Failure sending request") - return - } - - result.lbbaplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "List", resp, "Failure responding to request") - return - } - if result.lbbaplr.hasNextLink() && result.lbbaplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancerBackendAddressPoolsClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/backendAddressPools", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerBackendAddressPoolsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancerBackendAddressPoolsClient) ListResponder(resp *http.Response) (result LoadBalancerBackendAddressPoolListResult, err error) { - err = autorest.Respond( - resp, - 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 LoadBalancerBackendAddressPoolsClient) listNextResults(ctx context.Context, lastResults LoadBalancerBackendAddressPoolListResult) (result LoadBalancerBackendAddressPoolListResult, err error) { - req, err := lastResults.loadBalancerBackendAddressPoolListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancerBackendAddressPoolsClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerBackendAddressPoolListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerBackendAddressPoolsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancerfrontendipconfigurations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancerfrontendipconfigurations.go deleted file mode 100644 index 9d5495f9d3..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancerfrontendipconfigurations.go +++ /dev/null @@ -1,229 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancerFrontendIPConfigurationsClient is the network Client -type LoadBalancerFrontendIPConfigurationsClient struct { - BaseClient -} - -// NewLoadBalancerFrontendIPConfigurationsClient creates an instance of the LoadBalancerFrontendIPConfigurationsClient -// client. -func NewLoadBalancerFrontendIPConfigurationsClient(subscriptionID string) LoadBalancerFrontendIPConfigurationsClient { - return NewLoadBalancerFrontendIPConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancerFrontendIPConfigurationsClientWithBaseURI creates an instance of the -// LoadBalancerFrontendIPConfigurationsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewLoadBalancerFrontendIPConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerFrontendIPConfigurationsClient { - return LoadBalancerFrontendIPConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets load balancer frontend IP configuration. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// frontendIPConfigurationName - the name of the frontend IP configuration. -func (client LoadBalancerFrontendIPConfigurationsClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, frontendIPConfigurationName string) (result FrontendIPConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerFrontendIPConfigurationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, frontendIPConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "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.LoadBalancerFrontendIPConfigurationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LoadBalancerFrontendIPConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, frontendIPConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "frontendIPConfigurationName": autorest.Encode("path", frontendIPConfigurationName), - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/frontendIPConfigurations/{frontendIPConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerFrontendIPConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LoadBalancerFrontendIPConfigurationsClient) GetResponder(resp *http.Response) (result FrontendIPConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the load balancer frontend IP configurations. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancerFrontendIPConfigurationsClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerFrontendIPConfigurationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerFrontendIPConfigurationsClient.List") - defer func() { - sc := -1 - if result.lbficlr.Response.Response != nil { - sc = result.lbficlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lbficlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "List", resp, "Failure sending request") - return - } - - result.lbficlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "List", resp, "Failure responding to request") - return - } - if result.lbficlr.hasNextLink() && result.lbficlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancerFrontendIPConfigurationsClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/frontendIPConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerFrontendIPConfigurationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancerFrontendIPConfigurationsClient) ListResponder(resp *http.Response) (result LoadBalancerFrontendIPConfigurationListResult, err error) { - err = autorest.Respond( - resp, - 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 LoadBalancerFrontendIPConfigurationsClient) listNextResults(ctx context.Context, lastResults LoadBalancerFrontendIPConfigurationListResult) (result LoadBalancerFrontendIPConfigurationListResult, err error) { - req, err := lastResults.loadBalancerFrontendIPConfigurationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerFrontendIPConfigurationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancerFrontendIPConfigurationsClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerFrontendIPConfigurationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerFrontendIPConfigurationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancerloadbalancingrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancerloadbalancingrules.go deleted file mode 100644 index c114893293..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancerloadbalancingrules.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancerLoadBalancingRulesClient is the network Client -type LoadBalancerLoadBalancingRulesClient struct { - BaseClient -} - -// NewLoadBalancerLoadBalancingRulesClient creates an instance of the LoadBalancerLoadBalancingRulesClient client. -func NewLoadBalancerLoadBalancingRulesClient(subscriptionID string) LoadBalancerLoadBalancingRulesClient { - return NewLoadBalancerLoadBalancingRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancerLoadBalancingRulesClientWithBaseURI creates an instance of the LoadBalancerLoadBalancingRulesClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewLoadBalancerLoadBalancingRulesClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerLoadBalancingRulesClient { - return LoadBalancerLoadBalancingRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets the specified load balancer load balancing rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// loadBalancingRuleName - the name of the load balancing rule. -func (client LoadBalancerLoadBalancingRulesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, loadBalancingRuleName string) (result LoadBalancingRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, loadBalancingRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "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.LoadBalancerLoadBalancingRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LoadBalancerLoadBalancingRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, loadBalancingRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "loadBalancingRuleName": autorest.Encode("path", loadBalancingRuleName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/loadBalancingRules/{loadBalancingRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerLoadBalancingRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LoadBalancerLoadBalancingRulesClient) GetResponder(resp *http.Response) (result LoadBalancingRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the load balancing rules in a load balancer. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancerLoadBalancingRulesClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerLoadBalancingRuleListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRulesClient.List") - defer func() { - sc := -1 - if result.lblbrlr.Response.Response != nil { - sc = result.lblbrlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lblbrlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "List", resp, "Failure sending request") - return - } - - result.lblbrlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "List", resp, "Failure responding to request") - return - } - if result.lblbrlr.hasNextLink() && result.lblbrlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancerLoadBalancingRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/loadBalancingRules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerLoadBalancingRulesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancerLoadBalancingRulesClient) ListResponder(resp *http.Response) (result LoadBalancerLoadBalancingRuleListResult, err error) { - err = autorest.Respond( - resp, - 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 LoadBalancerLoadBalancingRulesClient) listNextResults(ctx context.Context, lastResults LoadBalancerLoadBalancingRuleListResult) (result LoadBalancerLoadBalancingRuleListResult, err error) { - req, err := lastResults.loadBalancerLoadBalancingRuleListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerLoadBalancingRulesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancerLoadBalancingRulesClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerLoadBalancingRuleListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRulesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancernetworkinterfaces.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancernetworkinterfaces.go deleted file mode 100644 index 586ff96709..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancernetworkinterfaces.go +++ /dev/null @@ -1,150 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancerNetworkInterfacesClient is the network Client -type LoadBalancerNetworkInterfacesClient struct { - BaseClient -} - -// NewLoadBalancerNetworkInterfacesClient creates an instance of the LoadBalancerNetworkInterfacesClient client. -func NewLoadBalancerNetworkInterfacesClient(subscriptionID string) LoadBalancerNetworkInterfacesClient { - return NewLoadBalancerNetworkInterfacesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancerNetworkInterfacesClientWithBaseURI creates an instance of the LoadBalancerNetworkInterfacesClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewLoadBalancerNetworkInterfacesClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerNetworkInterfacesClient { - return LoadBalancerNetworkInterfacesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets associated load balancer network interfaces. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancerNetworkInterfacesClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result InterfaceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerNetworkInterfacesClient.List") - defer func() { - sc := -1 - if result.ilr.Response.Response != nil { - sc = result.ilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerNetworkInterfacesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerNetworkInterfacesClient", "List", resp, "Failure sending request") - return - } - - result.ilr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerNetworkInterfacesClient", "List", resp, "Failure responding to request") - return - } - if result.ilr.hasNextLink() && result.ilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancerNetworkInterfacesClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/networkInterfaces", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerNetworkInterfacesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancerNetworkInterfacesClient) ListResponder(resp *http.Response) (result InterfaceListResult, err error) { - err = autorest.Respond( - resp, - 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 LoadBalancerNetworkInterfacesClient) listNextResults(ctx context.Context, lastResults InterfaceListResult) (result InterfaceListResult, err error) { - req, err := lastResults.interfaceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancerNetworkInterfacesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancerNetworkInterfacesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerNetworkInterfacesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancerNetworkInterfacesClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result InterfaceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerNetworkInterfacesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalanceroutboundrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalanceroutboundrules.go deleted file mode 100644 index 6212cd6ded..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalanceroutboundrules.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancerOutboundRulesClient is the network Client -type LoadBalancerOutboundRulesClient struct { - BaseClient -} - -// NewLoadBalancerOutboundRulesClient creates an instance of the LoadBalancerOutboundRulesClient client. -func NewLoadBalancerOutboundRulesClient(subscriptionID string) LoadBalancerOutboundRulesClient { - return NewLoadBalancerOutboundRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancerOutboundRulesClientWithBaseURI creates an instance of the LoadBalancerOutboundRulesClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewLoadBalancerOutboundRulesClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerOutboundRulesClient { - return LoadBalancerOutboundRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets the specified load balancer outbound rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// outboundRuleName - the name of the outbound rule. -func (client LoadBalancerOutboundRulesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, outboundRuleName string) (result OutboundRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerOutboundRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, outboundRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "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.LoadBalancerOutboundRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LoadBalancerOutboundRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, outboundRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "outboundRuleName": autorest.Encode("path", outboundRuleName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/outboundRules/{outboundRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerOutboundRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LoadBalancerOutboundRulesClient) GetResponder(resp *http.Response) (result OutboundRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the outbound rules in a load balancer. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancerOutboundRulesClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerOutboundRuleListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerOutboundRulesClient.List") - defer func() { - sc := -1 - if result.lborlr.Response.Response != nil { - sc = result.lborlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lborlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "List", resp, "Failure sending request") - return - } - - result.lborlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "List", resp, "Failure responding to request") - return - } - if result.lborlr.hasNextLink() && result.lborlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancerOutboundRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/outboundRules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerOutboundRulesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancerOutboundRulesClient) ListResponder(resp *http.Response) (result LoadBalancerOutboundRuleListResult, err error) { - err = autorest.Respond( - resp, - 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 LoadBalancerOutboundRulesClient) listNextResults(ctx context.Context, lastResults LoadBalancerOutboundRuleListResult) (result LoadBalancerOutboundRuleListResult, err error) { - req, err := lastResults.loadBalancerOutboundRuleListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerOutboundRulesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancerOutboundRulesClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerOutboundRuleListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerOutboundRulesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancerprobes.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancerprobes.go deleted file mode 100644 index 4ba2205c36..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancerprobes.go +++ /dev/null @@ -1,228 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancerProbesClient is the network Client -type LoadBalancerProbesClient struct { - BaseClient -} - -// NewLoadBalancerProbesClient creates an instance of the LoadBalancerProbesClient client. -func NewLoadBalancerProbesClient(subscriptionID string) LoadBalancerProbesClient { - return NewLoadBalancerProbesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancerProbesClientWithBaseURI creates an instance of the LoadBalancerProbesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewLoadBalancerProbesClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancerProbesClient { - return LoadBalancerProbesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets load balancer probe. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// probeName - the name of the probe. -func (client LoadBalancerProbesClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, probeName string) (result Probe, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerProbesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, probeName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "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.LoadBalancerProbesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LoadBalancerProbesClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, probeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "probeName": autorest.Encode("path", probeName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/probes/{probeName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerProbesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LoadBalancerProbesClient) GetResponder(resp *http.Response) (result Probe, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the load balancer probes. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancerProbesClient) List(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerProbeListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerProbesClient.List") - defer func() { - sc := -1 - if result.lbplr.Response.Response != nil { - sc = result.lbplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lbplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "List", resp, "Failure sending request") - return - } - - result.lbplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "List", resp, "Failure responding to request") - return - } - if result.lbplr.hasNextLink() && result.lbplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancerProbesClient) ListPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}/probes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancerProbesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancerProbesClient) ListResponder(resp *http.Response) (result LoadBalancerProbeListResult, err error) { - err = autorest.Respond( - resp, - 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 LoadBalancerProbesClient) listNextResults(ctx context.Context, lastResults LoadBalancerProbeListResult) (result LoadBalancerProbeListResult, err error) { - req, err := lastResults.loadBalancerProbeListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerProbesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancerProbesClient) ListComplete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancerProbeListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerProbesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, loadBalancerName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancers.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancers.go deleted file mode 100644 index ed722a05f8..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/loadbalancers.go +++ /dev/null @@ -1,743 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LoadBalancersClient is the network Client -type LoadBalancersClient struct { - BaseClient -} - -// NewLoadBalancersClient creates an instance of the LoadBalancersClient client. -func NewLoadBalancersClient(subscriptionID string) LoadBalancersClient { - return NewLoadBalancersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLoadBalancersClientWithBaseURI creates an instance of the LoadBalancersClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewLoadBalancersClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancersClient { - return LoadBalancersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a load balancer. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// parameters - parameters supplied to the create or update load balancer operation. -func (client LoadBalancersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters LoadBalancer) (result LoadBalancersCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, loadBalancerName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client LoadBalancersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters LoadBalancer) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) CreateOrUpdateSender(req *http.Request) (future LoadBalancersCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) CreateOrUpdateResponder(resp *http.Response) (result LoadBalancer, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified load balancer. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -func (client LoadBalancersClient) Delete(ctx context.Context, resourceGroupName string, loadBalancerName string) (result LoadBalancersDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, loadBalancerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client LoadBalancersClient) DeletePreparer(ctx context.Context, resourceGroupName string, loadBalancerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) DeleteSender(req *http.Request) (future LoadBalancersDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified load balancer. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// expand - expands referenced resources. -func (client LoadBalancersClient) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, expand string) (result LoadBalancer, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, loadBalancerName, expand) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LoadBalancersClient) GetPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers/{loadBalancerName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) GetResponder(resp *http.Response) (result LoadBalancer, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the load balancers in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client LoadBalancersClient) List(ctx context.Context, resourceGroupName string) (result LoadBalancerListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.List") - defer func() { - sc := -1 - if result.lblr.Response.Response != nil { - sc = result.lblr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lblr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure sending request") - return - } - - result.lblr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure responding to request") - return - } - if result.lblr.hasNextLink() && result.lblr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LoadBalancersClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/loadBalancers", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) ListResponder(resp *http.Response) (result LoadBalancerListResult, err error) { - err = autorest.Respond( - resp, - 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 LoadBalancersClient) listNextResults(ctx context.Context, lastResults LoadBalancerListResult) (result LoadBalancerListResult, err error) { - req, err := lastResults.loadBalancerListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancersClient) ListComplete(ctx context.Context, resourceGroupName string) (result LoadBalancerListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the load balancers in a subscription. -func (client LoadBalancersClient) ListAll(ctx context.Context) (result LoadBalancerListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.ListAll") - defer func() { - sc := -1 - if result.lblr.Response.Response != nil { - sc = result.lblr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.lblr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure sending request") - return - } - - result.lblr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure responding to request") - return - } - if result.lblr.hasNextLink() && result.lblr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client LoadBalancersClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) ListAllResponder(resp *http.Response) (result LoadBalancerListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client LoadBalancersClient) listAllNextResults(ctx context.Context, lastResults LoadBalancerListResult) (result LoadBalancerListResult, err error) { - req, err := lastResults.loadBalancerListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client LoadBalancersClient) ListAllComplete(ctx context.Context) (result LoadBalancerListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListInboundNatRulePortMappings list of inbound NAT rule port mappings. -// Parameters: -// groupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// backendPoolName - the name of the load balancer backend address pool. -// parameters - query inbound NAT rule port mapping request. -func (client LoadBalancersClient) ListInboundNatRulePortMappings(ctx context.Context, groupName string, loadBalancerName string, backendPoolName string, parameters QueryInboundNatRulePortMappingRequest) (result LoadBalancersListInboundNatRulePortMappingsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.ListInboundNatRulePortMappings") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListInboundNatRulePortMappingsPreparer(ctx, groupName, loadBalancerName, backendPoolName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListInboundNatRulePortMappings", nil, "Failure preparing request") - return - } - - result, err = client.ListInboundNatRulePortMappingsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListInboundNatRulePortMappings", result.Response(), "Failure sending request") - return - } - - return -} - -// ListInboundNatRulePortMappingsPreparer prepares the ListInboundNatRulePortMappings request. -func (client LoadBalancersClient) ListInboundNatRulePortMappingsPreparer(ctx context.Context, groupName string, loadBalancerName string, backendPoolName string, parameters QueryInboundNatRulePortMappingRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "backendPoolName": autorest.Encode("path", backendPoolName), - "groupName": autorest.Encode("path", groupName), - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendPoolName}/queryInboundNatRulePortMapping", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListInboundNatRulePortMappingsSender sends the ListInboundNatRulePortMappings request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) ListInboundNatRulePortMappingsSender(req *http.Request) (future LoadBalancersListInboundNatRulePortMappingsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListInboundNatRulePortMappingsResponder handles the response to the ListInboundNatRulePortMappings request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) ListInboundNatRulePortMappingsResponder(resp *http.Response) (result BackendAddressInboundNatRulePortMappings, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SwapPublicIPAddresses swaps VIPs between two load balancers. -// Parameters: -// location - the region where load balancers are located at. -// parameters - parameters that define which VIPs should be swapped. -func (client LoadBalancersClient) SwapPublicIPAddresses(ctx context.Context, location string, parameters LoadBalancerVipSwapRequest) (result LoadBalancersSwapPublicIPAddressesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.SwapPublicIPAddresses") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.SwapPublicIPAddressesPreparer(ctx, location, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "SwapPublicIPAddresses", nil, "Failure preparing request") - return - } - - result, err = client.SwapPublicIPAddressesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "SwapPublicIPAddresses", result.Response(), "Failure sending request") - return - } - - return -} - -// SwapPublicIPAddressesPreparer prepares the SwapPublicIPAddresses request. -func (client LoadBalancersClient) SwapPublicIPAddressesPreparer(ctx context.Context, location string, parameters LoadBalancerVipSwapRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/setLoadBalancerFrontendPublicIpAddresses", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SwapPublicIPAddressesSender sends the SwapPublicIPAddresses request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) SwapPublicIPAddressesSender(req *http.Request) (future LoadBalancersSwapPublicIPAddressesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// SwapPublicIPAddressesResponder handles the response to the SwapPublicIPAddresses request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) SwapPublicIPAddressesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// UpdateTags updates a load balancer tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// loadBalancerName - the name of the load balancer. -// parameters - parameters supplied to update load balancer tags. -func (client LoadBalancersClient) UpdateTags(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters TagsObject) (result LoadBalancer, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancersClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, loadBalancerName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client LoadBalancersClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "loadBalancerName": autorest.Encode("path", loadBalancerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client LoadBalancersClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client LoadBalancersClient) UpdateTagsResponder(resp *http.Response) (result LoadBalancer, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/localnetworkgateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/localnetworkgateways.go deleted file mode 100644 index c1e4015d06..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/localnetworkgateways.go +++ /dev/null @@ -1,498 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// LocalNetworkGatewaysClient is the network Client -type LocalNetworkGatewaysClient struct { - BaseClient -} - -// NewLocalNetworkGatewaysClient creates an instance of the LocalNetworkGatewaysClient client. -func NewLocalNetworkGatewaysClient(subscriptionID string) LocalNetworkGatewaysClient { - return NewLocalNetworkGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewLocalNetworkGatewaysClientWithBaseURI creates an instance of the LocalNetworkGatewaysClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewLocalNetworkGatewaysClientWithBaseURI(baseURI string, subscriptionID string) LocalNetworkGatewaysClient { - return LocalNetworkGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a local network gateway in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// localNetworkGatewayName - the name of the local network gateway. -// parameters - parameters supplied to the create or update local network gateway operation. -func (client LocalNetworkGatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway) (result LocalNetworkGatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.BgpSettings", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.LocalNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.LocalNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "parameters.LocalNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.LocalNetworkGatewaysClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, localNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client LocalNetworkGatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "localNetworkGatewayName": autorest.Encode("path", localNetworkGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client LocalNetworkGatewaysClient) CreateOrUpdateSender(req *http.Request) (future LocalNetworkGatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client LocalNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result LocalNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified local network gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// localNetworkGatewayName - the name of the local network gateway. -func (client LocalNetworkGatewaysClient) Delete(ctx context.Context, resourceGroupName string, localNetworkGatewayName string) (result LocalNetworkGatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.NewError("network.LocalNetworkGatewaysClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, localNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client LocalNetworkGatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, localNetworkGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "localNetworkGatewayName": autorest.Encode("path", localNetworkGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/localNetworkGateways/{localNetworkGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client LocalNetworkGatewaysClient) DeleteSender(req *http.Request) (future LocalNetworkGatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client LocalNetworkGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified local network gateway in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// localNetworkGatewayName - the name of the local network gateway. -func (client LocalNetworkGatewaysClient) Get(ctx context.Context, resourceGroupName string, localNetworkGatewayName string) (result LocalNetworkGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.NewError("network.LocalNetworkGatewaysClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, localNetworkGatewayName) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client LocalNetworkGatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, localNetworkGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "localNetworkGatewayName": autorest.Encode("path", localNetworkGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/localNetworkGateways/{localNetworkGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client LocalNetworkGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client LocalNetworkGatewaysClient) GetResponder(resp *http.Response) (result LocalNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the local network gateways in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client LocalNetworkGatewaysClient) List(ctx context.Context, resourceGroupName string) (result LocalNetworkGatewayListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewaysClient.List") - defer func() { - sc := -1 - if result.lnglr.Response.Response != nil { - sc = result.lnglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lnglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure sending request") - return - } - - result.lnglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure responding to request") - return - } - if result.lnglr.hasNextLink() && result.lnglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client LocalNetworkGatewaysClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/localNetworkGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client LocalNetworkGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client LocalNetworkGatewaysClient) ListResponder(resp *http.Response) (result LocalNetworkGatewayListResult, err error) { - err = autorest.Respond( - resp, - 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 LocalNetworkGatewaysClient) listNextResults(ctx context.Context, lastResults LocalNetworkGatewayListResult) (result LocalNetworkGatewayListResult, err error) { - req, err := lastResults.localNetworkGatewayListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client LocalNetworkGatewaysClient) ListComplete(ctx context.Context, resourceGroupName string) (result LocalNetworkGatewayListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewaysClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// UpdateTags updates a local network gateway tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// localNetworkGatewayName - the name of the local network gateway. -// parameters - parameters supplied to update local network gateway tags. -func (client LocalNetworkGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, parameters TagsObject) (result LocalNetworkGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewaysClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.NewError("network.LocalNetworkGatewaysClient", "UpdateTags", err.Error()) - } - - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, localNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client LocalNetworkGatewaysClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, localNetworkGatewayName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "localNetworkGatewayName": autorest.Encode("path", localNetworkGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client LocalNetworkGatewaysClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client LocalNetworkGatewaysClient) UpdateTagsResponder(resp *http.Response) (result LocalNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/managementgroupnetworkmanagerconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/managementgroupnetworkmanagerconnections.go deleted file mode 100644 index 177be9f9bd..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/managementgroupnetworkmanagerconnections.go +++ /dev/null @@ -1,397 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ManagementGroupNetworkManagerConnectionsClient is the network Client -type ManagementGroupNetworkManagerConnectionsClient struct { - BaseClient -} - -// NewManagementGroupNetworkManagerConnectionsClient creates an instance of the -// ManagementGroupNetworkManagerConnectionsClient client. -func NewManagementGroupNetworkManagerConnectionsClient(subscriptionID string) ManagementGroupNetworkManagerConnectionsClient { - return NewManagementGroupNetworkManagerConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewManagementGroupNetworkManagerConnectionsClientWithBaseURI creates an instance of the -// ManagementGroupNetworkManagerConnectionsClient client using a custom endpoint. Use this when interacting with an -// Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewManagementGroupNetworkManagerConnectionsClientWithBaseURI(baseURI string, subscriptionID string) ManagementGroupNetworkManagerConnectionsClient { - return ManagementGroupNetworkManagerConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create a network manager connection on this management group. -// Parameters: -// parameters - network manager connection to be created/updated. -// managementGroupID - the management group Id which uniquely identify the Microsoft Azure management group. -// networkManagerConnectionName - name for the network manager connection. -func (client ManagementGroupNetworkManagerConnectionsClient) CreateOrUpdate(ctx context.Context, parameters ManagerConnection, managementGroupID string, networkManagerConnectionName string) (result ManagerConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagementGroupNetworkManagerConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, parameters, managementGroupID, networkManagerConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagementGroupNetworkManagerConnectionsClient", "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.ManagementGroupNetworkManagerConnectionsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagementGroupNetworkManagerConnectionsClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ManagementGroupNetworkManagerConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, parameters ManagerConnection, managementGroupID string, networkManagerConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupId": autorest.Encode("path", managementGroupID), - "networkManagerConnectionName": autorest.Encode("path", networkManagerConnectionName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Network/networkManagerConnections/{networkManagerConnectionName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ManagementGroupNetworkManagerConnectionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ManagementGroupNetworkManagerConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result ManagerConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete specified pending connection created by this management group. -// Parameters: -// managementGroupID - the management group Id which uniquely identify the Microsoft Azure management group. -// networkManagerConnectionName - name for the network manager connection. -func (client ManagementGroupNetworkManagerConnectionsClient) Delete(ctx context.Context, managementGroupID string, networkManagerConnectionName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagementGroupNetworkManagerConnectionsClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, managementGroupID, networkManagerConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagementGroupNetworkManagerConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "network.ManagementGroupNetworkManagerConnectionsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagementGroupNetworkManagerConnectionsClient", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ManagementGroupNetworkManagerConnectionsClient) DeletePreparer(ctx context.Context, managementGroupID string, networkManagerConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupId": autorest.Encode("path", managementGroupID), - "networkManagerConnectionName": autorest.Encode("path", networkManagerConnectionName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Network/networkManagerConnections/{networkManagerConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ManagementGroupNetworkManagerConnectionsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ManagementGroupNetworkManagerConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get a specified connection created by this management group. -// Parameters: -// managementGroupID - the management group Id which uniquely identify the Microsoft Azure management group. -// networkManagerConnectionName - name for the network manager connection. -func (client ManagementGroupNetworkManagerConnectionsClient) Get(ctx context.Context, managementGroupID string, networkManagerConnectionName string) (result ManagerConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagementGroupNetworkManagerConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, managementGroupID, networkManagerConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagementGroupNetworkManagerConnectionsClient", "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.ManagementGroupNetworkManagerConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagementGroupNetworkManagerConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ManagementGroupNetworkManagerConnectionsClient) GetPreparer(ctx context.Context, managementGroupID string, networkManagerConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupId": autorest.Encode("path", managementGroupID), - "networkManagerConnectionName": autorest.Encode("path", networkManagerConnectionName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Network/networkManagerConnections/{networkManagerConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ManagementGroupNetworkManagerConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ManagementGroupNetworkManagerConnectionsClient) GetResponder(resp *http.Response) (result ManagerConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all network manager connections created by this management group. -// Parameters: -// managementGroupID - the management group Id which uniquely identify the Microsoft Azure management group. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -// skipToken - skipToken is only used if a previous operation returned a partial result. If a previous response -// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that -// specifies a starting point to use for subsequent calls. -func (client ManagementGroupNetworkManagerConnectionsClient) List(ctx context.Context, managementGroupID string, top *int32, skipToken string) (result ManagerConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagementGroupNetworkManagerConnectionsClient.List") - defer func() { - sc := -1 - if result.mclr.Response.Response != nil { - sc = result.mclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.ManagementGroupNetworkManagerConnectionsClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, managementGroupID, top, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagementGroupNetworkManagerConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.mclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ManagementGroupNetworkManagerConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.mclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagementGroupNetworkManagerConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.mclr.hasNextLink() && result.mclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ManagementGroupNetworkManagerConnectionsClient) ListPreparer(ctx context.Context, managementGroupID string, top *int32, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "managementGroupId": autorest.Encode("path", managementGroupID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(skipToken) > 0 { - queryParameters["$skipToken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Network/networkManagerConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ManagementGroupNetworkManagerConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ManagementGroupNetworkManagerConnectionsClient) ListResponder(resp *http.Response) (result ManagerConnectionListResult, err error) { - err = autorest.Respond( - resp, - 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 ManagementGroupNetworkManagerConnectionsClient) listNextResults(ctx context.Context, lastResults ManagerConnectionListResult) (result ManagerConnectionListResult, err error) { - req, err := lastResults.managerConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ManagementGroupNetworkManagerConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ManagementGroupNetworkManagerConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagementGroupNetworkManagerConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ManagementGroupNetworkManagerConnectionsClient) ListComplete(ctx context.Context, managementGroupID string, top *int32, skipToken string) (result ManagerConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagementGroupNetworkManagerConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, managementGroupID, top, skipToken) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/managercommits.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/managercommits.go deleted file mode 100644 index 8a88e396b2..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/managercommits.go +++ /dev/null @@ -1,121 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ManagerCommitsClient is the network Client -type ManagerCommitsClient struct { - BaseClient -} - -// NewManagerCommitsClient creates an instance of the ManagerCommitsClient client. -func NewManagerCommitsClient(subscriptionID string) ManagerCommitsClient { - return NewManagerCommitsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewManagerCommitsClientWithBaseURI creates an instance of the ManagerCommitsClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewManagerCommitsClientWithBaseURI(baseURI string, subscriptionID string) ManagerCommitsClient { - return ManagerCommitsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Post post a Network Manager Commit. -// Parameters: -// parameters - parameters supplied to specify which Managed Network commit is. -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -func (client ManagerCommitsClient) Post(ctx context.Context, parameters ManagerCommit, resourceGroupName string, networkManagerName string) (result ManagerCommitsPostFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagerCommitsClient.Post") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.TargetLocations", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.ManagerCommitsClient", "Post", err.Error()) - } - - req, err := client.PostPreparer(ctx, parameters, resourceGroupName, networkManagerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagerCommitsClient", "Post", nil, "Failure preparing request") - return - } - - result, err = client.PostSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagerCommitsClient", "Post", result.Response(), "Failure sending request") - return - } - - return -} - -// PostPreparer prepares the Post request. -func (client ManagerCommitsClient) PostPreparer(ctx context.Context, parameters ManagerCommit, resourceGroupName string, networkManagerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.CommitID = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/commit", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PostSender sends the Post request. The method will close the -// http.Response Body if it receives an error. -func (client ManagerCommitsClient) PostSender(req *http.Request) (future ManagerCommitsPostFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// PostResponder handles the response to the Post request. The method always -// closes the http.Response Body. -func (client ManagerCommitsClient) PostResponder(resp *http.Response) (result ManagerCommit, err error) { - err = autorest.Respond( - resp, - 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/services/network/mgmt/2022-07-01/network/managerdeploymentstatus.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/managerdeploymentstatus.go deleted file mode 100644 index eff571d698..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/managerdeploymentstatus.go +++ /dev/null @@ -1,126 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ManagerDeploymentStatusClient is the network Client -type ManagerDeploymentStatusClient struct { - BaseClient -} - -// NewManagerDeploymentStatusClient creates an instance of the ManagerDeploymentStatusClient client. -func NewManagerDeploymentStatusClient(subscriptionID string) ManagerDeploymentStatusClient { - return NewManagerDeploymentStatusClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewManagerDeploymentStatusClientWithBaseURI creates an instance of the ManagerDeploymentStatusClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewManagerDeploymentStatusClientWithBaseURI(baseURI string, subscriptionID string) ManagerDeploymentStatusClient { - return ManagerDeploymentStatusClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List post to List of Network Manager Deployment Status. -// Parameters: -// parameters - parameters supplied to specify which Managed Network deployment status is. -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -func (client ManagerDeploymentStatusClient) List(ctx context.Context, parameters ManagerDeploymentStatusParameter, resourceGroupName string, networkManagerName string, top *int32) (result ManagerDeploymentStatusListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagerDeploymentStatusClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.ManagerDeploymentStatusClient", "List", err.Error()) - } - - req, err := client.ListPreparer(ctx, parameters, resourceGroupName, networkManagerName, top) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagerDeploymentStatusClient", "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.ManagerDeploymentStatusClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagerDeploymentStatusClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ManagerDeploymentStatusClient) ListPreparer(ctx context.Context, parameters ManagerDeploymentStatusParameter, resourceGroupName string, networkManagerName string, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/listDeploymentStatus", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ManagerDeploymentStatusClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ManagerDeploymentStatusClient) ListResponder(resp *http.Response) (result ManagerDeploymentStatusListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/managers.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/managers.go deleted file mode 100644 index f569db33cb..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/managers.go +++ /dev/null @@ -1,630 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ManagersClient is the network Client -type ManagersClient struct { - BaseClient -} - -// NewManagersClient creates an instance of the ManagersClient client. -func NewManagersClient(subscriptionID string) ManagersClient { - return NewManagersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewManagersClientWithBaseURI creates an instance of the ManagersClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewManagersClientWithBaseURI(baseURI string, subscriptionID string) ManagersClient { - return ManagersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a Network Manager. -// Parameters: -// parameters - parameters supplied to specify which network manager is. -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -func (client ManagersClient) CreateOrUpdate(ctx context.Context, parameters Manager, resourceGroupName string, networkManagerName string) (result Manager, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagersClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.ManagerProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ManagerProperties.NetworkManagerScopes", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ManagerProperties.NetworkManagerScopeAccesses", Name: validation.Null, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.ManagersClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, parameters, resourceGroupName, networkManagerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "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.ManagersClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ManagersClient) CreateOrUpdatePreparer(ctx context.Context, parameters Manager, resourceGroupName string, networkManagerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - parameters.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ManagersClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ManagersClient) CreateOrUpdateResponder(resp *http.Response) (result Manager, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a network manager. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// force - deletes the resource even if it is part of a deployed configuration. If the configuration has been -// deployed, the service will do a cleanup deployment in the background, prior to the delete. -func (client ManagersClient) Delete(ctx context.Context, resourceGroupName string, networkManagerName string, force *bool) (result ManagersDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagersClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkManagerName, force) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ManagersClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkManagerName string, force *bool) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if force != nil { - queryParameters["force"] = autorest.Encode("query", *force) - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ManagersClient) DeleteSender(req *http.Request) (future ManagersDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ManagersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified Network Manager. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -func (client ManagersClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string) (result Manager, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagersClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkManagerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "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.ManagersClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ManagersClient) GetPreparer(ctx context.Context, resourceGroupName string, networkManagerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkManagers/{networkManagerName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ManagersClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ManagersClient) GetResponder(resp *http.Response) (result Manager, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list network managers in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -// skipToken - skipToken is only used if a previous operation returned a partial result. If a previous response -// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that -// specifies a starting point to use for subsequent calls. -func (client ManagersClient) List(ctx context.Context, resourceGroupName string, top *int32, skipToken string) (result ManagerListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagersClient.List") - defer func() { - sc := -1 - if result.mlr.Response.Response != nil { - sc = result.mlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.ManagersClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, top, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.mlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ManagersClient", "List", resp, "Failure sending request") - return - } - - result.mlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "List", resp, "Failure responding to request") - return - } - if result.mlr.hasNextLink() && result.mlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ManagersClient) ListPreparer(ctx context.Context, resourceGroupName string, top *int32, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(skipToken) > 0 { - queryParameters["$skipToken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ManagersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ManagersClient) ListResponder(resp *http.Response) (result ManagerListResult, err error) { - err = autorest.Respond( - resp, - 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 ManagersClient) listNextResults(ctx context.Context, lastResults ManagerListResult) (result ManagerListResult, err error) { - req, err := lastResults.managerListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ManagersClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ManagersClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ManagersClient) ListComplete(ctx context.Context, resourceGroupName string, top *int32, skipToken string) (result ManagerListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagersClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, top, skipToken) - return -} - -// ListBySubscription list all network managers in a subscription. -// Parameters: -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -// skipToken - skipToken is only used if a previous operation returned a partial result. If a previous response -// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that -// specifies a starting point to use for subsequent calls. -func (client ManagersClient) ListBySubscription(ctx context.Context, top *int32, skipToken string) (result ManagerListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagersClient.ListBySubscription") - defer func() { - sc := -1 - if result.mlr.Response.Response != nil { - sc = result.mlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.ManagersClient", "ListBySubscription", err.Error()) - } - - result.fn = client.listBySubscriptionNextResults - req, err := client.ListBySubscriptionPreparer(ctx, top, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "ListBySubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.mlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ManagersClient", "ListBySubscription", resp, "Failure sending request") - return - } - - result.mlr, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "ListBySubscription", resp, "Failure responding to request") - return - } - if result.mlr.hasNextLink() && result.mlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client ManagersClient) ListBySubscriptionPreparer(ctx context.Context, top *int32, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(skipToken) > 0 { - queryParameters["$skipToken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkManagers", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBySubscriptionSender sends the ListBySubscription request. The method will close the -// http.Response Body if it receives an error. -func (client ManagersClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always -// closes the http.Response Body. -func (client ManagersClient) ListBySubscriptionResponder(resp *http.Response) (result ManagerListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listBySubscriptionNextResults retrieves the next set of results, if any. -func (client ManagersClient) listBySubscriptionNextResults(ctx context.Context, lastResults ManagerListResult) (result ManagerListResult, err error) { - req, err := lastResults.managerListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ManagersClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ManagersClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client ManagersClient) ListBySubscriptionComplete(ctx context.Context, top *int32, skipToken string) (result ManagerListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagersClient.ListBySubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListBySubscription(ctx, top, skipToken) - return -} - -// Patch patch NetworkManager. -// Parameters: -// parameters - parameters supplied to specify which network manager is. -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -func (client ManagersClient) Patch(ctx context.Context, parameters PatchObject, resourceGroupName string, networkManagerName string) (result Manager, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagersClient.Patch") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PatchPreparer(ctx, parameters, resourceGroupName, networkManagerName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "Patch", nil, "Failure preparing request") - return - } - - resp, err := client.PatchSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ManagersClient", "Patch", resp, "Failure sending request") - return - } - - result, err = client.PatchResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersClient", "Patch", resp, "Failure responding to request") - return - } - - return -} - -// PatchPreparer prepares the Patch request. -func (client ManagersClient) PatchPreparer(ctx context.Context, parameters PatchObject, resourceGroupName string, networkManagerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PatchSender sends the Patch request. The method will close the -// http.Response Body if it receives an error. -func (client ManagersClient) PatchSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// PatchResponder handles the response to the Patch request. The method always -// closes the http.Response Body. -func (client ManagersClient) PatchResponder(resp *http.Response) (result Manager, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/models.go deleted file mode 100644 index 9695388e70..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/models.go +++ /dev/null @@ -1,58052 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "encoding/json" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/go-autorest/autorest/to" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - -// AadAuthenticationParameters AAD Vpn authentication type related parameters. -type AadAuthenticationParameters struct { - // AadTenant - AAD Vpn authentication parameter AAD tenant. - AadTenant *string `json:"aadTenant,omitempty"` - // AadAudience - AAD Vpn authentication parameter AAD audience. - AadAudience *string `json:"aadAudience,omitempty"` - // AadIssuer - AAD Vpn authentication parameter AAD issuer. - AadIssuer *string `json:"aadIssuer,omitempty"` -} - -// Action action to be taken on a route matching a RouteMap criterion. -type Action struct { - // Type - Type of action to be taken. Supported types are 'Remove', 'Add', 'Replace', and 'Drop.'. Possible values include: 'RouteMapActionTypeUnknown', 'RouteMapActionTypeRemove', 'RouteMapActionTypeAdd', 'RouteMapActionTypeReplace', 'RouteMapActionTypeDrop' - Type RouteMapActionType `json:"type,omitempty"` - // Parameters - List of parameters relevant to the action.For instance if type is drop then parameters has list of prefixes to be dropped.If type is add, parameters would have list of ASN numbers to be added - Parameters *[]Parameter `json:"parameters,omitempty"` -} - -// BasicActiveBaseSecurityAdminRule network base admin rule. -type BasicActiveBaseSecurityAdminRule interface { - AsActiveSecurityAdminRule() (*ActiveSecurityAdminRule, bool) - AsActiveDefaultSecurityAdminRule() (*ActiveDefaultSecurityAdminRule, bool) - AsActiveBaseSecurityAdminRule() (*ActiveBaseSecurityAdminRule, bool) -} - -// ActiveBaseSecurityAdminRule network base admin rule. -type ActiveBaseSecurityAdminRule struct { - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // CommitTime - Deployment time string. - CommitTime *date.Time `json:"commitTime,omitempty"` - // Region - Deployment region. - Region *string `json:"region,omitempty"` - // ConfigurationDescription - A description of the security admin configuration. - ConfigurationDescription *string `json:"configurationDescription,omitempty"` - // RuleCollectionDescription - A description of the rule collection. - RuleCollectionDescription *string `json:"ruleCollectionDescription,omitempty"` - // RuleCollectionAppliesToGroups - Groups for rule collection - RuleCollectionAppliesToGroups *[]ManagerSecurityGroupItem `json:"ruleCollectionAppliesToGroups,omitempty"` - // RuleGroups - Effective configuration groups. - RuleGroups *[]ConfigurationGroup `json:"ruleGroups,omitempty"` - // Kind - Possible values include: 'KindActiveBaseSecurityAdminRule', 'KindCustom', 'KindDefault' - Kind Kind `json:"kind,omitempty"` -} - -func unmarshalBasicActiveBaseSecurityAdminRule(body []byte) (BasicActiveBaseSecurityAdminRule, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["kind"] { - case string(KindCustom): - var asar ActiveSecurityAdminRule - err := json.Unmarshal(body, &asar) - return asar, err - case string(KindDefault): - var adsar ActiveDefaultSecurityAdminRule - err := json.Unmarshal(body, &adsar) - return adsar, err - default: - var absar ActiveBaseSecurityAdminRule - err := json.Unmarshal(body, &absar) - return absar, err - } -} -func unmarshalBasicActiveBaseSecurityAdminRuleArray(body []byte) ([]BasicActiveBaseSecurityAdminRule, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - absarArray := make([]BasicActiveBaseSecurityAdminRule, len(rawMessages)) - - for index, rawMessage := range rawMessages { - absar, err := unmarshalBasicActiveBaseSecurityAdminRule(*rawMessage) - if err != nil { - return nil, err - } - absarArray[index] = absar - } - return absarArray, nil -} - -// MarshalJSON is the custom marshaler for ActiveBaseSecurityAdminRule. -func (absar ActiveBaseSecurityAdminRule) MarshalJSON() ([]byte, error) { - absar.Kind = KindActiveBaseSecurityAdminRule - objectMap := make(map[string]interface{}) - if absar.ID != nil { - objectMap["id"] = absar.ID - } - if absar.CommitTime != nil { - objectMap["commitTime"] = absar.CommitTime - } - if absar.Region != nil { - objectMap["region"] = absar.Region - } - if absar.ConfigurationDescription != nil { - objectMap["configurationDescription"] = absar.ConfigurationDescription - } - if absar.RuleCollectionDescription != nil { - objectMap["ruleCollectionDescription"] = absar.RuleCollectionDescription - } - if absar.RuleCollectionAppliesToGroups != nil { - objectMap["ruleCollectionAppliesToGroups"] = absar.RuleCollectionAppliesToGroups - } - if absar.RuleGroups != nil { - objectMap["ruleGroups"] = absar.RuleGroups - } - if absar.Kind != "" { - objectMap["kind"] = absar.Kind - } - return json.Marshal(objectMap) -} - -// AsActiveSecurityAdminRule is the BasicActiveBaseSecurityAdminRule implementation for ActiveBaseSecurityAdminRule. -func (absar ActiveBaseSecurityAdminRule) AsActiveSecurityAdminRule() (*ActiveSecurityAdminRule, bool) { - return nil, false -} - -// AsActiveDefaultSecurityAdminRule is the BasicActiveBaseSecurityAdminRule implementation for ActiveBaseSecurityAdminRule. -func (absar ActiveBaseSecurityAdminRule) AsActiveDefaultSecurityAdminRule() (*ActiveDefaultSecurityAdminRule, bool) { - return nil, false -} - -// AsActiveBaseSecurityAdminRule is the BasicActiveBaseSecurityAdminRule implementation for ActiveBaseSecurityAdminRule. -func (absar ActiveBaseSecurityAdminRule) AsActiveBaseSecurityAdminRule() (*ActiveBaseSecurityAdminRule, bool) { - return &absar, true -} - -// AsBasicActiveBaseSecurityAdminRule is the BasicActiveBaseSecurityAdminRule implementation for ActiveBaseSecurityAdminRule. -func (absar ActiveBaseSecurityAdminRule) AsBasicActiveBaseSecurityAdminRule() (BasicActiveBaseSecurityAdminRule, bool) { - return &absar, true -} - -// ActiveConfigurationParameter effective Virtual Networks Parameter. -type ActiveConfigurationParameter struct { - // Regions - List of regions. - Regions *[]string `json:"regions,omitempty"` - // SkipToken - When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current request) to retrieve the next page of data. - SkipToken *string `json:"skipToken,omitempty"` -} - -// ActiveConnectivityConfiguration active connectivity configuration. -type ActiveConnectivityConfiguration struct { - // CommitTime - Deployment time string. - CommitTime *date.Time `json:"commitTime,omitempty"` - // Region - Deployment region. - Region *string `json:"region,omitempty"` - // ID - Connectivity configuration ID. - ID *string `json:"id,omitempty"` - // ConnectivityConfigurationProperties - Properties of a network manager connectivity configuration - *ConnectivityConfigurationProperties `json:"properties,omitempty"` - // ConfigurationGroups - Effective configuration groups. - ConfigurationGroups *[]ConfigurationGroup `json:"configurationGroups,omitempty"` -} - -// MarshalJSON is the custom marshaler for ActiveConnectivityConfiguration. -func (acc ActiveConnectivityConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if acc.CommitTime != nil { - objectMap["commitTime"] = acc.CommitTime - } - if acc.Region != nil { - objectMap["region"] = acc.Region - } - if acc.ID != nil { - objectMap["id"] = acc.ID - } - if acc.ConnectivityConfigurationProperties != nil { - objectMap["properties"] = acc.ConnectivityConfigurationProperties - } - if acc.ConfigurationGroups != nil { - objectMap["configurationGroups"] = acc.ConfigurationGroups - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ActiveConnectivityConfiguration struct. -func (acc *ActiveConnectivityConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "commitTime": - if v != nil { - var commitTime date.Time - err = json.Unmarshal(*v, &commitTime) - if err != nil { - return err - } - acc.CommitTime = &commitTime - } - case "region": - if v != nil { - var region string - err = json.Unmarshal(*v, ®ion) - if err != nil { - return err - } - acc.Region = ®ion - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - acc.ID = &ID - } - case "properties": - if v != nil { - var connectivityConfigurationProperties ConnectivityConfigurationProperties - err = json.Unmarshal(*v, &connectivityConfigurationProperties) - if err != nil { - return err - } - acc.ConnectivityConfigurationProperties = &connectivityConfigurationProperties - } - case "configurationGroups": - if v != nil { - var configurationGroups []ConfigurationGroup - err = json.Unmarshal(*v, &configurationGroups) - if err != nil { - return err - } - acc.ConfigurationGroups = &configurationGroups - } - } - } - - return nil -} - -// ActiveConnectivityConfigurationsListResult result of the request to list active connectivity -// configurations. It contains a list of active connectivity configurations and a skiptoken to get the next -// set of results. -type ActiveConnectivityConfigurationsListResult struct { - autorest.Response `json:"-"` - // Value - Gets a page of active connectivity configurations. - Value *[]ActiveConnectivityConfiguration `json:"value,omitempty"` - // SkipToken - When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current request) to retrieve the next page of data. - SkipToken *string `json:"skipToken,omitempty"` -} - -// ActiveDefaultSecurityAdminRule network default admin rule. -type ActiveDefaultSecurityAdminRule struct { - // DefaultAdminPropertiesFormat - Indicates the properties of the default security admin rule - *DefaultAdminPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // CommitTime - Deployment time string. - CommitTime *date.Time `json:"commitTime,omitempty"` - // Region - Deployment region. - Region *string `json:"region,omitempty"` - // ConfigurationDescription - A description of the security admin configuration. - ConfigurationDescription *string `json:"configurationDescription,omitempty"` - // RuleCollectionDescription - A description of the rule collection. - RuleCollectionDescription *string `json:"ruleCollectionDescription,omitempty"` - // RuleCollectionAppliesToGroups - Groups for rule collection - RuleCollectionAppliesToGroups *[]ManagerSecurityGroupItem `json:"ruleCollectionAppliesToGroups,omitempty"` - // RuleGroups - Effective configuration groups. - RuleGroups *[]ConfigurationGroup `json:"ruleGroups,omitempty"` - // Kind - Possible values include: 'KindActiveBaseSecurityAdminRule', 'KindCustom', 'KindDefault' - Kind Kind `json:"kind,omitempty"` -} - -// MarshalJSON is the custom marshaler for ActiveDefaultSecurityAdminRule. -func (adsar ActiveDefaultSecurityAdminRule) MarshalJSON() ([]byte, error) { - adsar.Kind = KindDefault - objectMap := make(map[string]interface{}) - if adsar.DefaultAdminPropertiesFormat != nil { - objectMap["properties"] = adsar.DefaultAdminPropertiesFormat - } - if adsar.ID != nil { - objectMap["id"] = adsar.ID - } - if adsar.CommitTime != nil { - objectMap["commitTime"] = adsar.CommitTime - } - if adsar.Region != nil { - objectMap["region"] = adsar.Region - } - if adsar.ConfigurationDescription != nil { - objectMap["configurationDescription"] = adsar.ConfigurationDescription - } - if adsar.RuleCollectionDescription != nil { - objectMap["ruleCollectionDescription"] = adsar.RuleCollectionDescription - } - if adsar.RuleCollectionAppliesToGroups != nil { - objectMap["ruleCollectionAppliesToGroups"] = adsar.RuleCollectionAppliesToGroups - } - if adsar.RuleGroups != nil { - objectMap["ruleGroups"] = adsar.RuleGroups - } - if adsar.Kind != "" { - objectMap["kind"] = adsar.Kind - } - return json.Marshal(objectMap) -} - -// AsActiveSecurityAdminRule is the BasicActiveBaseSecurityAdminRule implementation for ActiveDefaultSecurityAdminRule. -func (adsar ActiveDefaultSecurityAdminRule) AsActiveSecurityAdminRule() (*ActiveSecurityAdminRule, bool) { - return nil, false -} - -// AsActiveDefaultSecurityAdminRule is the BasicActiveBaseSecurityAdminRule implementation for ActiveDefaultSecurityAdminRule. -func (adsar ActiveDefaultSecurityAdminRule) AsActiveDefaultSecurityAdminRule() (*ActiveDefaultSecurityAdminRule, bool) { - return &adsar, true -} - -// AsActiveBaseSecurityAdminRule is the BasicActiveBaseSecurityAdminRule implementation for ActiveDefaultSecurityAdminRule. -func (adsar ActiveDefaultSecurityAdminRule) AsActiveBaseSecurityAdminRule() (*ActiveBaseSecurityAdminRule, bool) { - return nil, false -} - -// AsBasicActiveBaseSecurityAdminRule is the BasicActiveBaseSecurityAdminRule implementation for ActiveDefaultSecurityAdminRule. -func (adsar ActiveDefaultSecurityAdminRule) AsBasicActiveBaseSecurityAdminRule() (BasicActiveBaseSecurityAdminRule, bool) { - return &adsar, true -} - -// UnmarshalJSON is the custom unmarshaler for ActiveDefaultSecurityAdminRule struct. -func (adsar *ActiveDefaultSecurityAdminRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var defaultAdminPropertiesFormat DefaultAdminPropertiesFormat - err = json.Unmarshal(*v, &defaultAdminPropertiesFormat) - if err != nil { - return err - } - adsar.DefaultAdminPropertiesFormat = &defaultAdminPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - adsar.ID = &ID - } - case "commitTime": - if v != nil { - var commitTime date.Time - err = json.Unmarshal(*v, &commitTime) - if err != nil { - return err - } - adsar.CommitTime = &commitTime - } - case "region": - if v != nil { - var region string - err = json.Unmarshal(*v, ®ion) - if err != nil { - return err - } - adsar.Region = ®ion - } - case "configurationDescription": - if v != nil { - var configurationDescription string - err = json.Unmarshal(*v, &configurationDescription) - if err != nil { - return err - } - adsar.ConfigurationDescription = &configurationDescription - } - case "ruleCollectionDescription": - if v != nil { - var ruleCollectionDescription string - err = json.Unmarshal(*v, &ruleCollectionDescription) - if err != nil { - return err - } - adsar.RuleCollectionDescription = &ruleCollectionDescription - } - case "ruleCollectionAppliesToGroups": - if v != nil { - var ruleCollectionAppliesToGroups []ManagerSecurityGroupItem - err = json.Unmarshal(*v, &ruleCollectionAppliesToGroups) - if err != nil { - return err - } - adsar.RuleCollectionAppliesToGroups = &ruleCollectionAppliesToGroups - } - case "ruleGroups": - if v != nil { - var ruleGroups []ConfigurationGroup - err = json.Unmarshal(*v, &ruleGroups) - if err != nil { - return err - } - adsar.RuleGroups = &ruleGroups - } - case "kind": - if v != nil { - var kind Kind - err = json.Unmarshal(*v, &kind) - if err != nil { - return err - } - adsar.Kind = kind - } - } - } - - return nil -} - -// ActiveSecurityAdminRule network admin rule. -type ActiveSecurityAdminRule struct { - // AdminPropertiesFormat - Indicates the properties of the security admin rule - *AdminPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // CommitTime - Deployment time string. - CommitTime *date.Time `json:"commitTime,omitempty"` - // Region - Deployment region. - Region *string `json:"region,omitempty"` - // ConfigurationDescription - A description of the security admin configuration. - ConfigurationDescription *string `json:"configurationDescription,omitempty"` - // RuleCollectionDescription - A description of the rule collection. - RuleCollectionDescription *string `json:"ruleCollectionDescription,omitempty"` - // RuleCollectionAppliesToGroups - Groups for rule collection - RuleCollectionAppliesToGroups *[]ManagerSecurityGroupItem `json:"ruleCollectionAppliesToGroups,omitempty"` - // RuleGroups - Effective configuration groups. - RuleGroups *[]ConfigurationGroup `json:"ruleGroups,omitempty"` - // Kind - Possible values include: 'KindActiveBaseSecurityAdminRule', 'KindCustom', 'KindDefault' - Kind Kind `json:"kind,omitempty"` -} - -// MarshalJSON is the custom marshaler for ActiveSecurityAdminRule. -func (asar ActiveSecurityAdminRule) MarshalJSON() ([]byte, error) { - asar.Kind = KindCustom - objectMap := make(map[string]interface{}) - if asar.AdminPropertiesFormat != nil { - objectMap["properties"] = asar.AdminPropertiesFormat - } - if asar.ID != nil { - objectMap["id"] = asar.ID - } - if asar.CommitTime != nil { - objectMap["commitTime"] = asar.CommitTime - } - if asar.Region != nil { - objectMap["region"] = asar.Region - } - if asar.ConfigurationDescription != nil { - objectMap["configurationDescription"] = asar.ConfigurationDescription - } - if asar.RuleCollectionDescription != nil { - objectMap["ruleCollectionDescription"] = asar.RuleCollectionDescription - } - if asar.RuleCollectionAppliesToGroups != nil { - objectMap["ruleCollectionAppliesToGroups"] = asar.RuleCollectionAppliesToGroups - } - if asar.RuleGroups != nil { - objectMap["ruleGroups"] = asar.RuleGroups - } - if asar.Kind != "" { - objectMap["kind"] = asar.Kind - } - return json.Marshal(objectMap) -} - -// AsActiveSecurityAdminRule is the BasicActiveBaseSecurityAdminRule implementation for ActiveSecurityAdminRule. -func (asar ActiveSecurityAdminRule) AsActiveSecurityAdminRule() (*ActiveSecurityAdminRule, bool) { - return &asar, true -} - -// AsActiveDefaultSecurityAdminRule is the BasicActiveBaseSecurityAdminRule implementation for ActiveSecurityAdminRule. -func (asar ActiveSecurityAdminRule) AsActiveDefaultSecurityAdminRule() (*ActiveDefaultSecurityAdminRule, bool) { - return nil, false -} - -// AsActiveBaseSecurityAdminRule is the BasicActiveBaseSecurityAdminRule implementation for ActiveSecurityAdminRule. -func (asar ActiveSecurityAdminRule) AsActiveBaseSecurityAdminRule() (*ActiveBaseSecurityAdminRule, bool) { - return nil, false -} - -// AsBasicActiveBaseSecurityAdminRule is the BasicActiveBaseSecurityAdminRule implementation for ActiveSecurityAdminRule. -func (asar ActiveSecurityAdminRule) AsBasicActiveBaseSecurityAdminRule() (BasicActiveBaseSecurityAdminRule, bool) { - return &asar, true -} - -// UnmarshalJSON is the custom unmarshaler for ActiveSecurityAdminRule struct. -func (asar *ActiveSecurityAdminRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var adminPropertiesFormat AdminPropertiesFormat - err = json.Unmarshal(*v, &adminPropertiesFormat) - if err != nil { - return err - } - asar.AdminPropertiesFormat = &adminPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - asar.ID = &ID - } - case "commitTime": - if v != nil { - var commitTime date.Time - err = json.Unmarshal(*v, &commitTime) - if err != nil { - return err - } - asar.CommitTime = &commitTime - } - case "region": - if v != nil { - var region string - err = json.Unmarshal(*v, ®ion) - if err != nil { - return err - } - asar.Region = ®ion - } - case "configurationDescription": - if v != nil { - var configurationDescription string - err = json.Unmarshal(*v, &configurationDescription) - if err != nil { - return err - } - asar.ConfigurationDescription = &configurationDescription - } - case "ruleCollectionDescription": - if v != nil { - var ruleCollectionDescription string - err = json.Unmarshal(*v, &ruleCollectionDescription) - if err != nil { - return err - } - asar.RuleCollectionDescription = &ruleCollectionDescription - } - case "ruleCollectionAppliesToGroups": - if v != nil { - var ruleCollectionAppliesToGroups []ManagerSecurityGroupItem - err = json.Unmarshal(*v, &ruleCollectionAppliesToGroups) - if err != nil { - return err - } - asar.RuleCollectionAppliesToGroups = &ruleCollectionAppliesToGroups - } - case "ruleGroups": - if v != nil { - var ruleGroups []ConfigurationGroup - err = json.Unmarshal(*v, &ruleGroups) - if err != nil { - return err - } - asar.RuleGroups = &ruleGroups - } - case "kind": - if v != nil { - var kind Kind - err = json.Unmarshal(*v, &kind) - if err != nil { - return err - } - asar.Kind = kind - } - } - } - - return nil -} - -// ActiveSecurityAdminRulesListResult result of the request to list active security admin rules. It -// contains a list of active security admin rules and a skiptoken to get the next set of results. -type ActiveSecurityAdminRulesListResult struct { - autorest.Response `json:"-"` - // Value - Gets a page of active security admin rules. - Value *[]BasicActiveBaseSecurityAdminRule `json:"value,omitempty"` - // SkipToken - When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current request) to retrieve the next page of data. - SkipToken *string `json:"skipToken,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for ActiveSecurityAdminRulesListResult struct. -func (asarlr *ActiveSecurityAdminRulesListResult) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "value": - if v != nil { - value, err := unmarshalBasicActiveBaseSecurityAdminRuleArray(*v) - if err != nil { - return err - } - asarlr.Value = &value - } - case "skipToken": - if v != nil { - var skipToken string - err = json.Unmarshal(*v, &skipToken) - if err != nil { - return err - } - asarlr.SkipToken = &skipToken - } - } - } - - return nil -} - -// AddressPrefixItem address prefix item. -type AddressPrefixItem struct { - // AddressPrefix - Address prefix. - AddressPrefix *string `json:"addressPrefix,omitempty"` - // AddressPrefixType - Address prefix type. Possible values include: 'IPPrefix', 'ServiceTag' - AddressPrefixType AddressPrefixType `json:"addressPrefixType,omitempty"` -} - -// AddressSpace addressSpace contains an array of IP address ranges that can be used by subnets of the -// virtual network. -type AddressSpace struct { - // AddressPrefixes - A list of address blocks reserved for this virtual network in CIDR notation. - AddressPrefixes *[]string `json:"addressPrefixes,omitempty"` -} - -// AdminPropertiesFormat security admin rule resource. -type AdminPropertiesFormat struct { - // Description - A description for this rule. Restricted to 140 chars. - Description *string `json:"description,omitempty"` - // Protocol - Network protocol this rule applies to. Possible values include: 'SecurityConfigurationRuleProtocolTCP', 'SecurityConfigurationRuleProtocolUDP', 'SecurityConfigurationRuleProtocolIcmp', 'SecurityConfigurationRuleProtocolEsp', 'SecurityConfigurationRuleProtocolAny', 'SecurityConfigurationRuleProtocolAh' - Protocol SecurityConfigurationRuleProtocol `json:"protocol,omitempty"` - // Sources - The CIDR or source IP ranges. - Sources *[]AddressPrefixItem `json:"sources,omitempty"` - // Destinations - The destination address prefixes. CIDR or destination IP ranges. - Destinations *[]AddressPrefixItem `json:"destinations,omitempty"` - // SourcePortRanges - The source port ranges. - SourcePortRanges *[]string `json:"sourcePortRanges,omitempty"` - // DestinationPortRanges - The destination port ranges. - DestinationPortRanges *[]string `json:"destinationPortRanges,omitempty"` - // Access - Indicates the access allowed for this particular rule. Possible values include: 'SecurityConfigurationRuleAccessAllow', 'SecurityConfigurationRuleAccessDeny', 'SecurityConfigurationRuleAccessAlwaysAllow' - Access SecurityConfigurationRuleAccess `json:"access,omitempty"` - // Priority - The priority of the rule. The value can be between 1 and 4096. The priority number must be unique for each rule in the collection. The lower the priority number, the higher the priority of the rule. - Priority *int32 `json:"priority,omitempty"` - // Direction - Indicates if the traffic matched against the rule in inbound or outbound. Possible values include: 'SecurityConfigurationRuleDirectionInbound', 'SecurityConfigurationRuleDirectionOutbound' - Direction SecurityConfigurationRuleDirection `json:"direction,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for AdminPropertiesFormat. -func (apf AdminPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if apf.Description != nil { - objectMap["description"] = apf.Description - } - if apf.Protocol != "" { - objectMap["protocol"] = apf.Protocol - } - if apf.Sources != nil { - objectMap["sources"] = apf.Sources - } - if apf.Destinations != nil { - objectMap["destinations"] = apf.Destinations - } - if apf.SourcePortRanges != nil { - objectMap["sourcePortRanges"] = apf.SourcePortRanges - } - if apf.DestinationPortRanges != nil { - objectMap["destinationPortRanges"] = apf.DestinationPortRanges - } - if apf.Access != "" { - objectMap["access"] = apf.Access - } - if apf.Priority != nil { - objectMap["priority"] = apf.Priority - } - if apf.Direction != "" { - objectMap["direction"] = apf.Direction - } - return json.Marshal(objectMap) -} - -// AdminRule network admin rule. -type AdminRule struct { - // AdminPropertiesFormat - Indicates the properties of the security admin rule - *AdminPropertiesFormat `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system metadata related to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Kind - Possible values include: 'KindBasicBaseAdminRuleKindBaseAdminRule', 'KindBasicBaseAdminRuleKindCustom', 'KindBasicBaseAdminRuleKindDefault' - Kind KindBasicBaseAdminRule `json:"kind,omitempty"` -} - -// MarshalJSON is the custom marshaler for AdminRule. -func (ar AdminRule) MarshalJSON() ([]byte, error) { - ar.Kind = KindBasicBaseAdminRuleKindCustom - objectMap := make(map[string]interface{}) - if ar.AdminPropertiesFormat != nil { - objectMap["properties"] = ar.AdminPropertiesFormat - } - if ar.Kind != "" { - objectMap["kind"] = ar.Kind - } - return json.Marshal(objectMap) -} - -// AsAdminRule is the BasicBaseAdminRule implementation for AdminRule. -func (ar AdminRule) AsAdminRule() (*AdminRule, bool) { - return &ar, true -} - -// AsDefaultAdminRule is the BasicBaseAdminRule implementation for AdminRule. -func (ar AdminRule) AsDefaultAdminRule() (*DefaultAdminRule, bool) { - return nil, false -} - -// AsBaseAdminRule is the BasicBaseAdminRule implementation for AdminRule. -func (ar AdminRule) AsBaseAdminRule() (*BaseAdminRule, bool) { - return nil, false -} - -// AsBasicBaseAdminRule is the BasicBaseAdminRule implementation for AdminRule. -func (ar AdminRule) AsBasicBaseAdminRule() (BasicBaseAdminRule, bool) { - return &ar, true -} - -// UnmarshalJSON is the custom unmarshaler for AdminRule struct. -func (ar *AdminRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var adminPropertiesFormat AdminPropertiesFormat - err = json.Unmarshal(*v, &adminPropertiesFormat) - if err != nil { - return err - } - ar.AdminPropertiesFormat = &adminPropertiesFormat - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - ar.SystemData = &systemData - } - case "kind": - if v != nil { - var kind KindBasicBaseAdminRule - err = json.Unmarshal(*v, &kind) - if err != nil { - return err - } - ar.Kind = kind - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ar.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ar.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ar.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ar.Etag = &etag - } - } - } - - return nil -} - -// AdminRuleCollection defines the admin rule collection. -type AdminRuleCollection struct { - autorest.Response `json:"-"` - // AdminRuleCollectionPropertiesFormat - Indicates the properties for the network manager admin rule collection. - *AdminRuleCollectionPropertiesFormat `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system metadata related to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for AdminRuleCollection. -func (arc AdminRuleCollection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if arc.AdminRuleCollectionPropertiesFormat != nil { - objectMap["properties"] = arc.AdminRuleCollectionPropertiesFormat - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AdminRuleCollection struct. -func (arc *AdminRuleCollection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var adminRuleCollectionPropertiesFormat AdminRuleCollectionPropertiesFormat - err = json.Unmarshal(*v, &adminRuleCollectionPropertiesFormat) - if err != nil { - return err - } - arc.AdminRuleCollectionPropertiesFormat = &adminRuleCollectionPropertiesFormat - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - arc.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - arc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - arc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - arc.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - arc.Etag = &etag - } - } - } - - return nil -} - -// AdminRuleCollectionListResult security admin configuration rule collection list result. -type AdminRuleCollectionListResult struct { - autorest.Response `json:"-"` - // Value - A list of network manager security admin configuration rule collections - Value *[]AdminRuleCollection `json:"value,omitempty"` - // NextLink - Gets the URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// AdminRuleCollectionListResultIterator provides access to a complete listing of AdminRuleCollection -// values. -type AdminRuleCollectionListResultIterator struct { - i int - page AdminRuleCollectionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AdminRuleCollectionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRuleCollectionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AdminRuleCollectionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AdminRuleCollectionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AdminRuleCollectionListResultIterator) Response() AdminRuleCollectionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AdminRuleCollectionListResultIterator) Value() AdminRuleCollection { - if !iter.page.NotDone() { - return AdminRuleCollection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AdminRuleCollectionListResultIterator type. -func NewAdminRuleCollectionListResultIterator(page AdminRuleCollectionListResultPage) AdminRuleCollectionListResultIterator { - return AdminRuleCollectionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (arclr AdminRuleCollectionListResult) IsEmpty() bool { - return arclr.Value == nil || len(*arclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (arclr AdminRuleCollectionListResult) hasNextLink() bool { - return arclr.NextLink != nil && len(*arclr.NextLink) != 0 -} - -// adminRuleCollectionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (arclr AdminRuleCollectionListResult) adminRuleCollectionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !arclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(arclr.NextLink))) -} - -// AdminRuleCollectionListResultPage contains a page of AdminRuleCollection values. -type AdminRuleCollectionListResultPage struct { - fn func(context.Context, AdminRuleCollectionListResult) (AdminRuleCollectionListResult, error) - arclr AdminRuleCollectionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AdminRuleCollectionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRuleCollectionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.arclr) - if err != nil { - return err - } - page.arclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AdminRuleCollectionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AdminRuleCollectionListResultPage) NotDone() bool { - return !page.arclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AdminRuleCollectionListResultPage) Response() AdminRuleCollectionListResult { - return page.arclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AdminRuleCollectionListResultPage) Values() []AdminRuleCollection { - if page.arclr.IsEmpty() { - return nil - } - return *page.arclr.Value -} - -// Creates a new instance of the AdminRuleCollectionListResultPage type. -func NewAdminRuleCollectionListResultPage(cur AdminRuleCollectionListResult, getNextPage func(context.Context, AdminRuleCollectionListResult) (AdminRuleCollectionListResult, error)) AdminRuleCollectionListResultPage { - return AdminRuleCollectionListResultPage{ - fn: getNextPage, - arclr: cur, - } -} - -// AdminRuleCollectionPropertiesFormat defines the admin rule collection properties. -type AdminRuleCollectionPropertiesFormat struct { - // Description - A description of the admin rule collection. - Description *string `json:"description,omitempty"` - // AppliesToGroups - Groups for configuration - AppliesToGroups *[]ManagerSecurityGroupItem `json:"appliesToGroups,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for AdminRuleCollectionPropertiesFormat. -func (arcpf AdminRuleCollectionPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if arcpf.Description != nil { - objectMap["description"] = arcpf.Description - } - if arcpf.AppliesToGroups != nil { - objectMap["appliesToGroups"] = arcpf.AppliesToGroups - } - return json.Marshal(objectMap) -} - -// AdminRuleCollectionsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type AdminRuleCollectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AdminRuleCollectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AdminRuleCollectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AdminRuleCollectionsDeleteFuture.Result. -func (future *AdminRuleCollectionsDeleteFuture) result(client AdminRuleCollectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRuleCollectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.AdminRuleCollectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// AdminRuleListResult security configuration admin rule list result. -type AdminRuleListResult struct { - autorest.Response `json:"-"` - // Value - A list of admin rules - Value *[]BasicBaseAdminRule `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for AdminRuleListResult struct. -func (arlr *AdminRuleListResult) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "value": - if v != nil { - value, err := unmarshalBasicBaseAdminRuleArray(*v) - if err != nil { - return err - } - arlr.Value = &value - } - case "nextLink": - if v != nil { - var nextLink string - err = json.Unmarshal(*v, &nextLink) - if err != nil { - return err - } - arlr.NextLink = &nextLink - } - } - } - - return nil -} - -// AdminRuleListResultIterator provides access to a complete listing of BaseAdminRule values. -type AdminRuleListResultIterator struct { - i int - page AdminRuleListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AdminRuleListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRuleListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AdminRuleListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AdminRuleListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AdminRuleListResultIterator) Response() AdminRuleListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AdminRuleListResultIterator) Value() BasicBaseAdminRule { - if !iter.page.NotDone() { - return BaseAdminRule{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AdminRuleListResultIterator type. -func NewAdminRuleListResultIterator(page AdminRuleListResultPage) AdminRuleListResultIterator { - return AdminRuleListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (arlr AdminRuleListResult) IsEmpty() bool { - return arlr.Value == nil || len(*arlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (arlr AdminRuleListResult) hasNextLink() bool { - return arlr.NextLink != nil && len(*arlr.NextLink) != 0 -} - -// adminRuleListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (arlr AdminRuleListResult) adminRuleListResultPreparer(ctx context.Context) (*http.Request, error) { - if !arlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(arlr.NextLink))) -} - -// AdminRuleListResultPage contains a page of BasicBaseAdminRule values. -type AdminRuleListResultPage struct { - fn func(context.Context, AdminRuleListResult) (AdminRuleListResult, error) - arlr AdminRuleListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AdminRuleListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AdminRuleListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.arlr) - if err != nil { - return err - } - page.arlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AdminRuleListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AdminRuleListResultPage) NotDone() bool { - return !page.arlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AdminRuleListResultPage) Response() AdminRuleListResult { - return page.arlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AdminRuleListResultPage) Values() []BasicBaseAdminRule { - if page.arlr.IsEmpty() { - return nil - } - return *page.arlr.Value -} - -// Creates a new instance of the AdminRuleListResultPage type. -func NewAdminRuleListResultPage(cur AdminRuleListResult, getNextPage func(context.Context, AdminRuleListResult) (AdminRuleListResult, error)) AdminRuleListResultPage { - return AdminRuleListResultPage{ - fn: getNextPage, - arlr: cur, - } -} - -// AdminRulesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type AdminRulesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AdminRulesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AdminRulesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AdminRulesDeleteFuture.Result. -func (future *AdminRulesDeleteFuture) result(client AdminRulesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AdminRulesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.AdminRulesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ApplicationGateway application gateway resource. -type ApplicationGateway struct { - autorest.Response `json:"-"` - // ApplicationGatewayPropertiesFormat - Properties of the application gateway. - *ApplicationGatewayPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Zones - A list of availability zones denoting where the resource needs to come from. - Zones *[]string `json:"zones,omitempty"` - // Identity - The identity of the application gateway, if configured. - Identity *ManagedServiceIdentity `json:"identity,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ApplicationGateway. -func (ag ApplicationGateway) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ag.ApplicationGatewayPropertiesFormat != nil { - objectMap["properties"] = ag.ApplicationGatewayPropertiesFormat - } - if ag.Zones != nil { - objectMap["zones"] = ag.Zones - } - if ag.Identity != nil { - objectMap["identity"] = ag.Identity - } - if ag.ID != nil { - objectMap["id"] = ag.ID - } - if ag.Location != nil { - objectMap["location"] = ag.Location - } - if ag.Tags != nil { - objectMap["tags"] = ag.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGateway struct. -func (ag *ApplicationGateway) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayPropertiesFormat ApplicationGatewayPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayPropertiesFormat) - if err != nil { - return err - } - ag.ApplicationGatewayPropertiesFormat = &applicationGatewayPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ag.Etag = &etag - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - ag.Zones = &zones - } - case "identity": - if v != nil { - var identity ManagedServiceIdentity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - ag.Identity = &identity - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ag.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ag.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ag.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ag.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - ag.Tags = tags - } - } - } - - return nil -} - -// ApplicationGatewayAuthenticationCertificate authentication certificates of an application gateway. -type ApplicationGatewayAuthenticationCertificate struct { - // ApplicationGatewayAuthenticationCertificatePropertiesFormat - Properties of the application gateway authentication certificate. - *ApplicationGatewayAuthenticationCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the authentication certificate that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayAuthenticationCertificate. -func (agac ApplicationGatewayAuthenticationCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agac.ApplicationGatewayAuthenticationCertificatePropertiesFormat != nil { - objectMap["properties"] = agac.ApplicationGatewayAuthenticationCertificatePropertiesFormat - } - if agac.Name != nil { - objectMap["name"] = agac.Name - } - if agac.ID != nil { - objectMap["id"] = agac.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayAuthenticationCertificate struct. -func (agac *ApplicationGatewayAuthenticationCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayAuthenticationCertificatePropertiesFormat ApplicationGatewayAuthenticationCertificatePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayAuthenticationCertificatePropertiesFormat) - if err != nil { - return err - } - agac.ApplicationGatewayAuthenticationCertificatePropertiesFormat = &applicationGatewayAuthenticationCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agac.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agac.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agac.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agac.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayAuthenticationCertificatePropertiesFormat authentication certificates properties of an -// application gateway. -type ApplicationGatewayAuthenticationCertificatePropertiesFormat struct { - // Data - Certificate public data. - Data *string `json:"data,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the authentication certificate resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayAuthenticationCertificatePropertiesFormat. -func (agacpf ApplicationGatewayAuthenticationCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agacpf.Data != nil { - objectMap["data"] = agacpf.Data - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayAutoscaleConfiguration application Gateway autoscale configuration. -type ApplicationGatewayAutoscaleConfiguration struct { - // MinCapacity - Lower bound on number of Application Gateway capacity. - MinCapacity *int32 `json:"minCapacity,omitempty"` - // MaxCapacity - Upper bound on number of Application Gateway capacity. - MaxCapacity *int32 `json:"maxCapacity,omitempty"` -} - -// ApplicationGatewayAvailableSslOptions response for ApplicationGatewayAvailableSslOptions API service -// call. -type ApplicationGatewayAvailableSslOptions struct { - autorest.Response `json:"-"` - // ApplicationGatewayAvailableSslOptionsPropertiesFormat - Properties of the application gateway available SSL options. - *ApplicationGatewayAvailableSslOptionsPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayAvailableSslOptions. -func (agaso ApplicationGatewayAvailableSslOptions) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agaso.ApplicationGatewayAvailableSslOptionsPropertiesFormat != nil { - objectMap["properties"] = agaso.ApplicationGatewayAvailableSslOptionsPropertiesFormat - } - if agaso.ID != nil { - objectMap["id"] = agaso.ID - } - if agaso.Location != nil { - objectMap["location"] = agaso.Location - } - if agaso.Tags != nil { - objectMap["tags"] = agaso.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayAvailableSslOptions struct. -func (agaso *ApplicationGatewayAvailableSslOptions) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayAvailableSslOptionsPropertiesFormat ApplicationGatewayAvailableSslOptionsPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayAvailableSslOptionsPropertiesFormat) - if err != nil { - return err - } - agaso.ApplicationGatewayAvailableSslOptionsPropertiesFormat = &applicationGatewayAvailableSslOptionsPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agaso.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agaso.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agaso.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - agaso.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - agaso.Tags = tags - } - } - } - - return nil -} - -// ApplicationGatewayAvailableSslOptionsPropertiesFormat properties of -// ApplicationGatewayAvailableSslOptions. -type ApplicationGatewayAvailableSslOptionsPropertiesFormat struct { - // PredefinedPolicies - List of available Ssl predefined policy. - PredefinedPolicies *[]SubResource `json:"predefinedPolicies,omitempty"` - // DefaultPolicy - Name of the Ssl predefined policy applied by default to application gateway. Possible values include: 'AppGwSslPolicy20150501', 'AppGwSslPolicy20170401', 'AppGwSslPolicy20170401S', 'AppGwSslPolicy20220101', 'AppGwSslPolicy20220101S' - DefaultPolicy ApplicationGatewaySslPolicyName `json:"defaultPolicy,omitempty"` - // AvailableCipherSuites - List of available Ssl cipher suites. - AvailableCipherSuites *[]ApplicationGatewaySslCipherSuite `json:"availableCipherSuites,omitempty"` - // AvailableProtocols - List of available Ssl protocols. - AvailableProtocols *[]ApplicationGatewaySslProtocol `json:"availableProtocols,omitempty"` -} - -// ApplicationGatewayAvailableSslPredefinedPolicies response for ApplicationGatewayAvailableSslOptions API -// service call. -type ApplicationGatewayAvailableSslPredefinedPolicies struct { - autorest.Response `json:"-"` - // Value - List of available Ssl predefined policy. - Value *[]ApplicationGatewaySslPredefinedPolicy `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ApplicationGatewayAvailableSslPredefinedPoliciesIterator provides access to a complete listing of -// ApplicationGatewaySslPredefinedPolicy values. -type ApplicationGatewayAvailableSslPredefinedPoliciesIterator struct { - i int - page ApplicationGatewayAvailableSslPredefinedPoliciesPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ApplicationGatewayAvailableSslPredefinedPoliciesIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayAvailableSslPredefinedPoliciesIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ApplicationGatewayAvailableSslPredefinedPoliciesIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ApplicationGatewayAvailableSslPredefinedPoliciesIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ApplicationGatewayAvailableSslPredefinedPoliciesIterator) Response() ApplicationGatewayAvailableSslPredefinedPolicies { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ApplicationGatewayAvailableSslPredefinedPoliciesIterator) Value() ApplicationGatewaySslPredefinedPolicy { - if !iter.page.NotDone() { - return ApplicationGatewaySslPredefinedPolicy{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ApplicationGatewayAvailableSslPredefinedPoliciesIterator type. -func NewApplicationGatewayAvailableSslPredefinedPoliciesIterator(page ApplicationGatewayAvailableSslPredefinedPoliciesPage) ApplicationGatewayAvailableSslPredefinedPoliciesIterator { - return ApplicationGatewayAvailableSslPredefinedPoliciesIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (agaspp ApplicationGatewayAvailableSslPredefinedPolicies) IsEmpty() bool { - return agaspp.Value == nil || len(*agaspp.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (agaspp ApplicationGatewayAvailableSslPredefinedPolicies) hasNextLink() bool { - return agaspp.NextLink != nil && len(*agaspp.NextLink) != 0 -} - -// applicationGatewayAvailableSslPredefinedPoliciesPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (agaspp ApplicationGatewayAvailableSslPredefinedPolicies) applicationGatewayAvailableSslPredefinedPoliciesPreparer(ctx context.Context) (*http.Request, error) { - if !agaspp.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(agaspp.NextLink))) -} - -// ApplicationGatewayAvailableSslPredefinedPoliciesPage contains a page of -// ApplicationGatewaySslPredefinedPolicy values. -type ApplicationGatewayAvailableSslPredefinedPoliciesPage struct { - fn func(context.Context, ApplicationGatewayAvailableSslPredefinedPolicies) (ApplicationGatewayAvailableSslPredefinedPolicies, error) - agaspp ApplicationGatewayAvailableSslPredefinedPolicies -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ApplicationGatewayAvailableSslPredefinedPoliciesPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayAvailableSslPredefinedPoliciesPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.agaspp) - if err != nil { - return err - } - page.agaspp = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ApplicationGatewayAvailableSslPredefinedPoliciesPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ApplicationGatewayAvailableSslPredefinedPoliciesPage) NotDone() bool { - return !page.agaspp.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ApplicationGatewayAvailableSslPredefinedPoliciesPage) Response() ApplicationGatewayAvailableSslPredefinedPolicies { - return page.agaspp -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ApplicationGatewayAvailableSslPredefinedPoliciesPage) Values() []ApplicationGatewaySslPredefinedPolicy { - if page.agaspp.IsEmpty() { - return nil - } - return *page.agaspp.Value -} - -// Creates a new instance of the ApplicationGatewayAvailableSslPredefinedPoliciesPage type. -func NewApplicationGatewayAvailableSslPredefinedPoliciesPage(cur ApplicationGatewayAvailableSslPredefinedPolicies, getNextPage func(context.Context, ApplicationGatewayAvailableSslPredefinedPolicies) (ApplicationGatewayAvailableSslPredefinedPolicies, error)) ApplicationGatewayAvailableSslPredefinedPoliciesPage { - return ApplicationGatewayAvailableSslPredefinedPoliciesPage{ - fn: getNextPage, - agaspp: cur, - } -} - -// ApplicationGatewayAvailableWafRuleSetsResult response for ApplicationGatewayAvailableWafRuleSets API -// service call. -type ApplicationGatewayAvailableWafRuleSetsResult struct { - autorest.Response `json:"-"` - // Value - The list of application gateway rule sets. - Value *[]ApplicationGatewayFirewallRuleSet `json:"value,omitempty"` -} - -// ApplicationGatewayBackendAddress backend address of an application gateway. -type ApplicationGatewayBackendAddress struct { - // Fqdn - Fully qualified domain name (FQDN). - Fqdn *string `json:"fqdn,omitempty"` - // IPAddress - IP address. - IPAddress *string `json:"ipAddress,omitempty"` -} - -// ApplicationGatewayBackendAddressPool backend Address Pool of an application gateway. -type ApplicationGatewayBackendAddressPool struct { - // ApplicationGatewayBackendAddressPoolPropertiesFormat - Properties of the application gateway backend address pool. - *ApplicationGatewayBackendAddressPoolPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the backend address pool that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayBackendAddressPool. -func (agbap ApplicationGatewayBackendAddressPool) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agbap.ApplicationGatewayBackendAddressPoolPropertiesFormat != nil { - objectMap["properties"] = agbap.ApplicationGatewayBackendAddressPoolPropertiesFormat - } - if agbap.Name != nil { - objectMap["name"] = agbap.Name - } - if agbap.ID != nil { - objectMap["id"] = agbap.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayBackendAddressPool struct. -func (agbap *ApplicationGatewayBackendAddressPool) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayBackendAddressPoolPropertiesFormat ApplicationGatewayBackendAddressPoolPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayBackendAddressPoolPropertiesFormat) - if err != nil { - return err - } - agbap.ApplicationGatewayBackendAddressPoolPropertiesFormat = &applicationGatewayBackendAddressPoolPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agbap.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agbap.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agbap.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agbap.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayBackendAddressPoolPropertiesFormat properties of Backend Address Pool of an -// application gateway. -type ApplicationGatewayBackendAddressPoolPropertiesFormat struct { - // BackendIPConfigurations - READ-ONLY; Collection of references to IPs defined in network interfaces. - BackendIPConfigurations *[]InterfaceIPConfiguration `json:"backendIPConfigurations,omitempty"` - // BackendAddresses - Backend addresses. - BackendAddresses *[]ApplicationGatewayBackendAddress `json:"backendAddresses,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the backend address pool resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayBackendAddressPoolPropertiesFormat. -func (agbappf ApplicationGatewayBackendAddressPoolPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agbappf.BackendAddresses != nil { - objectMap["backendAddresses"] = agbappf.BackendAddresses - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayBackendHealth response for ApplicationGatewayBackendHealth API service call. -type ApplicationGatewayBackendHealth struct { - autorest.Response `json:"-"` - // BackendAddressPools - A list of ApplicationGatewayBackendHealthPool resources. - BackendAddressPools *[]ApplicationGatewayBackendHealthPool `json:"backendAddressPools,omitempty"` -} - -// ApplicationGatewayBackendHealthHTTPSettings application gateway BackendHealthHttp settings. -type ApplicationGatewayBackendHealthHTTPSettings struct { - // BackendHTTPSettings - Reference to an ApplicationGatewayBackendHttpSettings resource. - BackendHTTPSettings *ApplicationGatewayBackendHTTPSettings `json:"backendHttpSettings,omitempty"` - // Servers - List of ApplicationGatewayBackendHealthServer resources. - Servers *[]ApplicationGatewayBackendHealthServer `json:"servers,omitempty"` -} - -// ApplicationGatewayBackendHealthOnDemand result of on demand test probe. -type ApplicationGatewayBackendHealthOnDemand struct { - autorest.Response `json:"-"` - // BackendAddressPool - Reference to an ApplicationGatewayBackendAddressPool resource. - BackendAddressPool *ApplicationGatewayBackendAddressPool `json:"backendAddressPool,omitempty"` - // BackendHealthHTTPSettings - Application gateway BackendHealthHttp settings. - BackendHealthHTTPSettings *ApplicationGatewayBackendHealthHTTPSettings `json:"backendHealthHttpSettings,omitempty"` -} - -// ApplicationGatewayBackendHealthPool application gateway BackendHealth pool. -type ApplicationGatewayBackendHealthPool struct { - // BackendAddressPool - Reference to an ApplicationGatewayBackendAddressPool resource. - BackendAddressPool *ApplicationGatewayBackendAddressPool `json:"backendAddressPool,omitempty"` - // BackendHTTPSettingsCollection - List of ApplicationGatewayBackendHealthHttpSettings resources. - BackendHTTPSettingsCollection *[]ApplicationGatewayBackendHealthHTTPSettings `json:"backendHttpSettingsCollection,omitempty"` -} - -// ApplicationGatewayBackendHealthServer application gateway backendhealth http settings. -type ApplicationGatewayBackendHealthServer struct { - // Address - IP address or FQDN of backend server. - Address *string `json:"address,omitempty"` - // IPConfiguration - Reference to IP configuration of backend server. - IPConfiguration *InterfaceIPConfiguration `json:"ipConfiguration,omitempty"` - // Health - Health of backend server. Possible values include: 'Unknown', 'Up', 'Down', 'Partial', 'Draining' - Health ApplicationGatewayBackendHealthServerHealth `json:"health,omitempty"` - // HealthProbeLog - Health Probe Log. - HealthProbeLog *string `json:"healthProbeLog,omitempty"` -} - -// ApplicationGatewayBackendHTTPSettings backend address pool settings of an application gateway. -type ApplicationGatewayBackendHTTPSettings struct { - // ApplicationGatewayBackendHTTPSettingsPropertiesFormat - Properties of the application gateway backend HTTP settings. - *ApplicationGatewayBackendHTTPSettingsPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the backend http settings that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayBackendHTTPSettings. -func (agbhs ApplicationGatewayBackendHTTPSettings) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agbhs.ApplicationGatewayBackendHTTPSettingsPropertiesFormat != nil { - objectMap["properties"] = agbhs.ApplicationGatewayBackendHTTPSettingsPropertiesFormat - } - if agbhs.Name != nil { - objectMap["name"] = agbhs.Name - } - if agbhs.ID != nil { - objectMap["id"] = agbhs.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayBackendHTTPSettings struct. -func (agbhs *ApplicationGatewayBackendHTTPSettings) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayBackendHTTPSettingsPropertiesFormat ApplicationGatewayBackendHTTPSettingsPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayBackendHTTPSettingsPropertiesFormat) - if err != nil { - return err - } - agbhs.ApplicationGatewayBackendHTTPSettingsPropertiesFormat = &applicationGatewayBackendHTTPSettingsPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agbhs.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agbhs.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agbhs.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agbhs.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayBackendHTTPSettingsPropertiesFormat properties of Backend address pool settings of an -// application gateway. -type ApplicationGatewayBackendHTTPSettingsPropertiesFormat struct { - // Port - The destination port on the backend. - Port *int32 `json:"port,omitempty"` - // Protocol - The protocol used to communicate with the backend. Possible values include: 'HTTP', 'HTTPS', 'TCP', 'TLS' - Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` - // CookieBasedAffinity - Cookie based affinity. Possible values include: 'Enabled', 'Disabled' - CookieBasedAffinity ApplicationGatewayCookieBasedAffinity `json:"cookieBasedAffinity,omitempty"` - // RequestTimeout - Request timeout in seconds. Application Gateway will fail the request if response is not received within RequestTimeout. Acceptable values are from 1 second to 86400 seconds. - RequestTimeout *int32 `json:"requestTimeout,omitempty"` - // Probe - Probe resource of an application gateway. - Probe *SubResource `json:"probe,omitempty"` - // AuthenticationCertificates - Array of references to application gateway authentication certificates. - AuthenticationCertificates *[]SubResource `json:"authenticationCertificates,omitempty"` - // TrustedRootCertificates - Array of references to application gateway trusted root certificates. - TrustedRootCertificates *[]SubResource `json:"trustedRootCertificates,omitempty"` - // ConnectionDraining - Connection draining of the backend http settings resource. - ConnectionDraining *ApplicationGatewayConnectionDraining `json:"connectionDraining,omitempty"` - // HostName - Host header to be sent to the backend servers. - HostName *string `json:"hostName,omitempty"` - // PickHostNameFromBackendAddress - Whether to pick host header should be picked from the host name of the backend server. Default value is false. - PickHostNameFromBackendAddress *bool `json:"pickHostNameFromBackendAddress,omitempty"` - // AffinityCookieName - Cookie name to use for the affinity cookie. - AffinityCookieName *string `json:"affinityCookieName,omitempty"` - // ProbeEnabled - Whether the probe is enabled. Default value is false. - ProbeEnabled *bool `json:"probeEnabled,omitempty"` - // Path - Path which should be used as a prefix for all HTTP requests. Null means no path will be prefixed. Default value is null. - Path *string `json:"path,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the backend HTTP settings resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayBackendHTTPSettingsPropertiesFormat. -func (agbhspf ApplicationGatewayBackendHTTPSettingsPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agbhspf.Port != nil { - objectMap["port"] = agbhspf.Port - } - if agbhspf.Protocol != "" { - objectMap["protocol"] = agbhspf.Protocol - } - if agbhspf.CookieBasedAffinity != "" { - objectMap["cookieBasedAffinity"] = agbhspf.CookieBasedAffinity - } - if agbhspf.RequestTimeout != nil { - objectMap["requestTimeout"] = agbhspf.RequestTimeout - } - if agbhspf.Probe != nil { - objectMap["probe"] = agbhspf.Probe - } - if agbhspf.AuthenticationCertificates != nil { - objectMap["authenticationCertificates"] = agbhspf.AuthenticationCertificates - } - if agbhspf.TrustedRootCertificates != nil { - objectMap["trustedRootCertificates"] = agbhspf.TrustedRootCertificates - } - if agbhspf.ConnectionDraining != nil { - objectMap["connectionDraining"] = agbhspf.ConnectionDraining - } - if agbhspf.HostName != nil { - objectMap["hostName"] = agbhspf.HostName - } - if agbhspf.PickHostNameFromBackendAddress != nil { - objectMap["pickHostNameFromBackendAddress"] = agbhspf.PickHostNameFromBackendAddress - } - if agbhspf.AffinityCookieName != nil { - objectMap["affinityCookieName"] = agbhspf.AffinityCookieName - } - if agbhspf.ProbeEnabled != nil { - objectMap["probeEnabled"] = agbhspf.ProbeEnabled - } - if agbhspf.Path != nil { - objectMap["path"] = agbhspf.Path - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayBackendSettings backend address pool settings of an application gateway. -type ApplicationGatewayBackendSettings struct { - // ApplicationGatewayBackendSettingsPropertiesFormat - Properties of the application gateway backend settings. - *ApplicationGatewayBackendSettingsPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the backend settings that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayBackendSettings. -func (agbs ApplicationGatewayBackendSettings) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agbs.ApplicationGatewayBackendSettingsPropertiesFormat != nil { - objectMap["properties"] = agbs.ApplicationGatewayBackendSettingsPropertiesFormat - } - if agbs.Name != nil { - objectMap["name"] = agbs.Name - } - if agbs.ID != nil { - objectMap["id"] = agbs.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayBackendSettings struct. -func (agbs *ApplicationGatewayBackendSettings) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayBackendSettingsPropertiesFormat ApplicationGatewayBackendSettingsPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayBackendSettingsPropertiesFormat) - if err != nil { - return err - } - agbs.ApplicationGatewayBackendSettingsPropertiesFormat = &applicationGatewayBackendSettingsPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agbs.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agbs.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agbs.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agbs.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayBackendSettingsPropertiesFormat properties of Backend address pool settings of an -// application gateway. -type ApplicationGatewayBackendSettingsPropertiesFormat struct { - // Port - The destination port on the backend. - Port *int32 `json:"port,omitempty"` - // Protocol - The protocol used to communicate with the backend. Possible values include: 'HTTP', 'HTTPS', 'TCP', 'TLS' - Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` - // Timeout - Connection timeout in seconds. Application Gateway will fail the request if response is not received within ConnectionTimeout. Acceptable values are from 1 second to 86400 seconds. - Timeout *int32 `json:"timeout,omitempty"` - // Probe - Probe resource of an application gateway. - Probe *SubResource `json:"probe,omitempty"` - // TrustedRootCertificates - Array of references to application gateway trusted root certificates. - TrustedRootCertificates *[]SubResource `json:"trustedRootCertificates,omitempty"` - // HostName - Server name indication to be sent to the backend servers for Tls protocol. - HostName *string `json:"hostName,omitempty"` - // PickHostNameFromBackendAddress - Whether to pick server name indication from the host name of the backend server for Tls protocol. Default value is false. - PickHostNameFromBackendAddress *bool `json:"pickHostNameFromBackendAddress,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the backend HTTP settings resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayBackendSettingsPropertiesFormat. -func (agbspf ApplicationGatewayBackendSettingsPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agbspf.Port != nil { - objectMap["port"] = agbspf.Port - } - if agbspf.Protocol != "" { - objectMap["protocol"] = agbspf.Protocol - } - if agbspf.Timeout != nil { - objectMap["timeout"] = agbspf.Timeout - } - if agbspf.Probe != nil { - objectMap["probe"] = agbspf.Probe - } - if agbspf.TrustedRootCertificates != nil { - objectMap["trustedRootCertificates"] = agbspf.TrustedRootCertificates - } - if agbspf.HostName != nil { - objectMap["hostName"] = agbspf.HostName - } - if agbspf.PickHostNameFromBackendAddress != nil { - objectMap["pickHostNameFromBackendAddress"] = agbspf.PickHostNameFromBackendAddress - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayClientAuthConfiguration application gateway client authentication configuration. -type ApplicationGatewayClientAuthConfiguration struct { - // VerifyClientCertIssuerDN - Verify client certificate issuer name on the application gateway. - VerifyClientCertIssuerDN *bool `json:"verifyClientCertIssuerDN,omitempty"` - // VerifyClientRevocation - Verify client certificate revocation status. Possible values include: 'None', 'OCSP' - VerifyClientRevocation ApplicationGatewayClientRevocationOptions `json:"verifyClientRevocation,omitempty"` -} - -// ApplicationGatewayConnectionDraining 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 - Whether connection draining is enabled or not. - Enabled *bool `json:"enabled,omitempty"` - // DrainTimeoutInSec - The number of seconds connection draining is active. Acceptable values are from 1 second to 3600 seconds. - DrainTimeoutInSec *int32 `json:"drainTimeoutInSec,omitempty"` -} - -// ApplicationGatewayCustomError customer error of an application gateway. -type ApplicationGatewayCustomError struct { - // StatusCode - Status code of the application gateway customer error. Possible values include: 'HTTPStatus403', 'HTTPStatus502' - StatusCode ApplicationGatewayCustomErrorStatusCode `json:"statusCode,omitempty"` - // CustomErrorPageURL - Error page URL of the application gateway customer error. - CustomErrorPageURL *string `json:"customErrorPageUrl,omitempty"` -} - -// ApplicationGatewayFirewallDisabledRuleGroup allows to disable rules within a rule group or an entire -// rule group. -type ApplicationGatewayFirewallDisabledRuleGroup struct { - // RuleGroupName - The name of the rule group that will be disabled. - RuleGroupName *string `json:"ruleGroupName,omitempty"` - // Rules - The list of rules that will be disabled. If null, all rules of the rule group will be disabled. - Rules *[]int32 `json:"rules,omitempty"` -} - -// ApplicationGatewayFirewallExclusion allow to exclude some variable satisfy the condition for the WAF -// check. -type ApplicationGatewayFirewallExclusion struct { - // MatchVariable - The variable to be excluded. - MatchVariable *string `json:"matchVariable,omitempty"` - // SelectorMatchOperator - When matchVariable is a collection, operate on the selector to specify which elements in the collection this exclusion applies to. - SelectorMatchOperator *string `json:"selectorMatchOperator,omitempty"` - // Selector - When matchVariable is a collection, operator used to specify which elements in the collection this exclusion applies to. - Selector *string `json:"selector,omitempty"` -} - -// ApplicationGatewayFirewallManifestRuleSet properties of the web application firewall rule set. -type ApplicationGatewayFirewallManifestRuleSet struct { - // RuleSetType - The type of the web application firewall rule set. - RuleSetType *string `json:"ruleSetType,omitempty"` - // RuleSetVersion - The version of the web application firewall rule set type. - RuleSetVersion *string `json:"ruleSetVersion,omitempty"` - // Status - The rule set status. Possible values include: 'Preview', 'GA', 'Supported', 'Deprecated' - Status ApplicationGatewayRuleSetStatusOptions `json:"status,omitempty"` - // Tiers - Tier of an application gateway that support the rule set. - Tiers *[]ApplicationGatewayTierTypes `json:"tiers,omitempty"` - // RuleGroups - The rule groups of the web application firewall rule set. - RuleGroups *[]ApplicationGatewayFirewallRuleGroup `json:"ruleGroups,omitempty"` -} - -// ApplicationGatewayFirewallRule a web application firewall rule. -type ApplicationGatewayFirewallRule struct { - // RuleID - The identifier of the web application firewall rule. - RuleID *int32 `json:"ruleId,omitempty"` - // RuleIDString - The string representation of the web application firewall rule identifier. - RuleIDString *string `json:"ruleIdString,omitempty"` - // State - The string representation of the web application firewall rule state. Possible values include: 'ApplicationGatewayWafRuleStateTypesEnabled', 'ApplicationGatewayWafRuleStateTypesDisabled' - State ApplicationGatewayWafRuleStateTypes `json:"state,omitempty"` - // Action - The string representation of the web application firewall rule action. Possible values include: 'ApplicationGatewayWafRuleActionTypesNone', 'ApplicationGatewayWafRuleActionTypesAnomalyScoring', 'ApplicationGatewayWafRuleActionTypesAllow', 'ApplicationGatewayWafRuleActionTypesBlock', 'ApplicationGatewayWafRuleActionTypesLog' - Action ApplicationGatewayWafRuleActionTypes `json:"action,omitempty"` - // Description - The description of the web application firewall rule. - Description *string `json:"description,omitempty"` -} - -// ApplicationGatewayFirewallRuleGroup a web application firewall rule group. -type ApplicationGatewayFirewallRuleGroup struct { - // RuleGroupName - The name of the web application firewall rule group. - RuleGroupName *string `json:"ruleGroupName,omitempty"` - // Description - The description of the web application firewall rule group. - Description *string `json:"description,omitempty"` - // Rules - The rules of the web application firewall rule group. - Rules *[]ApplicationGatewayFirewallRule `json:"rules,omitempty"` -} - -// ApplicationGatewayFirewallRuleSet a web application firewall rule set. -type ApplicationGatewayFirewallRuleSet struct { - // ApplicationGatewayFirewallRuleSetPropertiesFormat - Properties of the application gateway firewall rule set. - *ApplicationGatewayFirewallRuleSetPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayFirewallRuleSet. -func (agfrs ApplicationGatewayFirewallRuleSet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agfrs.ApplicationGatewayFirewallRuleSetPropertiesFormat != nil { - objectMap["properties"] = agfrs.ApplicationGatewayFirewallRuleSetPropertiesFormat - } - if agfrs.ID != nil { - objectMap["id"] = agfrs.ID - } - if agfrs.Location != nil { - objectMap["location"] = agfrs.Location - } - if agfrs.Tags != nil { - objectMap["tags"] = agfrs.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayFirewallRuleSet struct. -func (agfrs *ApplicationGatewayFirewallRuleSet) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayFirewallRuleSetPropertiesFormat ApplicationGatewayFirewallRuleSetPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayFirewallRuleSetPropertiesFormat) - if err != nil { - return err - } - agfrs.ApplicationGatewayFirewallRuleSetPropertiesFormat = &applicationGatewayFirewallRuleSetPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agfrs.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agfrs.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agfrs.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - agfrs.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - agfrs.Tags = tags - } - } - } - - return nil -} - -// ApplicationGatewayFirewallRuleSetPropertiesFormat properties of the web application firewall rule set. -type ApplicationGatewayFirewallRuleSetPropertiesFormat struct { - // ProvisioningState - READ-ONLY; The provisioning state of the web application firewall rule set. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // RuleSetType - The type of the web application firewall rule set. - RuleSetType *string `json:"ruleSetType,omitempty"` - // RuleSetVersion - The version of the web application firewall rule set type. - RuleSetVersion *string `json:"ruleSetVersion,omitempty"` - // RuleGroups - The rule groups of the web application firewall rule set. - RuleGroups *[]ApplicationGatewayFirewallRuleGroup `json:"ruleGroups,omitempty"` - // Tiers - Tier of an application gateway that support the rule set. - Tiers *[]ApplicationGatewayTierTypes `json:"tiers,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayFirewallRuleSetPropertiesFormat. -func (agfrspf ApplicationGatewayFirewallRuleSetPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agfrspf.RuleSetType != nil { - objectMap["ruleSetType"] = agfrspf.RuleSetType - } - if agfrspf.RuleSetVersion != nil { - objectMap["ruleSetVersion"] = agfrspf.RuleSetVersion - } - if agfrspf.RuleGroups != nil { - objectMap["ruleGroups"] = agfrspf.RuleGroups - } - if agfrspf.Tiers != nil { - objectMap["tiers"] = agfrspf.Tiers - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayFrontendIPConfiguration frontend IP configuration of an application gateway. -type ApplicationGatewayFrontendIPConfiguration struct { - // ApplicationGatewayFrontendIPConfigurationPropertiesFormat - Properties of the application gateway frontend IP configuration. - *ApplicationGatewayFrontendIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the frontend IP configuration that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayFrontendIPConfiguration. -func (agfic ApplicationGatewayFrontendIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agfic.ApplicationGatewayFrontendIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = agfic.ApplicationGatewayFrontendIPConfigurationPropertiesFormat - } - if agfic.Name != nil { - objectMap["name"] = agfic.Name - } - if agfic.ID != nil { - objectMap["id"] = agfic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayFrontendIPConfiguration struct. -func (agfic *ApplicationGatewayFrontendIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayFrontendIPConfigurationPropertiesFormat ApplicationGatewayFrontendIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayFrontendIPConfigurationPropertiesFormat) - if err != nil { - return err - } - agfic.ApplicationGatewayFrontendIPConfigurationPropertiesFormat = &applicationGatewayFrontendIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agfic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agfic.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agfic.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agfic.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayFrontendIPConfigurationPropertiesFormat properties of Frontend IP configuration of an -// application gateway. -type ApplicationGatewayFrontendIPConfigurationPropertiesFormat struct { - // PrivateIPAddress - PrivateIPAddress of the network interface IP Configuration. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // PrivateIPAllocationMethod - The private IP address allocation method. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` - // Subnet - Reference to the subnet resource. - Subnet *SubResource `json:"subnet,omitempty"` - // PublicIPAddress - Reference to the PublicIP resource. - PublicIPAddress *SubResource `json:"publicIPAddress,omitempty"` - // PrivateLinkConfiguration - Reference to the application gateway private link configuration. - PrivateLinkConfiguration *SubResource `json:"privateLinkConfiguration,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the frontend IP configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayFrontendIPConfigurationPropertiesFormat. -func (agficpf ApplicationGatewayFrontendIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agficpf.PrivateIPAddress != nil { - objectMap["privateIPAddress"] = agficpf.PrivateIPAddress - } - if agficpf.PrivateIPAllocationMethod != "" { - objectMap["privateIPAllocationMethod"] = agficpf.PrivateIPAllocationMethod - } - if agficpf.Subnet != nil { - objectMap["subnet"] = agficpf.Subnet - } - if agficpf.PublicIPAddress != nil { - objectMap["publicIPAddress"] = agficpf.PublicIPAddress - } - if agficpf.PrivateLinkConfiguration != nil { - objectMap["privateLinkConfiguration"] = agficpf.PrivateLinkConfiguration - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayFrontendPort frontend port of an application gateway. -type ApplicationGatewayFrontendPort struct { - // ApplicationGatewayFrontendPortPropertiesFormat - Properties of the application gateway frontend port. - *ApplicationGatewayFrontendPortPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the frontend port that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayFrontendPort. -func (agfp ApplicationGatewayFrontendPort) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agfp.ApplicationGatewayFrontendPortPropertiesFormat != nil { - objectMap["properties"] = agfp.ApplicationGatewayFrontendPortPropertiesFormat - } - if agfp.Name != nil { - objectMap["name"] = agfp.Name - } - if agfp.ID != nil { - objectMap["id"] = agfp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayFrontendPort struct. -func (agfp *ApplicationGatewayFrontendPort) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayFrontendPortPropertiesFormat ApplicationGatewayFrontendPortPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayFrontendPortPropertiesFormat) - if err != nil { - return err - } - agfp.ApplicationGatewayFrontendPortPropertiesFormat = &applicationGatewayFrontendPortPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agfp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agfp.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agfp.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agfp.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayFrontendPortPropertiesFormat properties of Frontend port of an application gateway. -type ApplicationGatewayFrontendPortPropertiesFormat struct { - // Port - Frontend port. - Port *int32 `json:"port,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the frontend port resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayFrontendPortPropertiesFormat. -func (agfppf ApplicationGatewayFrontendPortPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agfppf.Port != nil { - objectMap["port"] = agfppf.Port - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayGlobalConfiguration application Gateway global configuration. -type ApplicationGatewayGlobalConfiguration struct { - // EnableRequestBuffering - Enable request buffering. - EnableRequestBuffering *bool `json:"enableRequestBuffering,omitempty"` - // EnableResponseBuffering - Enable response buffering. - EnableResponseBuffering *bool `json:"enableResponseBuffering,omitempty"` -} - -// ApplicationGatewayHeaderConfiguration header configuration of the Actions set in Application Gateway. -type ApplicationGatewayHeaderConfiguration struct { - // HeaderName - Header name of the header configuration. - HeaderName *string `json:"headerName,omitempty"` - // HeaderValue - Header value of the header configuration. - HeaderValue *string `json:"headerValue,omitempty"` -} - -// ApplicationGatewayHTTPListener http listener of an application gateway. -type ApplicationGatewayHTTPListener struct { - // ApplicationGatewayHTTPListenerPropertiesFormat - Properties of the application gateway HTTP listener. - *ApplicationGatewayHTTPListenerPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the HTTP listener that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayHTTPListener. -func (aghl ApplicationGatewayHTTPListener) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if aghl.ApplicationGatewayHTTPListenerPropertiesFormat != nil { - objectMap["properties"] = aghl.ApplicationGatewayHTTPListenerPropertiesFormat - } - if aghl.Name != nil { - objectMap["name"] = aghl.Name - } - if aghl.ID != nil { - objectMap["id"] = aghl.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayHTTPListener struct. -func (aghl *ApplicationGatewayHTTPListener) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayHTTPListenerPropertiesFormat ApplicationGatewayHTTPListenerPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayHTTPListenerPropertiesFormat) - if err != nil { - return err - } - aghl.ApplicationGatewayHTTPListenerPropertiesFormat = &applicationGatewayHTTPListenerPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - aghl.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - aghl.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - aghl.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - aghl.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayHTTPListenerPropertiesFormat properties of HTTP listener of an application gateway. -type ApplicationGatewayHTTPListenerPropertiesFormat struct { - // FrontendIPConfiguration - Frontend IP configuration resource of an application gateway. - FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` - // FrontendPort - Frontend port resource of an application gateway. - FrontendPort *SubResource `json:"frontendPort,omitempty"` - // Protocol - Protocol of the HTTP listener. Possible values include: 'HTTP', 'HTTPS', 'TCP', 'TLS' - Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` - // HostName - Host name of HTTP listener. - HostName *string `json:"hostName,omitempty"` - // SslCertificate - SSL certificate resource of an application gateway. - SslCertificate *SubResource `json:"sslCertificate,omitempty"` - // SslProfile - SSL profile resource of the application gateway. - SslProfile *SubResource `json:"sslProfile,omitempty"` - // RequireServerNameIndication - Applicable only if protocol is https. Enables SNI for multi-hosting. - RequireServerNameIndication *bool `json:"requireServerNameIndication,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the HTTP listener resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // CustomErrorConfigurations - Custom error configurations of the HTTP listener. - CustomErrorConfigurations *[]ApplicationGatewayCustomError `json:"customErrorConfigurations,omitempty"` - // FirewallPolicy - Reference to the FirewallPolicy resource. - FirewallPolicy *SubResource `json:"firewallPolicy,omitempty"` - // HostNames - List of Host names for HTTP Listener that allows special wildcard characters as well. - HostNames *[]string `json:"hostNames,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayHTTPListenerPropertiesFormat. -func (aghlpf ApplicationGatewayHTTPListenerPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if aghlpf.FrontendIPConfiguration != nil { - objectMap["frontendIPConfiguration"] = aghlpf.FrontendIPConfiguration - } - if aghlpf.FrontendPort != nil { - objectMap["frontendPort"] = aghlpf.FrontendPort - } - if aghlpf.Protocol != "" { - objectMap["protocol"] = aghlpf.Protocol - } - if aghlpf.HostName != nil { - objectMap["hostName"] = aghlpf.HostName - } - if aghlpf.SslCertificate != nil { - objectMap["sslCertificate"] = aghlpf.SslCertificate - } - if aghlpf.SslProfile != nil { - objectMap["sslProfile"] = aghlpf.SslProfile - } - if aghlpf.RequireServerNameIndication != nil { - objectMap["requireServerNameIndication"] = aghlpf.RequireServerNameIndication - } - if aghlpf.CustomErrorConfigurations != nil { - objectMap["customErrorConfigurations"] = aghlpf.CustomErrorConfigurations - } - if aghlpf.FirewallPolicy != nil { - objectMap["firewallPolicy"] = aghlpf.FirewallPolicy - } - if aghlpf.HostNames != nil { - objectMap["hostNames"] = aghlpf.HostNames - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayIPConfiguration IP configuration of an application gateway. Currently 1 public and 1 -// private IP configuration is allowed. -type ApplicationGatewayIPConfiguration struct { - // ApplicationGatewayIPConfigurationPropertiesFormat - Properties of the application gateway IP configuration. - *ApplicationGatewayIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the IP configuration that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayIPConfiguration. -func (agic ApplicationGatewayIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agic.ApplicationGatewayIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = agic.ApplicationGatewayIPConfigurationPropertiesFormat - } - if agic.Name != nil { - objectMap["name"] = agic.Name - } - if agic.ID != nil { - objectMap["id"] = agic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayIPConfiguration struct. -func (agic *ApplicationGatewayIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayIPConfigurationPropertiesFormat ApplicationGatewayIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayIPConfigurationPropertiesFormat) - if err != nil { - return err - } - agic.ApplicationGatewayIPConfigurationPropertiesFormat = &applicationGatewayIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agic.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agic.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agic.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayIPConfigurationPropertiesFormat properties of IP configuration of an application -// gateway. -type ApplicationGatewayIPConfigurationPropertiesFormat struct { - // Subnet - Reference to the subnet resource. A subnet from where application gateway gets its private address. - Subnet *SubResource `json:"subnet,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the application gateway IP configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayIPConfigurationPropertiesFormat. -func (agicpf ApplicationGatewayIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agicpf.Subnet != nil { - objectMap["subnet"] = agicpf.Subnet - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayListener listener of an application gateway. -type ApplicationGatewayListener struct { - // ApplicationGatewayListenerPropertiesFormat - Properties of the application gateway listener. - *ApplicationGatewayListenerPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the listener that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayListener. -func (agl ApplicationGatewayListener) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agl.ApplicationGatewayListenerPropertiesFormat != nil { - objectMap["properties"] = agl.ApplicationGatewayListenerPropertiesFormat - } - if agl.Name != nil { - objectMap["name"] = agl.Name - } - if agl.ID != nil { - objectMap["id"] = agl.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayListener struct. -func (agl *ApplicationGatewayListener) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayListenerPropertiesFormat ApplicationGatewayListenerPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayListenerPropertiesFormat) - if err != nil { - return err - } - agl.ApplicationGatewayListenerPropertiesFormat = &applicationGatewayListenerPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agl.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agl.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agl.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agl.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayListenerPropertiesFormat properties of listener of an application gateway. -type ApplicationGatewayListenerPropertiesFormat struct { - // FrontendIPConfiguration - Frontend IP configuration resource of an application gateway. - FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` - // FrontendPort - Frontend port resource of an application gateway. - FrontendPort *SubResource `json:"frontendPort,omitempty"` - // Protocol - Protocol of the listener. Possible values include: 'HTTP', 'HTTPS', 'TCP', 'TLS' - Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` - // SslCertificate - SSL certificate resource of an application gateway. - SslCertificate *SubResource `json:"sslCertificate,omitempty"` - // SslProfile - SSL profile resource of the application gateway. - SslProfile *SubResource `json:"sslProfile,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the listener resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayListenerPropertiesFormat. -func (aglpf ApplicationGatewayListenerPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if aglpf.FrontendIPConfiguration != nil { - objectMap["frontendIPConfiguration"] = aglpf.FrontendIPConfiguration - } - if aglpf.FrontendPort != nil { - objectMap["frontendPort"] = aglpf.FrontendPort - } - if aglpf.Protocol != "" { - objectMap["protocol"] = aglpf.Protocol - } - if aglpf.SslCertificate != nil { - objectMap["sslCertificate"] = aglpf.SslCertificate - } - if aglpf.SslProfile != nil { - objectMap["sslProfile"] = aglpf.SslProfile - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayListResult response for ListApplicationGateways API service call. -type ApplicationGatewayListResult struct { - autorest.Response `json:"-"` - // Value - List of an application gateways in a resource group. - Value *[]ApplicationGateway `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ApplicationGatewayListResultIterator provides access to a complete listing of ApplicationGateway values. -type ApplicationGatewayListResultIterator struct { - i int - page ApplicationGatewayListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ApplicationGatewayListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ApplicationGatewayListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ApplicationGatewayListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ApplicationGatewayListResultIterator) Response() ApplicationGatewayListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ApplicationGatewayListResultIterator) Value() ApplicationGateway { - if !iter.page.NotDone() { - return ApplicationGateway{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ApplicationGatewayListResultIterator type. -func NewApplicationGatewayListResultIterator(page ApplicationGatewayListResultPage) ApplicationGatewayListResultIterator { - return ApplicationGatewayListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (aglr ApplicationGatewayListResult) IsEmpty() bool { - return aglr.Value == nil || len(*aglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (aglr ApplicationGatewayListResult) hasNextLink() bool { - return aglr.NextLink != nil && len(*aglr.NextLink) != 0 -} - -// applicationGatewayListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (aglr ApplicationGatewayListResult) applicationGatewayListResultPreparer(ctx context.Context) (*http.Request, error) { - if !aglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(aglr.NextLink))) -} - -// ApplicationGatewayListResultPage contains a page of ApplicationGateway values. -type ApplicationGatewayListResultPage struct { - fn func(context.Context, ApplicationGatewayListResult) (ApplicationGatewayListResult, error) - aglr ApplicationGatewayListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ApplicationGatewayListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.aglr) - if err != nil { - return err - } - page.aglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ApplicationGatewayListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ApplicationGatewayListResultPage) NotDone() bool { - return !page.aglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ApplicationGatewayListResultPage) Response() ApplicationGatewayListResult { - return page.aglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ApplicationGatewayListResultPage) Values() []ApplicationGateway { - if page.aglr.IsEmpty() { - return nil - } - return *page.aglr.Value -} - -// Creates a new instance of the ApplicationGatewayListResultPage type. -func NewApplicationGatewayListResultPage(cur ApplicationGatewayListResult, getNextPage func(context.Context, ApplicationGatewayListResult) (ApplicationGatewayListResult, error)) ApplicationGatewayListResultPage { - return ApplicationGatewayListResultPage{ - fn: getNextPage, - aglr: cur, - } -} - -// ApplicationGatewayLoadDistributionPolicy load Distribution Policy of an application gateway. -type ApplicationGatewayLoadDistributionPolicy struct { - // ApplicationGatewayLoadDistributionPolicyPropertiesFormat - Properties of the application gateway load distribution policy. - *ApplicationGatewayLoadDistributionPolicyPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the load distribution policy that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayLoadDistributionPolicy. -func (agldp ApplicationGatewayLoadDistributionPolicy) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agldp.ApplicationGatewayLoadDistributionPolicyPropertiesFormat != nil { - objectMap["properties"] = agldp.ApplicationGatewayLoadDistributionPolicyPropertiesFormat - } - if agldp.Name != nil { - objectMap["name"] = agldp.Name - } - if agldp.ID != nil { - objectMap["id"] = agldp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayLoadDistributionPolicy struct. -func (agldp *ApplicationGatewayLoadDistributionPolicy) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayLoadDistributionPolicyPropertiesFormat ApplicationGatewayLoadDistributionPolicyPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayLoadDistributionPolicyPropertiesFormat) - if err != nil { - return err - } - agldp.ApplicationGatewayLoadDistributionPolicyPropertiesFormat = &applicationGatewayLoadDistributionPolicyPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agldp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agldp.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agldp.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agldp.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayLoadDistributionPolicyPropertiesFormat properties of Load Distribution Policy of an -// application gateway. -type ApplicationGatewayLoadDistributionPolicyPropertiesFormat struct { - // LoadDistributionTargets - Load Distribution Targets resource of an application gateway. - LoadDistributionTargets *[]ApplicationGatewayLoadDistributionTarget `json:"loadDistributionTargets,omitempty"` - // LoadDistributionAlgorithm - Load Distribution Targets resource of an application gateway. Possible values include: 'RoundRobin', 'LeastConnections', 'IPHash' - LoadDistributionAlgorithm ApplicationGatewayLoadDistributionAlgorithm `json:"loadDistributionAlgorithm,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the Load Distribution Policy resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayLoadDistributionPolicyPropertiesFormat. -func (agldppf ApplicationGatewayLoadDistributionPolicyPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agldppf.LoadDistributionTargets != nil { - objectMap["loadDistributionTargets"] = agldppf.LoadDistributionTargets - } - if agldppf.LoadDistributionAlgorithm != "" { - objectMap["loadDistributionAlgorithm"] = agldppf.LoadDistributionAlgorithm - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayLoadDistributionTarget load Distribution Target of an application gateway. -type ApplicationGatewayLoadDistributionTarget struct { - // ApplicationGatewayLoadDistributionTargetPropertiesFormat - Properties of the application gateway load distribution target. - *ApplicationGatewayLoadDistributionTargetPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the load distribution policy that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayLoadDistributionTarget. -func (agldt ApplicationGatewayLoadDistributionTarget) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agldt.ApplicationGatewayLoadDistributionTargetPropertiesFormat != nil { - objectMap["properties"] = agldt.ApplicationGatewayLoadDistributionTargetPropertiesFormat - } - if agldt.Name != nil { - objectMap["name"] = agldt.Name - } - if agldt.ID != nil { - objectMap["id"] = agldt.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayLoadDistributionTarget struct. -func (agldt *ApplicationGatewayLoadDistributionTarget) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayLoadDistributionTargetPropertiesFormat ApplicationGatewayLoadDistributionTargetPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayLoadDistributionTargetPropertiesFormat) - if err != nil { - return err - } - agldt.ApplicationGatewayLoadDistributionTargetPropertiesFormat = &applicationGatewayLoadDistributionTargetPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agldt.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agldt.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agldt.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agldt.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayLoadDistributionTargetPropertiesFormat ... -type ApplicationGatewayLoadDistributionTargetPropertiesFormat struct { - // WeightPerServer - Weight per server. Range between 1 and 100. - WeightPerServer *int32 `json:"weightPerServer,omitempty"` - // BackendAddressPool - Backend address pool resource of the application gateway. - BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` -} - -// ApplicationGatewayOnDemandProbe details of on demand test probe request. -type ApplicationGatewayOnDemandProbe struct { - // Protocol - The protocol used for the probe. Possible values include: 'HTTP', 'HTTPS', 'TCP', 'TLS' - Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` - // Host - Host name to send the probe to. - Host *string `json:"host,omitempty"` - // Path - Relative path of probe. Valid path starts from '/'. Probe is sent to ://:. - Path *string `json:"path,omitempty"` - // Timeout - The probe timeout in seconds. Probe marked as failed if valid response is not received with this timeout period. Acceptable values are from 1 second to 86400 seconds. - Timeout *int32 `json:"timeout,omitempty"` - // PickHostNameFromBackendHTTPSettings - Whether the host header should be picked from the backend http settings. Default value is false. - PickHostNameFromBackendHTTPSettings *bool `json:"pickHostNameFromBackendHttpSettings,omitempty"` - // Match - Criterion for classifying a healthy probe response. - Match *ApplicationGatewayProbeHealthResponseMatch `json:"match,omitempty"` - // BackendAddressPool - Reference to backend pool of application gateway to which probe request will be sent. - BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` - // BackendHTTPSettings - Reference to backend http setting of application gateway to be used for test probe. - BackendHTTPSettings *SubResource `json:"backendHttpSettings,omitempty"` -} - -// ApplicationGatewayPathRule path rule of URL path map of an application gateway. -type ApplicationGatewayPathRule struct { - // ApplicationGatewayPathRulePropertiesFormat - Properties of the application gateway path rule. - *ApplicationGatewayPathRulePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the path rule that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayPathRule. -func (agpr ApplicationGatewayPathRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agpr.ApplicationGatewayPathRulePropertiesFormat != nil { - objectMap["properties"] = agpr.ApplicationGatewayPathRulePropertiesFormat - } - if agpr.Name != nil { - objectMap["name"] = agpr.Name - } - if agpr.ID != nil { - objectMap["id"] = agpr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayPathRule struct. -func (agpr *ApplicationGatewayPathRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayPathRulePropertiesFormat ApplicationGatewayPathRulePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayPathRulePropertiesFormat) - if err != nil { - return err - } - agpr.ApplicationGatewayPathRulePropertiesFormat = &applicationGatewayPathRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agpr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agpr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agpr.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agpr.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayPathRulePropertiesFormat properties of path rule of an application gateway. -type ApplicationGatewayPathRulePropertiesFormat struct { - // Paths - Path rules of URL path map. - Paths *[]string `json:"paths,omitempty"` - // BackendAddressPool - Backend address pool resource of URL path map path rule. - BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` - // BackendHTTPSettings - Backend http settings resource of URL path map path rule. - BackendHTTPSettings *SubResource `json:"backendHttpSettings,omitempty"` - // RedirectConfiguration - Redirect configuration resource of URL path map path rule. - RedirectConfiguration *SubResource `json:"redirectConfiguration,omitempty"` - // RewriteRuleSet - Rewrite rule set resource of URL path map path rule. - RewriteRuleSet *SubResource `json:"rewriteRuleSet,omitempty"` - // LoadDistributionPolicy - Load Distribution Policy resource of URL path map path rule. - LoadDistributionPolicy *SubResource `json:"loadDistributionPolicy,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the path rule resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // FirewallPolicy - Reference to the FirewallPolicy resource. - FirewallPolicy *SubResource `json:"firewallPolicy,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayPathRulePropertiesFormat. -func (agprpf ApplicationGatewayPathRulePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agprpf.Paths != nil { - objectMap["paths"] = agprpf.Paths - } - if agprpf.BackendAddressPool != nil { - objectMap["backendAddressPool"] = agprpf.BackendAddressPool - } - if agprpf.BackendHTTPSettings != nil { - objectMap["backendHttpSettings"] = agprpf.BackendHTTPSettings - } - if agprpf.RedirectConfiguration != nil { - objectMap["redirectConfiguration"] = agprpf.RedirectConfiguration - } - if agprpf.RewriteRuleSet != nil { - objectMap["rewriteRuleSet"] = agprpf.RewriteRuleSet - } - if agprpf.LoadDistributionPolicy != nil { - objectMap["loadDistributionPolicy"] = agprpf.LoadDistributionPolicy - } - if agprpf.FirewallPolicy != nil { - objectMap["firewallPolicy"] = agprpf.FirewallPolicy - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayPrivateEndpointConnection private Endpoint connection on an application gateway. -type ApplicationGatewayPrivateEndpointConnection struct { - autorest.Response `json:"-"` - // ApplicationGatewayPrivateEndpointConnectionProperties - Properties of the application gateway private endpoint connection. - *ApplicationGatewayPrivateEndpointConnectionProperties `json:"properties,omitempty"` - // Name - Name of the private endpoint connection on an application gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayPrivateEndpointConnection. -func (agpec ApplicationGatewayPrivateEndpointConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agpec.ApplicationGatewayPrivateEndpointConnectionProperties != nil { - objectMap["properties"] = agpec.ApplicationGatewayPrivateEndpointConnectionProperties - } - if agpec.Name != nil { - objectMap["name"] = agpec.Name - } - if agpec.ID != nil { - objectMap["id"] = agpec.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayPrivateEndpointConnection struct. -func (agpec *ApplicationGatewayPrivateEndpointConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayPrivateEndpointConnectionProperties ApplicationGatewayPrivateEndpointConnectionProperties - err = json.Unmarshal(*v, &applicationGatewayPrivateEndpointConnectionProperties) - if err != nil { - return err - } - agpec.ApplicationGatewayPrivateEndpointConnectionProperties = &applicationGatewayPrivateEndpointConnectionProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agpec.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agpec.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agpec.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agpec.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayPrivateEndpointConnectionListResult response for -// ListApplicationGatewayPrivateEndpointConnection API service call. Gets all private endpoint connections -// for an application gateway. -type ApplicationGatewayPrivateEndpointConnectionListResult struct { - autorest.Response `json:"-"` - // Value - List of private endpoint connections on an application gateway. - Value *[]ApplicationGatewayPrivateEndpointConnection `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ApplicationGatewayPrivateEndpointConnectionListResultIterator provides access to a complete listing of -// ApplicationGatewayPrivateEndpointConnection values. -type ApplicationGatewayPrivateEndpointConnectionListResultIterator struct { - i int - page ApplicationGatewayPrivateEndpointConnectionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ApplicationGatewayPrivateEndpointConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayPrivateEndpointConnectionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ApplicationGatewayPrivateEndpointConnectionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ApplicationGatewayPrivateEndpointConnectionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ApplicationGatewayPrivateEndpointConnectionListResultIterator) Response() ApplicationGatewayPrivateEndpointConnectionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ApplicationGatewayPrivateEndpointConnectionListResultIterator) Value() ApplicationGatewayPrivateEndpointConnection { - if !iter.page.NotDone() { - return ApplicationGatewayPrivateEndpointConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ApplicationGatewayPrivateEndpointConnectionListResultIterator type. -func NewApplicationGatewayPrivateEndpointConnectionListResultIterator(page ApplicationGatewayPrivateEndpointConnectionListResultPage) ApplicationGatewayPrivateEndpointConnectionListResultIterator { - return ApplicationGatewayPrivateEndpointConnectionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (agpeclr ApplicationGatewayPrivateEndpointConnectionListResult) IsEmpty() bool { - return agpeclr.Value == nil || len(*agpeclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (agpeclr ApplicationGatewayPrivateEndpointConnectionListResult) hasNextLink() bool { - return agpeclr.NextLink != nil && len(*agpeclr.NextLink) != 0 -} - -// applicationGatewayPrivateEndpointConnectionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (agpeclr ApplicationGatewayPrivateEndpointConnectionListResult) applicationGatewayPrivateEndpointConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !agpeclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(agpeclr.NextLink))) -} - -// ApplicationGatewayPrivateEndpointConnectionListResultPage contains a page of -// ApplicationGatewayPrivateEndpointConnection values. -type ApplicationGatewayPrivateEndpointConnectionListResultPage struct { - fn func(context.Context, ApplicationGatewayPrivateEndpointConnectionListResult) (ApplicationGatewayPrivateEndpointConnectionListResult, error) - agpeclr ApplicationGatewayPrivateEndpointConnectionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ApplicationGatewayPrivateEndpointConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayPrivateEndpointConnectionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.agpeclr) - if err != nil { - return err - } - page.agpeclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ApplicationGatewayPrivateEndpointConnectionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ApplicationGatewayPrivateEndpointConnectionListResultPage) NotDone() bool { - return !page.agpeclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ApplicationGatewayPrivateEndpointConnectionListResultPage) Response() ApplicationGatewayPrivateEndpointConnectionListResult { - return page.agpeclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ApplicationGatewayPrivateEndpointConnectionListResultPage) Values() []ApplicationGatewayPrivateEndpointConnection { - if page.agpeclr.IsEmpty() { - return nil - } - return *page.agpeclr.Value -} - -// Creates a new instance of the ApplicationGatewayPrivateEndpointConnectionListResultPage type. -func NewApplicationGatewayPrivateEndpointConnectionListResultPage(cur ApplicationGatewayPrivateEndpointConnectionListResult, getNextPage func(context.Context, ApplicationGatewayPrivateEndpointConnectionListResult) (ApplicationGatewayPrivateEndpointConnectionListResult, error)) ApplicationGatewayPrivateEndpointConnectionListResultPage { - return ApplicationGatewayPrivateEndpointConnectionListResultPage{ - fn: getNextPage, - agpeclr: cur, - } -} - -// ApplicationGatewayPrivateEndpointConnectionProperties properties of Private Link Resource of an -// application gateway. -type ApplicationGatewayPrivateEndpointConnectionProperties struct { - // PrivateEndpoint - READ-ONLY; The resource of private end point. - PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` - // PrivateLinkServiceConnectionState - A collection of information about the state of the connection between service consumer and provider. - PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState `json:"privateLinkServiceConnectionState,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the application gateway private endpoint connection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // LinkIdentifier - READ-ONLY; The consumer link id. - LinkIdentifier *string `json:"linkIdentifier,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayPrivateEndpointConnectionProperties. -func (agpecp ApplicationGatewayPrivateEndpointConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agpecp.PrivateLinkServiceConnectionState != nil { - objectMap["privateLinkServiceConnectionState"] = agpecp.PrivateLinkServiceConnectionState - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayPrivateEndpointConnectionsDeleteFuture an abstraction for monitoring and retrieving -// the results of a long-running operation. -type ApplicationGatewayPrivateEndpointConnectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewayPrivateEndpointConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewayPrivateEndpointConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewayPrivateEndpointConnectionsDeleteFuture.Result. -func (future *ApplicationGatewayPrivateEndpointConnectionsDeleteFuture) result(client ApplicationGatewayPrivateEndpointConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewayPrivateEndpointConnectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ApplicationGatewayPrivateEndpointConnectionsUpdateFuture an abstraction for monitoring and retrieving -// the results of a long-running operation. -type ApplicationGatewayPrivateEndpointConnectionsUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewayPrivateEndpointConnectionsClient) (ApplicationGatewayPrivateEndpointConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewayPrivateEndpointConnectionsUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewayPrivateEndpointConnectionsUpdateFuture.Result. -func (future *ApplicationGatewayPrivateEndpointConnectionsUpdateFuture) result(client ApplicationGatewayPrivateEndpointConnectionsClient) (agpec ApplicationGatewayPrivateEndpointConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - agpec.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewayPrivateEndpointConnectionsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if agpec.Response.Response, err = future.GetResult(sender); err == nil && agpec.Response.Response.StatusCode != http.StatusNoContent { - agpec, err = client.UpdateResponder(agpec.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewayPrivateEndpointConnectionsUpdateFuture", "Result", agpec.Response.Response, "Failure responding to request") - } - } - return -} - -// ApplicationGatewayPrivateLinkConfiguration private Link Configuration on an application gateway. -type ApplicationGatewayPrivateLinkConfiguration struct { - // ApplicationGatewayPrivateLinkConfigurationProperties - Properties of the application gateway private link configuration. - *ApplicationGatewayPrivateLinkConfigurationProperties `json:"properties,omitempty"` - // Name - Name of the private link configuration that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayPrivateLinkConfiguration. -func (agplc ApplicationGatewayPrivateLinkConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agplc.ApplicationGatewayPrivateLinkConfigurationProperties != nil { - objectMap["properties"] = agplc.ApplicationGatewayPrivateLinkConfigurationProperties - } - if agplc.Name != nil { - objectMap["name"] = agplc.Name - } - if agplc.ID != nil { - objectMap["id"] = agplc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayPrivateLinkConfiguration struct. -func (agplc *ApplicationGatewayPrivateLinkConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayPrivateLinkConfigurationProperties ApplicationGatewayPrivateLinkConfigurationProperties - err = json.Unmarshal(*v, &applicationGatewayPrivateLinkConfigurationProperties) - if err != nil { - return err - } - agplc.ApplicationGatewayPrivateLinkConfigurationProperties = &applicationGatewayPrivateLinkConfigurationProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agplc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agplc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agplc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agplc.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayPrivateLinkConfigurationProperties properties of private link configuration on an -// application gateway. -type ApplicationGatewayPrivateLinkConfigurationProperties struct { - // IPConfigurations - An array of application gateway private link ip configurations. - IPConfigurations *[]ApplicationGatewayPrivateLinkIPConfiguration `json:"ipConfigurations,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the application gateway private link configuration. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayPrivateLinkConfigurationProperties. -func (agplcp ApplicationGatewayPrivateLinkConfigurationProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agplcp.IPConfigurations != nil { - objectMap["ipConfigurations"] = agplcp.IPConfigurations - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayPrivateLinkIPConfiguration the application gateway private link ip configuration. -type ApplicationGatewayPrivateLinkIPConfiguration struct { - // ApplicationGatewayPrivateLinkIPConfigurationProperties - Properties of an application gateway private link ip configuration. - *ApplicationGatewayPrivateLinkIPConfigurationProperties `json:"properties,omitempty"` - // Name - The name of application gateway private link ip configuration. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; The resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayPrivateLinkIPConfiguration. -func (agplic ApplicationGatewayPrivateLinkIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agplic.ApplicationGatewayPrivateLinkIPConfigurationProperties != nil { - objectMap["properties"] = agplic.ApplicationGatewayPrivateLinkIPConfigurationProperties - } - if agplic.Name != nil { - objectMap["name"] = agplic.Name - } - if agplic.ID != nil { - objectMap["id"] = agplic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayPrivateLinkIPConfiguration struct. -func (agplic *ApplicationGatewayPrivateLinkIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayPrivateLinkIPConfigurationProperties ApplicationGatewayPrivateLinkIPConfigurationProperties - err = json.Unmarshal(*v, &applicationGatewayPrivateLinkIPConfigurationProperties) - if err != nil { - return err - } - agplic.ApplicationGatewayPrivateLinkIPConfigurationProperties = &applicationGatewayPrivateLinkIPConfigurationProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agplic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agplic.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agplic.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agplic.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayPrivateLinkIPConfigurationProperties properties of an application gateway private link -// IP configuration. -type ApplicationGatewayPrivateLinkIPConfigurationProperties struct { - // PrivateIPAddress - The private IP address of the IP configuration. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // PrivateIPAllocationMethod - The private IP address allocation method. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` - // Subnet - Reference to the subnet resource. - Subnet *SubResource `json:"subnet,omitempty"` - // Primary - Whether the ip configuration is primary or not. - Primary *bool `json:"primary,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the application gateway private link IP configuration. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayPrivateLinkIPConfigurationProperties. -func (agplicp ApplicationGatewayPrivateLinkIPConfigurationProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agplicp.PrivateIPAddress != nil { - objectMap["privateIPAddress"] = agplicp.PrivateIPAddress - } - if agplicp.PrivateIPAllocationMethod != "" { - objectMap["privateIPAllocationMethod"] = agplicp.PrivateIPAllocationMethod - } - if agplicp.Subnet != nil { - objectMap["subnet"] = agplicp.Subnet - } - if agplicp.Primary != nil { - objectMap["primary"] = agplicp.Primary - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayPrivateLinkResource privateLink Resource of an application gateway. -type ApplicationGatewayPrivateLinkResource struct { - // ApplicationGatewayPrivateLinkResourceProperties - Properties of the application gateway private link resource. - *ApplicationGatewayPrivateLinkResourceProperties `json:"properties,omitempty"` - // Name - Name of the private link resource that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayPrivateLinkResource. -func (agplr ApplicationGatewayPrivateLinkResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agplr.ApplicationGatewayPrivateLinkResourceProperties != nil { - objectMap["properties"] = agplr.ApplicationGatewayPrivateLinkResourceProperties - } - if agplr.Name != nil { - objectMap["name"] = agplr.Name - } - if agplr.ID != nil { - objectMap["id"] = agplr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayPrivateLinkResource struct. -func (agplr *ApplicationGatewayPrivateLinkResource) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayPrivateLinkResourceProperties ApplicationGatewayPrivateLinkResourceProperties - err = json.Unmarshal(*v, &applicationGatewayPrivateLinkResourceProperties) - if err != nil { - return err - } - agplr.ApplicationGatewayPrivateLinkResourceProperties = &applicationGatewayPrivateLinkResourceProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agplr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agplr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agplr.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agplr.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayPrivateLinkResourceListResult response for ListApplicationGatewayPrivateLinkResources -// API service call. Gets all private link resources for an application gateway. -type ApplicationGatewayPrivateLinkResourceListResult struct { - autorest.Response `json:"-"` - // Value - List of private link resources of an application gateway. - Value *[]ApplicationGatewayPrivateLinkResource `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ApplicationGatewayPrivateLinkResourceListResultIterator provides access to a complete listing of -// ApplicationGatewayPrivateLinkResource values. -type ApplicationGatewayPrivateLinkResourceListResultIterator struct { - i int - page ApplicationGatewayPrivateLinkResourceListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ApplicationGatewayPrivateLinkResourceListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayPrivateLinkResourceListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ApplicationGatewayPrivateLinkResourceListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ApplicationGatewayPrivateLinkResourceListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ApplicationGatewayPrivateLinkResourceListResultIterator) Response() ApplicationGatewayPrivateLinkResourceListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ApplicationGatewayPrivateLinkResourceListResultIterator) Value() ApplicationGatewayPrivateLinkResource { - if !iter.page.NotDone() { - return ApplicationGatewayPrivateLinkResource{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ApplicationGatewayPrivateLinkResourceListResultIterator type. -func NewApplicationGatewayPrivateLinkResourceListResultIterator(page ApplicationGatewayPrivateLinkResourceListResultPage) ApplicationGatewayPrivateLinkResourceListResultIterator { - return ApplicationGatewayPrivateLinkResourceListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (agplrlr ApplicationGatewayPrivateLinkResourceListResult) IsEmpty() bool { - return agplrlr.Value == nil || len(*agplrlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (agplrlr ApplicationGatewayPrivateLinkResourceListResult) hasNextLink() bool { - return agplrlr.NextLink != nil && len(*agplrlr.NextLink) != 0 -} - -// applicationGatewayPrivateLinkResourceListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (agplrlr ApplicationGatewayPrivateLinkResourceListResult) applicationGatewayPrivateLinkResourceListResultPreparer(ctx context.Context) (*http.Request, error) { - if !agplrlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(agplrlr.NextLink))) -} - -// ApplicationGatewayPrivateLinkResourceListResultPage contains a page of -// ApplicationGatewayPrivateLinkResource values. -type ApplicationGatewayPrivateLinkResourceListResultPage struct { - fn func(context.Context, ApplicationGatewayPrivateLinkResourceListResult) (ApplicationGatewayPrivateLinkResourceListResult, error) - agplrlr ApplicationGatewayPrivateLinkResourceListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ApplicationGatewayPrivateLinkResourceListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayPrivateLinkResourceListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.agplrlr) - if err != nil { - return err - } - page.agplrlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ApplicationGatewayPrivateLinkResourceListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ApplicationGatewayPrivateLinkResourceListResultPage) NotDone() bool { - return !page.agplrlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ApplicationGatewayPrivateLinkResourceListResultPage) Response() ApplicationGatewayPrivateLinkResourceListResult { - return page.agplrlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ApplicationGatewayPrivateLinkResourceListResultPage) Values() []ApplicationGatewayPrivateLinkResource { - if page.agplrlr.IsEmpty() { - return nil - } - return *page.agplrlr.Value -} - -// Creates a new instance of the ApplicationGatewayPrivateLinkResourceListResultPage type. -func NewApplicationGatewayPrivateLinkResourceListResultPage(cur ApplicationGatewayPrivateLinkResourceListResult, getNextPage func(context.Context, ApplicationGatewayPrivateLinkResourceListResult) (ApplicationGatewayPrivateLinkResourceListResult, error)) ApplicationGatewayPrivateLinkResourceListResultPage { - return ApplicationGatewayPrivateLinkResourceListResultPage{ - fn: getNextPage, - agplrlr: cur, - } -} - -// ApplicationGatewayPrivateLinkResourceProperties properties of a private link resource. -type ApplicationGatewayPrivateLinkResourceProperties struct { - // GroupID - READ-ONLY; Group identifier of private link resource. - GroupID *string `json:"groupId,omitempty"` - // RequiredMembers - READ-ONLY; Required member names of private link resource. - RequiredMembers *[]string `json:"requiredMembers,omitempty"` - // RequiredZoneNames - Required DNS zone names of the the private link resource. - RequiredZoneNames *[]string `json:"requiredZoneNames,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayPrivateLinkResourceProperties. -func (agplrp ApplicationGatewayPrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agplrp.RequiredZoneNames != nil { - objectMap["requiredZoneNames"] = agplrp.RequiredZoneNames - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayProbe probe of the application gateway. -type ApplicationGatewayProbe struct { - // ApplicationGatewayProbePropertiesFormat - Properties of the application gateway probe. - *ApplicationGatewayProbePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the probe that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayProbe. -func (agp ApplicationGatewayProbe) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agp.ApplicationGatewayProbePropertiesFormat != nil { - objectMap["properties"] = agp.ApplicationGatewayProbePropertiesFormat - } - if agp.Name != nil { - objectMap["name"] = agp.Name - } - if agp.ID != nil { - objectMap["id"] = agp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayProbe struct. -func (agp *ApplicationGatewayProbe) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayProbePropertiesFormat ApplicationGatewayProbePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayProbePropertiesFormat) - if err != nil { - return err - } - agp.ApplicationGatewayProbePropertiesFormat = &applicationGatewayProbePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agp.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agp.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agp.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayProbeHealthResponseMatch application gateway probe health response match. -type ApplicationGatewayProbeHealthResponseMatch struct { - // Body - Body that must be contained in the health response. Default value is empty. - Body *string `json:"body,omitempty"` - // StatusCodes - Allowed ranges of healthy status codes. Default range of healthy status codes is 200-399. - StatusCodes *[]string `json:"statusCodes,omitempty"` -} - -// ApplicationGatewayProbePropertiesFormat properties of probe of an application gateway. -type ApplicationGatewayProbePropertiesFormat struct { - // Protocol - The protocol used for the probe. Possible values include: 'HTTP', 'HTTPS', 'TCP', 'TLS' - Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` - // Host - Host name to send the probe to. - Host *string `json:"host,omitempty"` - // Path - Relative path of probe. Valid path starts from '/'. Probe is sent to ://:. - Path *string `json:"path,omitempty"` - // Interval - The probing interval in seconds. This is the time interval between two consecutive probes. Acceptable values are from 1 second to 86400 seconds. - Interval *int32 `json:"interval,omitempty"` - // Timeout - The probe timeout in seconds. Probe marked as failed if valid response is not received with this timeout period. Acceptable values are from 1 second to 86400 seconds. - Timeout *int32 `json:"timeout,omitempty"` - // UnhealthyThreshold - The probe retry count. Backend server is marked down after consecutive probe failure count reaches UnhealthyThreshold. Acceptable values are from 1 second to 20. - UnhealthyThreshold *int32 `json:"unhealthyThreshold,omitempty"` - // PickHostNameFromBackendHTTPSettings - Whether the host header should be picked from the backend http settings. Default value is false. - PickHostNameFromBackendHTTPSettings *bool `json:"pickHostNameFromBackendHttpSettings,omitempty"` - // PickHostNameFromBackendSettings - Whether the server name indication should be picked from the backend settings for Tls protocol. Default value is false. - PickHostNameFromBackendSettings *bool `json:"pickHostNameFromBackendSettings,omitempty"` - // MinServers - Minimum number of servers that are always marked healthy. Default value is 0. - MinServers *int32 `json:"minServers,omitempty"` - // Match - Criterion for classifying a healthy probe response. - Match *ApplicationGatewayProbeHealthResponseMatch `json:"match,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the probe resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // Port - Custom port which will be used for probing the backend servers. The valid value ranges from 1 to 65535. In case not set, port from http settings will be used. This property is valid for Standard_v2 and WAF_v2 only. - Port *int32 `json:"port,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayProbePropertiesFormat. -func (agppf ApplicationGatewayProbePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agppf.Protocol != "" { - objectMap["protocol"] = agppf.Protocol - } - if agppf.Host != nil { - objectMap["host"] = agppf.Host - } - if agppf.Path != nil { - objectMap["path"] = agppf.Path - } - if agppf.Interval != nil { - objectMap["interval"] = agppf.Interval - } - if agppf.Timeout != nil { - objectMap["timeout"] = agppf.Timeout - } - if agppf.UnhealthyThreshold != nil { - objectMap["unhealthyThreshold"] = agppf.UnhealthyThreshold - } - if agppf.PickHostNameFromBackendHTTPSettings != nil { - objectMap["pickHostNameFromBackendHttpSettings"] = agppf.PickHostNameFromBackendHTTPSettings - } - if agppf.PickHostNameFromBackendSettings != nil { - objectMap["pickHostNameFromBackendSettings"] = agppf.PickHostNameFromBackendSettings - } - if agppf.MinServers != nil { - objectMap["minServers"] = agppf.MinServers - } - if agppf.Match != nil { - objectMap["match"] = agppf.Match - } - if agppf.Port != nil { - objectMap["port"] = agppf.Port - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayPropertiesFormat properties of the application gateway. -type ApplicationGatewayPropertiesFormat struct { - // Sku - SKU of the application gateway resource. - Sku *ApplicationGatewaySku `json:"sku,omitempty"` - // SslPolicy - SSL policy of the application gateway resource. - SslPolicy *ApplicationGatewaySslPolicy `json:"sslPolicy,omitempty"` - // OperationalState - READ-ONLY; Operational state of the application gateway resource. Possible values include: 'Stopped', 'Starting', 'Running', 'Stopping' - OperationalState ApplicationGatewayOperationalState `json:"operationalState,omitempty"` - // GatewayIPConfigurations - Subnets of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - GatewayIPConfigurations *[]ApplicationGatewayIPConfiguration `json:"gatewayIPConfigurations,omitempty"` - // AuthenticationCertificates - Authentication certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - AuthenticationCertificates *[]ApplicationGatewayAuthenticationCertificate `json:"authenticationCertificates,omitempty"` - // TrustedRootCertificates - Trusted Root certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - TrustedRootCertificates *[]ApplicationGatewayTrustedRootCertificate `json:"trustedRootCertificates,omitempty"` - // TrustedClientCertificates - Trusted client certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - TrustedClientCertificates *[]ApplicationGatewayTrustedClientCertificate `json:"trustedClientCertificates,omitempty"` - // SslCertificates - SSL certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - SslCertificates *[]ApplicationGatewaySslCertificate `json:"sslCertificates,omitempty"` - // FrontendIPConfigurations - Frontend IP addresses of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - FrontendIPConfigurations *[]ApplicationGatewayFrontendIPConfiguration `json:"frontendIPConfigurations,omitempty"` - // FrontendPorts - Frontend ports of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - FrontendPorts *[]ApplicationGatewayFrontendPort `json:"frontendPorts,omitempty"` - // Probes - Probes of the application gateway resource. - Probes *[]ApplicationGatewayProbe `json:"probes,omitempty"` - // BackendAddressPools - Backend address pool of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - BackendAddressPools *[]ApplicationGatewayBackendAddressPool `json:"backendAddressPools,omitempty"` - // BackendHTTPSettingsCollection - Backend http settings of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - BackendHTTPSettingsCollection *[]ApplicationGatewayBackendHTTPSettings `json:"backendHttpSettingsCollection,omitempty"` - // BackendSettingsCollection - Backend settings of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - BackendSettingsCollection *[]ApplicationGatewayBackendSettings `json:"backendSettingsCollection,omitempty"` - // HTTPListeners - Http listeners of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - HTTPListeners *[]ApplicationGatewayHTTPListener `json:"httpListeners,omitempty"` - // Listeners - Listeners of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - Listeners *[]ApplicationGatewayListener `json:"listeners,omitempty"` - // SslProfiles - SSL profiles of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - SslProfiles *[]ApplicationGatewaySslProfile `json:"sslProfiles,omitempty"` - // URLPathMaps - URL path map of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - URLPathMaps *[]ApplicationGatewayURLPathMap `json:"urlPathMaps,omitempty"` - // RequestRoutingRules - Request routing rules of the application gateway resource. - RequestRoutingRules *[]ApplicationGatewayRequestRoutingRule `json:"requestRoutingRules,omitempty"` - // RoutingRules - Routing rules of the application gateway resource. - RoutingRules *[]ApplicationGatewayRoutingRule `json:"routingRules,omitempty"` - // RewriteRuleSets - Rewrite rules for the application gateway resource. - RewriteRuleSets *[]ApplicationGatewayRewriteRuleSet `json:"rewriteRuleSets,omitempty"` - // RedirectConfigurations - Redirect configurations of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits). - RedirectConfigurations *[]ApplicationGatewayRedirectConfiguration `json:"redirectConfigurations,omitempty"` - // WebApplicationFirewallConfiguration - Web application firewall configuration. - WebApplicationFirewallConfiguration *ApplicationGatewayWebApplicationFirewallConfiguration `json:"webApplicationFirewallConfiguration,omitempty"` - // FirewallPolicy - Reference to the FirewallPolicy resource. - FirewallPolicy *SubResource `json:"firewallPolicy,omitempty"` - // EnableHTTP2 - Whether HTTP2 is enabled on the application gateway resource. - EnableHTTP2 *bool `json:"enableHttp2,omitempty"` - // EnableFips - Whether FIPS is enabled on the application gateway resource. - EnableFips *bool `json:"enableFips,omitempty"` - // AutoscaleConfiguration - Autoscale Configuration. - AutoscaleConfiguration *ApplicationGatewayAutoscaleConfiguration `json:"autoscaleConfiguration,omitempty"` - // PrivateLinkConfigurations - PrivateLink configurations on application gateway. - PrivateLinkConfigurations *[]ApplicationGatewayPrivateLinkConfiguration `json:"privateLinkConfigurations,omitempty"` - // PrivateEndpointConnections - READ-ONLY; Private Endpoint connections on application gateway. - PrivateEndpointConnections *[]ApplicationGatewayPrivateEndpointConnection `json:"privateEndpointConnections,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the application gateway resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the application gateway resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // CustomErrorConfigurations - Custom error configurations of the application gateway resource. - CustomErrorConfigurations *[]ApplicationGatewayCustomError `json:"customErrorConfigurations,omitempty"` - // ForceFirewallPolicyAssociation - If true, associates a firewall policy with an application gateway regardless whether the policy differs from the WAF Config. - ForceFirewallPolicyAssociation *bool `json:"forceFirewallPolicyAssociation,omitempty"` - // LoadDistributionPolicies - Load distribution policies of the application gateway resource. - LoadDistributionPolicies *[]ApplicationGatewayLoadDistributionPolicy `json:"loadDistributionPolicies,omitempty"` - // GlobalConfiguration - Global Configuration. - GlobalConfiguration *ApplicationGatewayGlobalConfiguration `json:"globalConfiguration,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayPropertiesFormat. -func (agpf ApplicationGatewayPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agpf.Sku != nil { - objectMap["sku"] = agpf.Sku - } - if agpf.SslPolicy != nil { - objectMap["sslPolicy"] = agpf.SslPolicy - } - if agpf.GatewayIPConfigurations != nil { - objectMap["gatewayIPConfigurations"] = agpf.GatewayIPConfigurations - } - if agpf.AuthenticationCertificates != nil { - objectMap["authenticationCertificates"] = agpf.AuthenticationCertificates - } - if agpf.TrustedRootCertificates != nil { - objectMap["trustedRootCertificates"] = agpf.TrustedRootCertificates - } - if agpf.TrustedClientCertificates != nil { - objectMap["trustedClientCertificates"] = agpf.TrustedClientCertificates - } - if agpf.SslCertificates != nil { - objectMap["sslCertificates"] = agpf.SslCertificates - } - if agpf.FrontendIPConfigurations != nil { - objectMap["frontendIPConfigurations"] = agpf.FrontendIPConfigurations - } - if agpf.FrontendPorts != nil { - objectMap["frontendPorts"] = agpf.FrontendPorts - } - if agpf.Probes != nil { - objectMap["probes"] = agpf.Probes - } - if agpf.BackendAddressPools != nil { - objectMap["backendAddressPools"] = agpf.BackendAddressPools - } - if agpf.BackendHTTPSettingsCollection != nil { - objectMap["backendHttpSettingsCollection"] = agpf.BackendHTTPSettingsCollection - } - if agpf.BackendSettingsCollection != nil { - objectMap["backendSettingsCollection"] = agpf.BackendSettingsCollection - } - if agpf.HTTPListeners != nil { - objectMap["httpListeners"] = agpf.HTTPListeners - } - if agpf.Listeners != nil { - objectMap["listeners"] = agpf.Listeners - } - if agpf.SslProfiles != nil { - objectMap["sslProfiles"] = agpf.SslProfiles - } - if agpf.URLPathMaps != nil { - objectMap["urlPathMaps"] = agpf.URLPathMaps - } - if agpf.RequestRoutingRules != nil { - objectMap["requestRoutingRules"] = agpf.RequestRoutingRules - } - if agpf.RoutingRules != nil { - objectMap["routingRules"] = agpf.RoutingRules - } - if agpf.RewriteRuleSets != nil { - objectMap["rewriteRuleSets"] = agpf.RewriteRuleSets - } - if agpf.RedirectConfigurations != nil { - objectMap["redirectConfigurations"] = agpf.RedirectConfigurations - } - if agpf.WebApplicationFirewallConfiguration != nil { - objectMap["webApplicationFirewallConfiguration"] = agpf.WebApplicationFirewallConfiguration - } - if agpf.FirewallPolicy != nil { - objectMap["firewallPolicy"] = agpf.FirewallPolicy - } - if agpf.EnableHTTP2 != nil { - objectMap["enableHttp2"] = agpf.EnableHTTP2 - } - if agpf.EnableFips != nil { - objectMap["enableFips"] = agpf.EnableFips - } - if agpf.AutoscaleConfiguration != nil { - objectMap["autoscaleConfiguration"] = agpf.AutoscaleConfiguration - } - if agpf.PrivateLinkConfigurations != nil { - objectMap["privateLinkConfigurations"] = agpf.PrivateLinkConfigurations - } - if agpf.CustomErrorConfigurations != nil { - objectMap["customErrorConfigurations"] = agpf.CustomErrorConfigurations - } - if agpf.ForceFirewallPolicyAssociation != nil { - objectMap["forceFirewallPolicyAssociation"] = agpf.ForceFirewallPolicyAssociation - } - if agpf.LoadDistributionPolicies != nil { - objectMap["loadDistributionPolicies"] = agpf.LoadDistributionPolicies - } - if agpf.GlobalConfiguration != nil { - objectMap["globalConfiguration"] = agpf.GlobalConfiguration - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayRedirectConfiguration redirect configuration of an application gateway. -type ApplicationGatewayRedirectConfiguration struct { - // ApplicationGatewayRedirectConfigurationPropertiesFormat - Properties of the application gateway redirect configuration. - *ApplicationGatewayRedirectConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the redirect configuration that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayRedirectConfiguration. -func (agrc ApplicationGatewayRedirectConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agrc.ApplicationGatewayRedirectConfigurationPropertiesFormat != nil { - objectMap["properties"] = agrc.ApplicationGatewayRedirectConfigurationPropertiesFormat - } - if agrc.Name != nil { - objectMap["name"] = agrc.Name - } - if agrc.ID != nil { - objectMap["id"] = agrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayRedirectConfiguration struct. -func (agrc *ApplicationGatewayRedirectConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayRedirectConfigurationPropertiesFormat ApplicationGatewayRedirectConfigurationPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayRedirectConfigurationPropertiesFormat) - if err != nil { - return err - } - agrc.ApplicationGatewayRedirectConfigurationPropertiesFormat = &applicationGatewayRedirectConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agrc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agrc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agrc.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayRedirectConfigurationPropertiesFormat properties of redirect configuration of the -// application gateway. -type ApplicationGatewayRedirectConfigurationPropertiesFormat struct { - // RedirectType - HTTP redirection type. Possible values include: 'Permanent', 'Found', 'SeeOther', 'Temporary' - RedirectType ApplicationGatewayRedirectType `json:"redirectType,omitempty"` - // TargetListener - Reference to a listener to redirect the request to. - TargetListener *SubResource `json:"targetListener,omitempty"` - // TargetURL - Url to redirect the request to. - TargetURL *string `json:"targetUrl,omitempty"` - // IncludePath - Include path in the redirected url. - IncludePath *bool `json:"includePath,omitempty"` - // IncludeQueryString - Include query string in the redirected url. - IncludeQueryString *bool `json:"includeQueryString,omitempty"` - // RequestRoutingRules - Request routing specifying redirect configuration. - RequestRoutingRules *[]SubResource `json:"requestRoutingRules,omitempty"` - // URLPathMaps - Url path maps specifying default redirect configuration. - URLPathMaps *[]SubResource `json:"urlPathMaps,omitempty"` - // PathRules - Path rules specifying redirect configuration. - PathRules *[]SubResource `json:"pathRules,omitempty"` -} - -// ApplicationGatewayRequestRoutingRule request routing rule of an application gateway. -type ApplicationGatewayRequestRoutingRule struct { - // ApplicationGatewayRequestRoutingRulePropertiesFormat - Properties of the application gateway request routing rule. - *ApplicationGatewayRequestRoutingRulePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the request routing rule that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayRequestRoutingRule. -func (agrrr ApplicationGatewayRequestRoutingRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agrrr.ApplicationGatewayRequestRoutingRulePropertiesFormat != nil { - objectMap["properties"] = agrrr.ApplicationGatewayRequestRoutingRulePropertiesFormat - } - if agrrr.Name != nil { - objectMap["name"] = agrrr.Name - } - if agrrr.ID != nil { - objectMap["id"] = agrrr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayRequestRoutingRule struct. -func (agrrr *ApplicationGatewayRequestRoutingRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayRequestRoutingRulePropertiesFormat ApplicationGatewayRequestRoutingRulePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayRequestRoutingRulePropertiesFormat) - if err != nil { - return err - } - agrrr.ApplicationGatewayRequestRoutingRulePropertiesFormat = &applicationGatewayRequestRoutingRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agrrr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agrrr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agrrr.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agrrr.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayRequestRoutingRulePropertiesFormat properties of request routing rule of the -// application gateway. -type ApplicationGatewayRequestRoutingRulePropertiesFormat struct { - // RuleType - Rule type. Possible values include: 'Basic', 'PathBasedRouting' - RuleType ApplicationGatewayRequestRoutingRuleType `json:"ruleType,omitempty"` - // Priority - Priority of the request routing rule. - Priority *int32 `json:"priority,omitempty"` - // BackendAddressPool - Backend address pool resource of the application gateway. - BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` - // BackendHTTPSettings - Backend http settings resource of the application gateway. - BackendHTTPSettings *SubResource `json:"backendHttpSettings,omitempty"` - // HTTPListener - Http listener resource of the application gateway. - HTTPListener *SubResource `json:"httpListener,omitempty"` - // URLPathMap - URL path map resource of the application gateway. - URLPathMap *SubResource `json:"urlPathMap,omitempty"` - // RewriteRuleSet - Rewrite Rule Set resource in Basic rule of the application gateway. - RewriteRuleSet *SubResource `json:"rewriteRuleSet,omitempty"` - // RedirectConfiguration - Redirect configuration resource of the application gateway. - RedirectConfiguration *SubResource `json:"redirectConfiguration,omitempty"` - // LoadDistributionPolicy - Load Distribution Policy resource of the application gateway. - LoadDistributionPolicy *SubResource `json:"loadDistributionPolicy,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the request routing rule resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayRequestRoutingRulePropertiesFormat. -func (agrrrpf ApplicationGatewayRequestRoutingRulePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agrrrpf.RuleType != "" { - objectMap["ruleType"] = agrrrpf.RuleType - } - if agrrrpf.Priority != nil { - objectMap["priority"] = agrrrpf.Priority - } - if agrrrpf.BackendAddressPool != nil { - objectMap["backendAddressPool"] = agrrrpf.BackendAddressPool - } - if agrrrpf.BackendHTTPSettings != nil { - objectMap["backendHttpSettings"] = agrrrpf.BackendHTTPSettings - } - if agrrrpf.HTTPListener != nil { - objectMap["httpListener"] = agrrrpf.HTTPListener - } - if agrrrpf.URLPathMap != nil { - objectMap["urlPathMap"] = agrrrpf.URLPathMap - } - if agrrrpf.RewriteRuleSet != nil { - objectMap["rewriteRuleSet"] = agrrrpf.RewriteRuleSet - } - if agrrrpf.RedirectConfiguration != nil { - objectMap["redirectConfiguration"] = agrrrpf.RedirectConfiguration - } - if agrrrpf.LoadDistributionPolicy != nil { - objectMap["loadDistributionPolicy"] = agrrrpf.LoadDistributionPolicy - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayRewriteRule rewrite rule of an application gateway. -type ApplicationGatewayRewriteRule struct { - // Name - Name of the rewrite rule that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // RuleSequence - Rule Sequence of the rewrite rule that determines the order of execution of a particular rule in a RewriteRuleSet. - RuleSequence *int32 `json:"ruleSequence,omitempty"` - // Conditions - Conditions based on which the action set execution will be evaluated. - Conditions *[]ApplicationGatewayRewriteRuleCondition `json:"conditions,omitempty"` - // ActionSet - Set of actions to be done as part of the rewrite Rule. - ActionSet *ApplicationGatewayRewriteRuleActionSet `json:"actionSet,omitempty"` -} - -// ApplicationGatewayRewriteRuleActionSet set of actions in the Rewrite Rule in Application Gateway. -type ApplicationGatewayRewriteRuleActionSet struct { - // RequestHeaderConfigurations - Request Header Actions in the Action Set. - RequestHeaderConfigurations *[]ApplicationGatewayHeaderConfiguration `json:"requestHeaderConfigurations,omitempty"` - // ResponseHeaderConfigurations - Response Header Actions in the Action Set. - ResponseHeaderConfigurations *[]ApplicationGatewayHeaderConfiguration `json:"responseHeaderConfigurations,omitempty"` - // URLConfiguration - Url Configuration Action in the Action Set. - URLConfiguration *ApplicationGatewayURLConfiguration `json:"urlConfiguration,omitempty"` -} - -// ApplicationGatewayRewriteRuleCondition set of conditions in the Rewrite Rule in Application Gateway. -type ApplicationGatewayRewriteRuleCondition struct { - // Variable - The condition parameter of the RewriteRuleCondition. - Variable *string `json:"variable,omitempty"` - // Pattern - The pattern, either fixed string or regular expression, that evaluates the truthfulness of the condition. - Pattern *string `json:"pattern,omitempty"` - // IgnoreCase - Setting this parameter to truth value with force the pattern to do a case in-sensitive comparison. - IgnoreCase *bool `json:"ignoreCase,omitempty"` - // Negate - Setting this value as truth will force to check the negation of the condition given by the user. - Negate *bool `json:"negate,omitempty"` -} - -// ApplicationGatewayRewriteRuleSet rewrite rule set of an application gateway. -type ApplicationGatewayRewriteRuleSet struct { - // ApplicationGatewayRewriteRuleSetPropertiesFormat - Properties of the application gateway rewrite rule set. - *ApplicationGatewayRewriteRuleSetPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the rewrite rule set that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayRewriteRuleSet. -func (agrrs ApplicationGatewayRewriteRuleSet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agrrs.ApplicationGatewayRewriteRuleSetPropertiesFormat != nil { - objectMap["properties"] = agrrs.ApplicationGatewayRewriteRuleSetPropertiesFormat - } - if agrrs.Name != nil { - objectMap["name"] = agrrs.Name - } - if agrrs.ID != nil { - objectMap["id"] = agrrs.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayRewriteRuleSet struct. -func (agrrs *ApplicationGatewayRewriteRuleSet) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayRewriteRuleSetPropertiesFormat ApplicationGatewayRewriteRuleSetPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayRewriteRuleSetPropertiesFormat) - if err != nil { - return err - } - agrrs.ApplicationGatewayRewriteRuleSetPropertiesFormat = &applicationGatewayRewriteRuleSetPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agrrs.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agrrs.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agrrs.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayRewriteRuleSetPropertiesFormat properties of rewrite rule set of the application -// gateway. -type ApplicationGatewayRewriteRuleSetPropertiesFormat struct { - // RewriteRules - Rewrite rules in the rewrite rule set. - RewriteRules *[]ApplicationGatewayRewriteRule `json:"rewriteRules,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the rewrite rule set resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayRewriteRuleSetPropertiesFormat. -func (agrrspf ApplicationGatewayRewriteRuleSetPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agrrspf.RewriteRules != nil { - objectMap["rewriteRules"] = agrrspf.RewriteRules - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayRoutingRule routing rule of an application gateway. -type ApplicationGatewayRoutingRule struct { - // ApplicationGatewayRoutingRulePropertiesFormat - Properties of the application gateway routing rule. - *ApplicationGatewayRoutingRulePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the routing rule that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayRoutingRule. -func (agrr ApplicationGatewayRoutingRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agrr.ApplicationGatewayRoutingRulePropertiesFormat != nil { - objectMap["properties"] = agrr.ApplicationGatewayRoutingRulePropertiesFormat - } - if agrr.Name != nil { - objectMap["name"] = agrr.Name - } - if agrr.ID != nil { - objectMap["id"] = agrr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayRoutingRule struct. -func (agrr *ApplicationGatewayRoutingRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayRoutingRulePropertiesFormat ApplicationGatewayRoutingRulePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayRoutingRulePropertiesFormat) - if err != nil { - return err - } - agrr.ApplicationGatewayRoutingRulePropertiesFormat = &applicationGatewayRoutingRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agrr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agrr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agrr.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agrr.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayRoutingRulePropertiesFormat properties of routing rule of the application gateway. -type ApplicationGatewayRoutingRulePropertiesFormat struct { - // RuleType - Rule type. Possible values include: 'Basic', 'PathBasedRouting' - RuleType ApplicationGatewayRequestRoutingRuleType `json:"ruleType,omitempty"` - // Priority - Priority of the routing rule. - Priority *int32 `json:"priority,omitempty"` - // BackendAddressPool - Backend address pool resource of the application gateway. - BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` - // BackendSettings - Backend settings resource of the application gateway. - BackendSettings *SubResource `json:"backendSettings,omitempty"` - // Listener - Listener resource of the application gateway. - Listener *SubResource `json:"listener,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the request routing rule resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayRoutingRulePropertiesFormat. -func (agrrpf ApplicationGatewayRoutingRulePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agrrpf.RuleType != "" { - objectMap["ruleType"] = agrrpf.RuleType - } - if agrrpf.Priority != nil { - objectMap["priority"] = agrrpf.Priority - } - if agrrpf.BackendAddressPool != nil { - objectMap["backendAddressPool"] = agrrpf.BackendAddressPool - } - if agrrpf.BackendSettings != nil { - objectMap["backendSettings"] = agrrpf.BackendSettings - } - if agrrpf.Listener != nil { - objectMap["listener"] = agrrpf.Listener - } - return json.Marshal(objectMap) -} - -// ApplicationGatewaysBackendHealthFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ApplicationGatewaysBackendHealthFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewaysClient) (ApplicationGatewayBackendHealth, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewaysBackendHealthFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewaysBackendHealthFuture.Result. -func (future *ApplicationGatewaysBackendHealthFuture) result(client ApplicationGatewaysClient) (agbh ApplicationGatewayBackendHealth, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysBackendHealthFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - agbh.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewaysBackendHealthFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if agbh.Response.Response, err = future.GetResult(sender); err == nil && agbh.Response.Response.StatusCode != http.StatusNoContent { - agbh, err = client.BackendHealthResponder(agbh.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysBackendHealthFuture", "Result", agbh.Response.Response, "Failure responding to request") - } - } - return -} - -// ApplicationGatewaysBackendHealthOnDemandFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type ApplicationGatewaysBackendHealthOnDemandFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewaysClient) (ApplicationGatewayBackendHealthOnDemand, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewaysBackendHealthOnDemandFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewaysBackendHealthOnDemandFuture.Result. -func (future *ApplicationGatewaysBackendHealthOnDemandFuture) result(client ApplicationGatewaysClient) (agbhod ApplicationGatewayBackendHealthOnDemand, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysBackendHealthOnDemandFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - agbhod.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewaysBackendHealthOnDemandFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if agbhod.Response.Response, err = future.GetResult(sender); err == nil && agbhod.Response.Response.StatusCode != http.StatusNoContent { - agbhod, err = client.BackendHealthOnDemandResponder(agbhod.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysBackendHealthOnDemandFuture", "Result", agbhod.Response.Response, "Failure responding to request") - } - } - return -} - -// ApplicationGatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ApplicationGatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewaysClient) (ApplicationGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewaysCreateOrUpdateFuture.Result. -func (future *ApplicationGatewaysCreateOrUpdateFuture) result(client ApplicationGatewaysClient) (ag ApplicationGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ag.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ag.Response.Response, err = future.GetResult(sender); err == nil && ag.Response.Response.StatusCode != http.StatusNoContent { - ag, err = client.CreateOrUpdateResponder(ag.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysCreateOrUpdateFuture", "Result", ag.Response.Response, "Failure responding to request") - } - } - return -} - -// ApplicationGatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ApplicationGatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewaysDeleteFuture.Result. -func (future *ApplicationGatewaysDeleteFuture) result(client ApplicationGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ApplicationGatewaySku SKU of an application gateway. -type ApplicationGatewaySku struct { - // Name - Name of an application gateway SKU. Possible values include: 'StandardSmall', 'StandardMedium', 'StandardLarge', 'WAFMedium', 'WAFLarge', 'StandardV2', 'StandardBasic', 'WAFV2' - Name ApplicationGatewaySkuName `json:"name,omitempty"` - // Tier - Tier of an application gateway. Possible values include: 'ApplicationGatewayTierStandard', 'ApplicationGatewayTierWAF', 'ApplicationGatewayTierStandardV2', 'ApplicationGatewayTierWAFV2', 'ApplicationGatewayTierStandardBasic' - Tier ApplicationGatewayTier `json:"tier,omitempty"` - // Capacity - Capacity (instance count) of an application gateway. - Capacity *int32 `json:"capacity,omitempty"` -} - -// ApplicationGatewaySslCertificate SSL certificates of an application gateway. -type ApplicationGatewaySslCertificate struct { - // ApplicationGatewaySslCertificatePropertiesFormat - Properties of the application gateway SSL certificate. - *ApplicationGatewaySslCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the SSL certificate that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewaySslCertificate. -func (agsc ApplicationGatewaySslCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agsc.ApplicationGatewaySslCertificatePropertiesFormat != nil { - objectMap["properties"] = agsc.ApplicationGatewaySslCertificatePropertiesFormat - } - if agsc.Name != nil { - objectMap["name"] = agsc.Name - } - if agsc.ID != nil { - objectMap["id"] = agsc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewaySslCertificate struct. -func (agsc *ApplicationGatewaySslCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewaySslCertificatePropertiesFormat ApplicationGatewaySslCertificatePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewaySslCertificatePropertiesFormat) - if err != nil { - return err - } - agsc.ApplicationGatewaySslCertificatePropertiesFormat = &applicationGatewaySslCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agsc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agsc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agsc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agsc.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewaySslCertificatePropertiesFormat properties of SSL certificates of an application -// gateway. -type ApplicationGatewaySslCertificatePropertiesFormat struct { - // Data - Base-64 encoded pfx certificate. Only applicable in PUT Request. - Data *string `json:"data,omitempty"` - // Password - Password for the pfx file specified in data. Only applicable in PUT request. - Password *string `json:"password,omitempty"` - // PublicCertData - READ-ONLY; Base-64 encoded Public cert data corresponding to pfx specified in data. Only applicable in GET request. - PublicCertData *string `json:"publicCertData,omitempty"` - // KeyVaultSecretID - Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or 'Certificate' object stored in KeyVault. - KeyVaultSecretID *string `json:"keyVaultSecretId,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the SSL certificate resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewaySslCertificatePropertiesFormat. -func (agscpf ApplicationGatewaySslCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agscpf.Data != nil { - objectMap["data"] = agscpf.Data - } - if agscpf.Password != nil { - objectMap["password"] = agscpf.Password - } - if agscpf.KeyVaultSecretID != nil { - objectMap["keyVaultSecretId"] = agscpf.KeyVaultSecretID - } - return json.Marshal(objectMap) -} - -// ApplicationGatewaySslPolicy application Gateway Ssl policy. -type ApplicationGatewaySslPolicy struct { - // DisabledSslProtocols - Ssl protocols to be disabled on application gateway. - DisabledSslProtocols *[]ApplicationGatewaySslProtocol `json:"disabledSslProtocols,omitempty"` - // PolicyType - Type of Ssl Policy. Possible values include: 'Predefined', 'Custom', 'CustomV2' - PolicyType ApplicationGatewaySslPolicyType `json:"policyType,omitempty"` - // PolicyName - Name of Ssl predefined policy. Possible values include: 'AppGwSslPolicy20150501', 'AppGwSslPolicy20170401', 'AppGwSslPolicy20170401S', 'AppGwSslPolicy20220101', 'AppGwSslPolicy20220101S' - PolicyName ApplicationGatewaySslPolicyName `json:"policyName,omitempty"` - // CipherSuites - Ssl cipher suites to be enabled in the specified order to application gateway. - CipherSuites *[]ApplicationGatewaySslCipherSuite `json:"cipherSuites,omitempty"` - // MinProtocolVersion - Minimum version of Ssl protocol to be supported on application gateway. Possible values include: 'TLSv10', 'TLSv11', 'TLSv12', 'TLSv13' - MinProtocolVersion ApplicationGatewaySslProtocol `json:"minProtocolVersion,omitempty"` -} - -// ApplicationGatewaySslPredefinedPolicy an Ssl predefined policy. -type ApplicationGatewaySslPredefinedPolicy struct { - autorest.Response `json:"-"` - // Name - Name of the Ssl predefined policy. - Name *string `json:"name,omitempty"` - // ApplicationGatewaySslPredefinedPolicyPropertiesFormat - Properties of the application gateway SSL predefined policy. - *ApplicationGatewaySslPredefinedPolicyPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewaySslPredefinedPolicy. -func (agspp ApplicationGatewaySslPredefinedPolicy) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agspp.Name != nil { - objectMap["name"] = agspp.Name - } - if agspp.ApplicationGatewaySslPredefinedPolicyPropertiesFormat != nil { - objectMap["properties"] = agspp.ApplicationGatewaySslPredefinedPolicyPropertiesFormat - } - if agspp.ID != nil { - objectMap["id"] = agspp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewaySslPredefinedPolicy struct. -func (agspp *ApplicationGatewaySslPredefinedPolicy) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agspp.Name = &name - } - case "properties": - if v != nil { - var applicationGatewaySslPredefinedPolicyPropertiesFormat ApplicationGatewaySslPredefinedPolicyPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewaySslPredefinedPolicyPropertiesFormat) - if err != nil { - return err - } - agspp.ApplicationGatewaySslPredefinedPolicyPropertiesFormat = &applicationGatewaySslPredefinedPolicyPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agspp.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewaySslPredefinedPolicyPropertiesFormat properties of -// ApplicationGatewaySslPredefinedPolicy. -type ApplicationGatewaySslPredefinedPolicyPropertiesFormat struct { - // CipherSuites - Ssl cipher suites to be enabled in the specified order for application gateway. - CipherSuites *[]ApplicationGatewaySslCipherSuite `json:"cipherSuites,omitempty"` - // MinProtocolVersion - Minimum version of Ssl protocol to be supported on application gateway. Possible values include: 'TLSv10', 'TLSv11', 'TLSv12', 'TLSv13' - MinProtocolVersion ApplicationGatewaySslProtocol `json:"minProtocolVersion,omitempty"` -} - -// ApplicationGatewaySslProfile SSL profile of an application gateway. -type ApplicationGatewaySslProfile struct { - // ApplicationGatewaySslProfilePropertiesFormat - Properties of the application gateway SSL profile. - *ApplicationGatewaySslProfilePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the SSL profile that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewaySslProfile. -func (agsp ApplicationGatewaySslProfile) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agsp.ApplicationGatewaySslProfilePropertiesFormat != nil { - objectMap["properties"] = agsp.ApplicationGatewaySslProfilePropertiesFormat - } - if agsp.Name != nil { - objectMap["name"] = agsp.Name - } - if agsp.ID != nil { - objectMap["id"] = agsp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewaySslProfile struct. -func (agsp *ApplicationGatewaySslProfile) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewaySslProfilePropertiesFormat ApplicationGatewaySslProfilePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewaySslProfilePropertiesFormat) - if err != nil { - return err - } - agsp.ApplicationGatewaySslProfilePropertiesFormat = &applicationGatewaySslProfilePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agsp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agsp.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agsp.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agsp.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewaySslProfilePropertiesFormat properties of SSL profile of an application gateway. -type ApplicationGatewaySslProfilePropertiesFormat struct { - // TrustedClientCertificates - Array of references to application gateway trusted client certificates. - TrustedClientCertificates *[]SubResource `json:"trustedClientCertificates,omitempty"` - // SslPolicy - SSL policy of the application gateway resource. - SslPolicy *ApplicationGatewaySslPolicy `json:"sslPolicy,omitempty"` - // ClientAuthConfiguration - Client authentication configuration of the application gateway resource. - ClientAuthConfiguration *ApplicationGatewayClientAuthConfiguration `json:"clientAuthConfiguration,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the HTTP listener resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewaySslProfilePropertiesFormat. -func (agsppf ApplicationGatewaySslProfilePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agsppf.TrustedClientCertificates != nil { - objectMap["trustedClientCertificates"] = agsppf.TrustedClientCertificates - } - if agsppf.SslPolicy != nil { - objectMap["sslPolicy"] = agsppf.SslPolicy - } - if agsppf.ClientAuthConfiguration != nil { - objectMap["clientAuthConfiguration"] = agsppf.ClientAuthConfiguration - } - return json.Marshal(objectMap) -} - -// ApplicationGatewaysStartFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ApplicationGatewaysStartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewaysStartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewaysStartFuture.Result. -func (future *ApplicationGatewaysStartFuture) result(client ApplicationGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysStartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewaysStartFuture") - return - } - ar.Response = future.Response() - return -} - -// ApplicationGatewaysStopFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ApplicationGatewaysStopFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationGatewaysStopFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationGatewaysStopFuture.Result. -func (future *ApplicationGatewaysStopFuture) result(client ApplicationGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysStopFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationGatewaysStopFuture") - return - } - ar.Response = future.Response() - return -} - -// ApplicationGatewayTrustedClientCertificate trusted client certificates of an application gateway. -type ApplicationGatewayTrustedClientCertificate struct { - // ApplicationGatewayTrustedClientCertificatePropertiesFormat - Properties of the application gateway trusted client certificate. - *ApplicationGatewayTrustedClientCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the trusted client certificate that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayTrustedClientCertificate. -func (agtcc ApplicationGatewayTrustedClientCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agtcc.ApplicationGatewayTrustedClientCertificatePropertiesFormat != nil { - objectMap["properties"] = agtcc.ApplicationGatewayTrustedClientCertificatePropertiesFormat - } - if agtcc.Name != nil { - objectMap["name"] = agtcc.Name - } - if agtcc.ID != nil { - objectMap["id"] = agtcc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayTrustedClientCertificate struct. -func (agtcc *ApplicationGatewayTrustedClientCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayTrustedClientCertificatePropertiesFormat ApplicationGatewayTrustedClientCertificatePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayTrustedClientCertificatePropertiesFormat) - if err != nil { - return err - } - agtcc.ApplicationGatewayTrustedClientCertificatePropertiesFormat = &applicationGatewayTrustedClientCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agtcc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agtcc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agtcc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agtcc.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayTrustedClientCertificatePropertiesFormat trusted client certificates properties of an -// application gateway. -type ApplicationGatewayTrustedClientCertificatePropertiesFormat struct { - // Data - Certificate public data. - Data *string `json:"data,omitempty"` - // ValidatedCertData - READ-ONLY; Validated certificate data. - ValidatedCertData *string `json:"validatedCertData,omitempty"` - // ClientCertIssuerDN - READ-ONLY; Distinguished name of client certificate issuer. - ClientCertIssuerDN *string `json:"clientCertIssuerDN,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the trusted client certificate resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayTrustedClientCertificatePropertiesFormat. -func (agtccpf ApplicationGatewayTrustedClientCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agtccpf.Data != nil { - objectMap["data"] = agtccpf.Data - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayTrustedRootCertificate trusted Root certificates of an application gateway. -type ApplicationGatewayTrustedRootCertificate struct { - // ApplicationGatewayTrustedRootCertificatePropertiesFormat - Properties of the application gateway trusted root certificate. - *ApplicationGatewayTrustedRootCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - Name of the trusted root certificate that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayTrustedRootCertificate. -func (agtrc ApplicationGatewayTrustedRootCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agtrc.ApplicationGatewayTrustedRootCertificatePropertiesFormat != nil { - objectMap["properties"] = agtrc.ApplicationGatewayTrustedRootCertificatePropertiesFormat - } - if agtrc.Name != nil { - objectMap["name"] = agtrc.Name - } - if agtrc.ID != nil { - objectMap["id"] = agtrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayTrustedRootCertificate struct. -func (agtrc *ApplicationGatewayTrustedRootCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayTrustedRootCertificatePropertiesFormat ApplicationGatewayTrustedRootCertificatePropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayTrustedRootCertificatePropertiesFormat) - if err != nil { - return err - } - agtrc.ApplicationGatewayTrustedRootCertificatePropertiesFormat = &applicationGatewayTrustedRootCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agtrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agtrc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agtrc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agtrc.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayTrustedRootCertificatePropertiesFormat trusted Root certificates properties of an -// application gateway. -type ApplicationGatewayTrustedRootCertificatePropertiesFormat struct { - // Data - Certificate public data. - Data *string `json:"data,omitempty"` - // KeyVaultSecretID - Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or 'Certificate' object stored in KeyVault. - KeyVaultSecretID *string `json:"keyVaultSecretId,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the trusted root certificate resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayTrustedRootCertificatePropertiesFormat. -func (agtrcpf ApplicationGatewayTrustedRootCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agtrcpf.Data != nil { - objectMap["data"] = agtrcpf.Data - } - if agtrcpf.KeyVaultSecretID != nil { - objectMap["keyVaultSecretId"] = agtrcpf.KeyVaultSecretID - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayURLConfiguration url configuration of the Actions set in Application Gateway. -type ApplicationGatewayURLConfiguration struct { - // ModifiedPath - Url path which user has provided for url rewrite. Null means no path will be updated. Default value is null. - ModifiedPath *string `json:"modifiedPath,omitempty"` - // ModifiedQueryString - Query string which user has provided for url rewrite. Null means no query string will be updated. Default value is null. - ModifiedQueryString *string `json:"modifiedQueryString,omitempty"` - // Reroute - If set as true, it will re-evaluate the url path map provided in path based request routing rules using modified path. Default value is false. - Reroute *bool `json:"reroute,omitempty"` -} - -// ApplicationGatewayURLPathMap urlPathMaps give a url path to the backend mapping information for -// PathBasedRouting. -type ApplicationGatewayURLPathMap struct { - // ApplicationGatewayURLPathMapPropertiesFormat - Properties of the application gateway URL path map. - *ApplicationGatewayURLPathMapPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the URL path map that is unique within an Application Gateway. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayURLPathMap. -func (agupm ApplicationGatewayURLPathMap) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agupm.ApplicationGatewayURLPathMapPropertiesFormat != nil { - objectMap["properties"] = agupm.ApplicationGatewayURLPathMapPropertiesFormat - } - if agupm.Name != nil { - objectMap["name"] = agupm.Name - } - if agupm.ID != nil { - objectMap["id"] = agupm.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayURLPathMap struct. -func (agupm *ApplicationGatewayURLPathMap) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationGatewayURLPathMapPropertiesFormat ApplicationGatewayURLPathMapPropertiesFormat - err = json.Unmarshal(*v, &applicationGatewayURLPathMapPropertiesFormat) - if err != nil { - return err - } - agupm.ApplicationGatewayURLPathMapPropertiesFormat = &applicationGatewayURLPathMapPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agupm.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - agupm.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agupm.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agupm.ID = &ID - } - } - } - - return nil -} - -// ApplicationGatewayURLPathMapPropertiesFormat properties of UrlPathMap of the application gateway. -type ApplicationGatewayURLPathMapPropertiesFormat struct { - // DefaultBackendAddressPool - Default backend address pool resource of URL path map. - DefaultBackendAddressPool *SubResource `json:"defaultBackendAddressPool,omitempty"` - // DefaultBackendHTTPSettings - Default backend http settings resource of URL path map. - DefaultBackendHTTPSettings *SubResource `json:"defaultBackendHttpSettings,omitempty"` - // DefaultRewriteRuleSet - Default Rewrite rule set resource of URL path map. - DefaultRewriteRuleSet *SubResource `json:"defaultRewriteRuleSet,omitempty"` - // DefaultRedirectConfiguration - Default redirect configuration resource of URL path map. - DefaultRedirectConfiguration *SubResource `json:"defaultRedirectConfiguration,omitempty"` - // DefaultLoadDistributionPolicy - Default Load Distribution Policy resource of URL path map. - DefaultLoadDistributionPolicy *SubResource `json:"defaultLoadDistributionPolicy,omitempty"` - // PathRules - Path rule of URL path map resource. - PathRules *[]ApplicationGatewayPathRule `json:"pathRules,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the URL path map resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayURLPathMapPropertiesFormat. -func (agupmpf ApplicationGatewayURLPathMapPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agupmpf.DefaultBackendAddressPool != nil { - objectMap["defaultBackendAddressPool"] = agupmpf.DefaultBackendAddressPool - } - if agupmpf.DefaultBackendHTTPSettings != nil { - objectMap["defaultBackendHttpSettings"] = agupmpf.DefaultBackendHTTPSettings - } - if agupmpf.DefaultRewriteRuleSet != nil { - objectMap["defaultRewriteRuleSet"] = agupmpf.DefaultRewriteRuleSet - } - if agupmpf.DefaultRedirectConfiguration != nil { - objectMap["defaultRedirectConfiguration"] = agupmpf.DefaultRedirectConfiguration - } - if agupmpf.DefaultLoadDistributionPolicy != nil { - objectMap["defaultLoadDistributionPolicy"] = agupmpf.DefaultLoadDistributionPolicy - } - if agupmpf.PathRules != nil { - objectMap["pathRules"] = agupmpf.PathRules - } - return json.Marshal(objectMap) -} - -// ApplicationGatewayWafDynamicManifestPropertiesResult properties of ApplicationGatewayWafDynamicManifest. -type ApplicationGatewayWafDynamicManifestPropertiesResult struct { - // DefaultRuleSetPropertyFormat - The default ruleset. - *DefaultRuleSetPropertyFormat `json:"defaultRuleSet,omitempty"` - // AvailableRuleSets - The available rulesets. - AvailableRuleSets *[]ApplicationGatewayFirewallManifestRuleSet `json:"availableRuleSets,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayWafDynamicManifestPropertiesResult. -func (agwdmpr ApplicationGatewayWafDynamicManifestPropertiesResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agwdmpr.DefaultRuleSetPropertyFormat != nil { - objectMap["defaultRuleSet"] = agwdmpr.DefaultRuleSetPropertyFormat - } - if agwdmpr.AvailableRuleSets != nil { - objectMap["availableRuleSets"] = agwdmpr.AvailableRuleSets - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayWafDynamicManifestPropertiesResult struct. -func (agwdmpr *ApplicationGatewayWafDynamicManifestPropertiesResult) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "defaultRuleSet": - if v != nil { - var defaultRuleSetPropertyFormat DefaultRuleSetPropertyFormat - err = json.Unmarshal(*v, &defaultRuleSetPropertyFormat) - if err != nil { - return err - } - agwdmpr.DefaultRuleSetPropertyFormat = &defaultRuleSetPropertyFormat - } - case "availableRuleSets": - if v != nil { - var availableRuleSets []ApplicationGatewayFirewallManifestRuleSet - err = json.Unmarshal(*v, &availableRuleSets) - if err != nil { - return err - } - agwdmpr.AvailableRuleSets = &availableRuleSets - } - } - } - - return nil -} - -// ApplicationGatewayWafDynamicManifestResult response for ApplicationGatewayWafDynamicManifest API service -// call. -type ApplicationGatewayWafDynamicManifestResult struct { - autorest.Response `json:"-"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // ApplicationGatewayWafDynamicManifestPropertiesResult - Properties of the ApplicationGatewayWafDynamicManifest . - *ApplicationGatewayWafDynamicManifestPropertiesResult `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationGatewayWafDynamicManifestResult. -func (agwdmr ApplicationGatewayWafDynamicManifestResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if agwdmr.ID != nil { - objectMap["id"] = agwdmr.ID - } - if agwdmr.ApplicationGatewayWafDynamicManifestPropertiesResult != nil { - objectMap["properties"] = agwdmr.ApplicationGatewayWafDynamicManifestPropertiesResult - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationGatewayWafDynamicManifestResult struct. -func (agwdmr *ApplicationGatewayWafDynamicManifestResult) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - agwdmr.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - agwdmr.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - agwdmr.Type = &typeVar - } - case "properties": - if v != nil { - var applicationGatewayWafDynamicManifestPropertiesResult ApplicationGatewayWafDynamicManifestPropertiesResult - err = json.Unmarshal(*v, &applicationGatewayWafDynamicManifestPropertiesResult) - if err != nil { - return err - } - agwdmr.ApplicationGatewayWafDynamicManifestPropertiesResult = &applicationGatewayWafDynamicManifestPropertiesResult - } - } - } - - return nil -} - -// ApplicationGatewayWafDynamicManifestResultList response for ApplicationGatewayWafDynamicManifests API -// service call. -type ApplicationGatewayWafDynamicManifestResultList struct { - autorest.Response `json:"-"` - // Value - The list of application gateway waf manifest. - Value *[]ApplicationGatewayWafDynamicManifestResult `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ApplicationGatewayWafDynamicManifestResultListIterator provides access to a complete listing of -// ApplicationGatewayWafDynamicManifestResult values. -type ApplicationGatewayWafDynamicManifestResultListIterator struct { - i int - page ApplicationGatewayWafDynamicManifestResultListPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ApplicationGatewayWafDynamicManifestResultListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayWafDynamicManifestResultListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ApplicationGatewayWafDynamicManifestResultListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ApplicationGatewayWafDynamicManifestResultListIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ApplicationGatewayWafDynamicManifestResultListIterator) Response() ApplicationGatewayWafDynamicManifestResultList { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ApplicationGatewayWafDynamicManifestResultListIterator) Value() ApplicationGatewayWafDynamicManifestResult { - if !iter.page.NotDone() { - return ApplicationGatewayWafDynamicManifestResult{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ApplicationGatewayWafDynamicManifestResultListIterator type. -func NewApplicationGatewayWafDynamicManifestResultListIterator(page ApplicationGatewayWafDynamicManifestResultListPage) ApplicationGatewayWafDynamicManifestResultListIterator { - return ApplicationGatewayWafDynamicManifestResultListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (agwdmrl ApplicationGatewayWafDynamicManifestResultList) IsEmpty() bool { - return agwdmrl.Value == nil || len(*agwdmrl.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (agwdmrl ApplicationGatewayWafDynamicManifestResultList) hasNextLink() bool { - return agwdmrl.NextLink != nil && len(*agwdmrl.NextLink) != 0 -} - -// applicationGatewayWafDynamicManifestResultListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (agwdmrl ApplicationGatewayWafDynamicManifestResultList) applicationGatewayWafDynamicManifestResultListPreparer(ctx context.Context) (*http.Request, error) { - if !agwdmrl.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(agwdmrl.NextLink))) -} - -// ApplicationGatewayWafDynamicManifestResultListPage contains a page of -// ApplicationGatewayWafDynamicManifestResult values. -type ApplicationGatewayWafDynamicManifestResultListPage struct { - fn func(context.Context, ApplicationGatewayWafDynamicManifestResultList) (ApplicationGatewayWafDynamicManifestResultList, error) - agwdmrl ApplicationGatewayWafDynamicManifestResultList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ApplicationGatewayWafDynamicManifestResultListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationGatewayWafDynamicManifestResultListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.agwdmrl) - if err != nil { - return err - } - page.agwdmrl = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ApplicationGatewayWafDynamicManifestResultListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ApplicationGatewayWafDynamicManifestResultListPage) NotDone() bool { - return !page.agwdmrl.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ApplicationGatewayWafDynamicManifestResultListPage) Response() ApplicationGatewayWafDynamicManifestResultList { - return page.agwdmrl -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ApplicationGatewayWafDynamicManifestResultListPage) Values() []ApplicationGatewayWafDynamicManifestResult { - if page.agwdmrl.IsEmpty() { - return nil - } - return *page.agwdmrl.Value -} - -// Creates a new instance of the ApplicationGatewayWafDynamicManifestResultListPage type. -func NewApplicationGatewayWafDynamicManifestResultListPage(cur ApplicationGatewayWafDynamicManifestResultList, getNextPage func(context.Context, ApplicationGatewayWafDynamicManifestResultList) (ApplicationGatewayWafDynamicManifestResultList, error)) ApplicationGatewayWafDynamicManifestResultListPage { - return ApplicationGatewayWafDynamicManifestResultListPage{ - fn: getNextPage, - agwdmrl: cur, - } -} - -// ApplicationGatewayWebApplicationFirewallConfiguration application gateway web application firewall -// configuration. -type ApplicationGatewayWebApplicationFirewallConfiguration struct { - // Enabled - Whether the web application firewall is enabled or not. - Enabled *bool `json:"enabled,omitempty"` - // FirewallMode - Web application firewall mode. Possible values include: 'Detection', 'Prevention' - FirewallMode ApplicationGatewayFirewallMode `json:"firewallMode,omitempty"` - // RuleSetType - The type of the web application firewall rule set. Possible values are: 'OWASP'. - RuleSetType *string `json:"ruleSetType,omitempty"` - // RuleSetVersion - The version of the rule set type. - RuleSetVersion *string `json:"ruleSetVersion,omitempty"` - // DisabledRuleGroups - The disabled rule groups. - DisabledRuleGroups *[]ApplicationGatewayFirewallDisabledRuleGroup `json:"disabledRuleGroups,omitempty"` - // RequestBodyCheck - Whether allow WAF to check request Body. - RequestBodyCheck *bool `json:"requestBodyCheck,omitempty"` - // MaxRequestBodySize - Maximum request body size for WAF. - MaxRequestBodySize *int32 `json:"maxRequestBodySize,omitempty"` - // MaxRequestBodySizeInKb - Maximum request body size in Kb for WAF. - MaxRequestBodySizeInKb *int32 `json:"maxRequestBodySizeInKb,omitempty"` - // FileUploadLimitInMb - Maximum file upload size in Mb for WAF. - FileUploadLimitInMb *int32 `json:"fileUploadLimitInMb,omitempty"` - // Exclusions - The exclusion list. - Exclusions *[]ApplicationGatewayFirewallExclusion `json:"exclusions,omitempty"` -} - -// ApplicationRule rule of type application. -type ApplicationRule struct { - // SourceAddresses - List of source IP addresses for this rule. - SourceAddresses *[]string `json:"sourceAddresses,omitempty"` - // DestinationAddresses - List of destination IP addresses or Service Tags. - DestinationAddresses *[]string `json:"destinationAddresses,omitempty"` - // Protocols - Array of Application Protocols. - Protocols *[]FirewallPolicyRuleApplicationProtocol `json:"protocols,omitempty"` - // TargetFqdns - List of FQDNs for this rule. - TargetFqdns *[]string `json:"targetFqdns,omitempty"` - // TargetUrls - List of Urls for this rule condition. - TargetUrls *[]string `json:"targetUrls,omitempty"` - // FqdnTags - List of FQDN Tags for this rule. - FqdnTags *[]string `json:"fqdnTags,omitempty"` - // SourceIPGroups - List of source IpGroups for this rule. - SourceIPGroups *[]string `json:"sourceIpGroups,omitempty"` - // TerminateTLS - Terminate TLS connections for this rule. - TerminateTLS *bool `json:"terminateTLS,omitempty"` - // WebCategories - List of destination azure web categories. - WebCategories *[]string `json:"webCategories,omitempty"` - // Name - Name of the rule. - Name *string `json:"name,omitempty"` - // Description - Description of the rule. - Description *string `json:"description,omitempty"` - // RuleType - Possible values include: 'RuleTypeFirewallPolicyRule', 'RuleTypeApplicationRule', 'RuleTypeNatRule', 'RuleTypeNetworkRule' - RuleType RuleType `json:"ruleType,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationRule. -func (ar ApplicationRule) MarshalJSON() ([]byte, error) { - ar.RuleType = RuleTypeApplicationRule - objectMap := make(map[string]interface{}) - if ar.SourceAddresses != nil { - objectMap["sourceAddresses"] = ar.SourceAddresses - } - if ar.DestinationAddresses != nil { - objectMap["destinationAddresses"] = ar.DestinationAddresses - } - if ar.Protocols != nil { - objectMap["protocols"] = ar.Protocols - } - if ar.TargetFqdns != nil { - objectMap["targetFqdns"] = ar.TargetFqdns - } - if ar.TargetUrls != nil { - objectMap["targetUrls"] = ar.TargetUrls - } - if ar.FqdnTags != nil { - objectMap["fqdnTags"] = ar.FqdnTags - } - if ar.SourceIPGroups != nil { - objectMap["sourceIpGroups"] = ar.SourceIPGroups - } - if ar.TerminateTLS != nil { - objectMap["terminateTLS"] = ar.TerminateTLS - } - if ar.WebCategories != nil { - objectMap["webCategories"] = ar.WebCategories - } - if ar.Name != nil { - objectMap["name"] = ar.Name - } - if ar.Description != nil { - objectMap["description"] = ar.Description - } - if ar.RuleType != "" { - objectMap["ruleType"] = ar.RuleType - } - return json.Marshal(objectMap) -} - -// AsApplicationRule is the BasicFirewallPolicyRule implementation for ApplicationRule. -func (ar ApplicationRule) AsApplicationRule() (*ApplicationRule, bool) { - return &ar, true -} - -// AsNatRule is the BasicFirewallPolicyRule implementation for ApplicationRule. -func (ar ApplicationRule) AsNatRule() (*NatRule, bool) { - return nil, false -} - -// AsRule is the BasicFirewallPolicyRule implementation for ApplicationRule. -func (ar ApplicationRule) AsRule() (*Rule, bool) { - return nil, false -} - -// AsFirewallPolicyRule is the BasicFirewallPolicyRule implementation for ApplicationRule. -func (ar ApplicationRule) AsFirewallPolicyRule() (*FirewallPolicyRule, bool) { - return nil, false -} - -// AsBasicFirewallPolicyRule is the BasicFirewallPolicyRule implementation for ApplicationRule. -func (ar ApplicationRule) AsBasicFirewallPolicyRule() (BasicFirewallPolicyRule, bool) { - return &ar, true -} - -// ApplicationSecurityGroup an application security group in a resource group. -type ApplicationSecurityGroup struct { - autorest.Response `json:"-"` - // ApplicationSecurityGroupPropertiesFormat - Properties of the application security group. - *ApplicationSecurityGroupPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ApplicationSecurityGroup. -func (asg ApplicationSecurityGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if asg.ApplicationSecurityGroupPropertiesFormat != nil { - objectMap["properties"] = asg.ApplicationSecurityGroupPropertiesFormat - } - if asg.ID != nil { - objectMap["id"] = asg.ID - } - if asg.Location != nil { - objectMap["location"] = asg.Location - } - if asg.Tags != nil { - objectMap["tags"] = asg.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ApplicationSecurityGroup struct. -func (asg *ApplicationSecurityGroup) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var applicationSecurityGroupPropertiesFormat ApplicationSecurityGroupPropertiesFormat - err = json.Unmarshal(*v, &applicationSecurityGroupPropertiesFormat) - if err != nil { - return err - } - asg.ApplicationSecurityGroupPropertiesFormat = &applicationSecurityGroupPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - asg.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - asg.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - asg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - asg.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - asg.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - asg.Tags = tags - } - } - } - - return nil -} - -// ApplicationSecurityGroupListResult a list of application security groups. -type ApplicationSecurityGroupListResult struct { - autorest.Response `json:"-"` - // Value - A list of application security groups. - Value *[]ApplicationSecurityGroup `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationSecurityGroupListResult. -func (asglr ApplicationSecurityGroupListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if asglr.Value != nil { - objectMap["value"] = asglr.Value - } - return json.Marshal(objectMap) -} - -// ApplicationSecurityGroupListResultIterator provides access to a complete listing of -// ApplicationSecurityGroup values. -type ApplicationSecurityGroupListResultIterator struct { - i int - page ApplicationSecurityGroupListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ApplicationSecurityGroupListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ApplicationSecurityGroupListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ApplicationSecurityGroupListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ApplicationSecurityGroupListResultIterator) Response() ApplicationSecurityGroupListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ApplicationSecurityGroupListResultIterator) Value() ApplicationSecurityGroup { - if !iter.page.NotDone() { - return ApplicationSecurityGroup{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ApplicationSecurityGroupListResultIterator type. -func NewApplicationSecurityGroupListResultIterator(page ApplicationSecurityGroupListResultPage) ApplicationSecurityGroupListResultIterator { - return ApplicationSecurityGroupListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (asglr ApplicationSecurityGroupListResult) IsEmpty() bool { - return asglr.Value == nil || len(*asglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (asglr ApplicationSecurityGroupListResult) hasNextLink() bool { - return asglr.NextLink != nil && len(*asglr.NextLink) != 0 -} - -// applicationSecurityGroupListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (asglr ApplicationSecurityGroupListResult) applicationSecurityGroupListResultPreparer(ctx context.Context) (*http.Request, error) { - if !asglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(asglr.NextLink))) -} - -// ApplicationSecurityGroupListResultPage contains a page of ApplicationSecurityGroup values. -type ApplicationSecurityGroupListResultPage struct { - fn func(context.Context, ApplicationSecurityGroupListResult) (ApplicationSecurityGroupListResult, error) - asglr ApplicationSecurityGroupListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ApplicationSecurityGroupListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ApplicationSecurityGroupListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.asglr) - if err != nil { - return err - } - page.asglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ApplicationSecurityGroupListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ApplicationSecurityGroupListResultPage) NotDone() bool { - return !page.asglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ApplicationSecurityGroupListResultPage) Response() ApplicationSecurityGroupListResult { - return page.asglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ApplicationSecurityGroupListResultPage) Values() []ApplicationSecurityGroup { - if page.asglr.IsEmpty() { - return nil - } - return *page.asglr.Value -} - -// Creates a new instance of the ApplicationSecurityGroupListResultPage type. -func NewApplicationSecurityGroupListResultPage(cur ApplicationSecurityGroupListResult, getNextPage func(context.Context, ApplicationSecurityGroupListResult) (ApplicationSecurityGroupListResult, error)) ApplicationSecurityGroupListResultPage { - return ApplicationSecurityGroupListResultPage{ - fn: getNextPage, - asglr: cur, - } -} - -// ApplicationSecurityGroupPropertiesFormat application security group properties. -type ApplicationSecurityGroupPropertiesFormat struct { - // ResourceGUID - READ-ONLY; The resource GUID property of the application security group resource. It uniquely identifies a resource, even if the user changes its name or migrate the resource across subscriptions or resource groups. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the application security group resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ApplicationSecurityGroupPropertiesFormat. -func (asgpf ApplicationSecurityGroupPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ApplicationSecurityGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type ApplicationSecurityGroupsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationSecurityGroupsClient) (ApplicationSecurityGroup, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationSecurityGroupsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationSecurityGroupsCreateOrUpdateFuture.Result. -func (future *ApplicationSecurityGroupsCreateOrUpdateFuture) result(client ApplicationSecurityGroupsClient) (asg ApplicationSecurityGroup, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - asg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationSecurityGroupsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if asg.Response.Response, err = future.GetResult(sender); err == nil && asg.Response.Response.StatusCode != http.StatusNoContent { - asg, err = client.CreateOrUpdateResponder(asg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsCreateOrUpdateFuture", "Result", asg.Response.Response, "Failure responding to request") - } - } - return -} - -// ApplicationSecurityGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ApplicationSecurityGroupsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ApplicationSecurityGroupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ApplicationSecurityGroupsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ApplicationSecurityGroupsDeleteFuture.Result. -func (future *ApplicationSecurityGroupsDeleteFuture) result(client ApplicationSecurityGroupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationSecurityGroupsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ApplicationSecurityGroupsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// AuthorizationListResult response for ListAuthorizations API service call retrieves all authorizations -// that belongs to an ExpressRouteCircuit. -type AuthorizationListResult struct { - autorest.Response `json:"-"` - // Value - The authorizations in an ExpressRoute Circuit. - Value *[]ExpressRouteCircuitAuthorization `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// AuthorizationListResultIterator provides access to a complete listing of -// ExpressRouteCircuitAuthorization values. -type AuthorizationListResultIterator struct { - i int - page AuthorizationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AuthorizationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AuthorizationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AuthorizationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AuthorizationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AuthorizationListResultIterator) Response() AuthorizationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AuthorizationListResultIterator) Value() ExpressRouteCircuitAuthorization { - if !iter.page.NotDone() { - return ExpressRouteCircuitAuthorization{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AuthorizationListResultIterator type. -func NewAuthorizationListResultIterator(page AuthorizationListResultPage) AuthorizationListResultIterator { - return AuthorizationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (alr AuthorizationListResult) IsEmpty() bool { - return alr.Value == nil || len(*alr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (alr AuthorizationListResult) hasNextLink() bool { - return alr.NextLink != nil && len(*alr.NextLink) != 0 -} - -// authorizationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (alr AuthorizationListResult) authorizationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !alr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(alr.NextLink))) -} - -// AuthorizationListResultPage contains a page of ExpressRouteCircuitAuthorization values. -type AuthorizationListResultPage struct { - fn func(context.Context, AuthorizationListResult) (AuthorizationListResult, error) - alr AuthorizationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AuthorizationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AuthorizationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.alr) - if err != nil { - return err - } - page.alr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AuthorizationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AuthorizationListResultPage) NotDone() bool { - return !page.alr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AuthorizationListResultPage) Response() AuthorizationListResult { - return page.alr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AuthorizationListResultPage) Values() []ExpressRouteCircuitAuthorization { - if page.alr.IsEmpty() { - return nil - } - return *page.alr.Value -} - -// Creates a new instance of the AuthorizationListResultPage type. -func NewAuthorizationListResultPage(cur AuthorizationListResult, getNextPage func(context.Context, AuthorizationListResult) (AuthorizationListResult, error)) AuthorizationListResultPage { - return AuthorizationListResultPage{ - fn: getNextPage, - alr: cur, - } -} - -// AuthorizationPropertiesFormat properties of ExpressRouteCircuitAuthorization. -type AuthorizationPropertiesFormat struct { - // AuthorizationKey - The authorization key. - AuthorizationKey *string `json:"authorizationKey,omitempty"` - // AuthorizationUseStatus - The authorization use status. Possible values include: 'Available', 'InUse' - AuthorizationUseStatus AuthorizationUseStatus `json:"authorizationUseStatus,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the authorization resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for AuthorizationPropertiesFormat. -func (apf AuthorizationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if apf.AuthorizationKey != nil { - objectMap["authorizationKey"] = apf.AuthorizationKey - } - if apf.AuthorizationUseStatus != "" { - objectMap["authorizationUseStatus"] = apf.AuthorizationUseStatus - } - return json.Marshal(objectMap) -} - -// AutoApprovedPrivateLinkService the information of an AutoApprovedPrivateLinkService. -type AutoApprovedPrivateLinkService struct { - // PrivateLinkService - The id of the private link service resource. - PrivateLinkService *string `json:"privateLinkService,omitempty"` -} - -// AutoApprovedPrivateLinkServicesResult an array of private link service id that can be linked to a -// private end point with auto approved. -type AutoApprovedPrivateLinkServicesResult struct { - autorest.Response `json:"-"` - // Value - An array of auto approved private link service. - Value *[]AutoApprovedPrivateLinkService `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for AutoApprovedPrivateLinkServicesResult. -func (aaplsr AutoApprovedPrivateLinkServicesResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if aaplsr.Value != nil { - objectMap["value"] = aaplsr.Value - } - return json.Marshal(objectMap) -} - -// AutoApprovedPrivateLinkServicesResultIterator provides access to a complete listing of -// AutoApprovedPrivateLinkService values. -type AutoApprovedPrivateLinkServicesResultIterator struct { - i int - page AutoApprovedPrivateLinkServicesResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AutoApprovedPrivateLinkServicesResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AutoApprovedPrivateLinkServicesResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AutoApprovedPrivateLinkServicesResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AutoApprovedPrivateLinkServicesResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AutoApprovedPrivateLinkServicesResultIterator) Response() AutoApprovedPrivateLinkServicesResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AutoApprovedPrivateLinkServicesResultIterator) Value() AutoApprovedPrivateLinkService { - if !iter.page.NotDone() { - return AutoApprovedPrivateLinkService{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AutoApprovedPrivateLinkServicesResultIterator type. -func NewAutoApprovedPrivateLinkServicesResultIterator(page AutoApprovedPrivateLinkServicesResultPage) AutoApprovedPrivateLinkServicesResultIterator { - return AutoApprovedPrivateLinkServicesResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (aaplsr AutoApprovedPrivateLinkServicesResult) IsEmpty() bool { - return aaplsr.Value == nil || len(*aaplsr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (aaplsr AutoApprovedPrivateLinkServicesResult) hasNextLink() bool { - return aaplsr.NextLink != nil && len(*aaplsr.NextLink) != 0 -} - -// autoApprovedPrivateLinkServicesResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (aaplsr AutoApprovedPrivateLinkServicesResult) autoApprovedPrivateLinkServicesResultPreparer(ctx context.Context) (*http.Request, error) { - if !aaplsr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(aaplsr.NextLink))) -} - -// AutoApprovedPrivateLinkServicesResultPage contains a page of AutoApprovedPrivateLinkService values. -type AutoApprovedPrivateLinkServicesResultPage struct { - fn func(context.Context, AutoApprovedPrivateLinkServicesResult) (AutoApprovedPrivateLinkServicesResult, error) - aaplsr AutoApprovedPrivateLinkServicesResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AutoApprovedPrivateLinkServicesResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AutoApprovedPrivateLinkServicesResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.aaplsr) - if err != nil { - return err - } - page.aaplsr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AutoApprovedPrivateLinkServicesResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AutoApprovedPrivateLinkServicesResultPage) NotDone() bool { - return !page.aaplsr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AutoApprovedPrivateLinkServicesResultPage) Response() AutoApprovedPrivateLinkServicesResult { - return page.aaplsr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AutoApprovedPrivateLinkServicesResultPage) Values() []AutoApprovedPrivateLinkService { - if page.aaplsr.IsEmpty() { - return nil - } - return *page.aaplsr.Value -} - -// Creates a new instance of the AutoApprovedPrivateLinkServicesResultPage type. -func NewAutoApprovedPrivateLinkServicesResultPage(cur AutoApprovedPrivateLinkServicesResult, getNextPage func(context.Context, AutoApprovedPrivateLinkServicesResult) (AutoApprovedPrivateLinkServicesResult, error)) AutoApprovedPrivateLinkServicesResultPage { - return AutoApprovedPrivateLinkServicesResultPage{ - fn: getNextPage, - aaplsr: cur, - } -} - -// Availability availability of the metric. -type Availability struct { - // TimeGrain - The time grain of the availability. - TimeGrain *string `json:"timeGrain,omitempty"` - // Retention - The retention of the availability. - Retention *string `json:"retention,omitempty"` - // BlobDuration - Duration of the availability blob. - BlobDuration *string `json:"blobDuration,omitempty"` -} - -// AvailableDelegation the serviceName of an AvailableDelegation indicates a possible delegation for a -// subnet. -type AvailableDelegation struct { - // Name - The name of the AvailableDelegation resource. - Name *string `json:"name,omitempty"` - // ID - A unique identifier of the AvailableDelegation resource. - ID *string `json:"id,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // ServiceName - The name of the service and resource. - ServiceName *string `json:"serviceName,omitempty"` - // Actions - The actions permitted to the service upon delegation. - Actions *[]string `json:"actions,omitempty"` -} - -// AvailableDelegationsResult an array of available delegations. -type AvailableDelegationsResult struct { - autorest.Response `json:"-"` - // Value - An array of available delegations. - Value *[]AvailableDelegation `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for AvailableDelegationsResult. -func (adr AvailableDelegationsResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if adr.Value != nil { - objectMap["value"] = adr.Value - } - return json.Marshal(objectMap) -} - -// AvailableDelegationsResultIterator provides access to a complete listing of AvailableDelegation values. -type AvailableDelegationsResultIterator struct { - i int - page AvailableDelegationsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AvailableDelegationsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableDelegationsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AvailableDelegationsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AvailableDelegationsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AvailableDelegationsResultIterator) Response() AvailableDelegationsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AvailableDelegationsResultIterator) Value() AvailableDelegation { - if !iter.page.NotDone() { - return AvailableDelegation{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AvailableDelegationsResultIterator type. -func NewAvailableDelegationsResultIterator(page AvailableDelegationsResultPage) AvailableDelegationsResultIterator { - return AvailableDelegationsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (adr AvailableDelegationsResult) IsEmpty() bool { - return adr.Value == nil || len(*adr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (adr AvailableDelegationsResult) hasNextLink() bool { - return adr.NextLink != nil && len(*adr.NextLink) != 0 -} - -// availableDelegationsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (adr AvailableDelegationsResult) availableDelegationsResultPreparer(ctx context.Context) (*http.Request, error) { - if !adr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(adr.NextLink))) -} - -// AvailableDelegationsResultPage contains a page of AvailableDelegation values. -type AvailableDelegationsResultPage struct { - fn func(context.Context, AvailableDelegationsResult) (AvailableDelegationsResult, error) - adr AvailableDelegationsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AvailableDelegationsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableDelegationsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.adr) - if err != nil { - return err - } - page.adr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AvailableDelegationsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AvailableDelegationsResultPage) NotDone() bool { - return !page.adr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AvailableDelegationsResultPage) Response() AvailableDelegationsResult { - return page.adr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AvailableDelegationsResultPage) Values() []AvailableDelegation { - if page.adr.IsEmpty() { - return nil - } - return *page.adr.Value -} - -// Creates a new instance of the AvailableDelegationsResultPage type. -func NewAvailableDelegationsResultPage(cur AvailableDelegationsResult, getNextPage func(context.Context, AvailableDelegationsResult) (AvailableDelegationsResult, error)) AvailableDelegationsResultPage { - return AvailableDelegationsResultPage{ - fn: getNextPage, - adr: cur, - } -} - -// AvailablePrivateEndpointType the information of an AvailablePrivateEndpointType. -type AvailablePrivateEndpointType struct { - // Name - The name of the service and resource. - Name *string `json:"name,omitempty"` - // ID - A unique identifier of the AvailablePrivateEndpoint Type resource. - ID *string `json:"id,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // ResourceName - The name of the service and resource. - ResourceName *string `json:"resourceName,omitempty"` - // DisplayName - Display name of the resource. - DisplayName *string `json:"displayName,omitempty"` -} - -// AvailablePrivateEndpointTypesResult an array of available PrivateEndpoint types. -type AvailablePrivateEndpointTypesResult struct { - autorest.Response `json:"-"` - // Value - An array of available privateEndpoint type. - Value *[]AvailablePrivateEndpointType `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for AvailablePrivateEndpointTypesResult. -func (apetr AvailablePrivateEndpointTypesResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if apetr.Value != nil { - objectMap["value"] = apetr.Value - } - return json.Marshal(objectMap) -} - -// AvailablePrivateEndpointTypesResultIterator provides access to a complete listing of -// AvailablePrivateEndpointType values. -type AvailablePrivateEndpointTypesResultIterator struct { - i int - page AvailablePrivateEndpointTypesResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AvailablePrivateEndpointTypesResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailablePrivateEndpointTypesResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AvailablePrivateEndpointTypesResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AvailablePrivateEndpointTypesResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AvailablePrivateEndpointTypesResultIterator) Response() AvailablePrivateEndpointTypesResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AvailablePrivateEndpointTypesResultIterator) Value() AvailablePrivateEndpointType { - if !iter.page.NotDone() { - return AvailablePrivateEndpointType{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AvailablePrivateEndpointTypesResultIterator type. -func NewAvailablePrivateEndpointTypesResultIterator(page AvailablePrivateEndpointTypesResultPage) AvailablePrivateEndpointTypesResultIterator { - return AvailablePrivateEndpointTypesResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (apetr AvailablePrivateEndpointTypesResult) IsEmpty() bool { - return apetr.Value == nil || len(*apetr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (apetr AvailablePrivateEndpointTypesResult) hasNextLink() bool { - return apetr.NextLink != nil && len(*apetr.NextLink) != 0 -} - -// availablePrivateEndpointTypesResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (apetr AvailablePrivateEndpointTypesResult) availablePrivateEndpointTypesResultPreparer(ctx context.Context) (*http.Request, error) { - if !apetr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(apetr.NextLink))) -} - -// AvailablePrivateEndpointTypesResultPage contains a page of AvailablePrivateEndpointType values. -type AvailablePrivateEndpointTypesResultPage struct { - fn func(context.Context, AvailablePrivateEndpointTypesResult) (AvailablePrivateEndpointTypesResult, error) - apetr AvailablePrivateEndpointTypesResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AvailablePrivateEndpointTypesResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailablePrivateEndpointTypesResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.apetr) - if err != nil { - return err - } - page.apetr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AvailablePrivateEndpointTypesResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AvailablePrivateEndpointTypesResultPage) NotDone() bool { - return !page.apetr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AvailablePrivateEndpointTypesResultPage) Response() AvailablePrivateEndpointTypesResult { - return page.apetr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AvailablePrivateEndpointTypesResultPage) Values() []AvailablePrivateEndpointType { - if page.apetr.IsEmpty() { - return nil - } - return *page.apetr.Value -} - -// Creates a new instance of the AvailablePrivateEndpointTypesResultPage type. -func NewAvailablePrivateEndpointTypesResultPage(cur AvailablePrivateEndpointTypesResult, getNextPage func(context.Context, AvailablePrivateEndpointTypesResult) (AvailablePrivateEndpointTypesResult, error)) AvailablePrivateEndpointTypesResultPage { - return AvailablePrivateEndpointTypesResultPage{ - fn: getNextPage, - apetr: cur, - } -} - -// AvailableProvidersList list of available countries with details. -type AvailableProvidersList struct { - autorest.Response `json:"-"` - // Countries - List of available countries. - Countries *[]AvailableProvidersListCountry `json:"countries,omitempty"` -} - -// AvailableProvidersListCity city or town details. -type AvailableProvidersListCity struct { - // CityName - The city or town name. - CityName *string `json:"cityName,omitempty"` - // Providers - A list of Internet service providers. - Providers *[]string `json:"providers,omitempty"` -} - -// AvailableProvidersListCountry country details. -type AvailableProvidersListCountry struct { - // CountryName - The country name. - CountryName *string `json:"countryName,omitempty"` - // Providers - A list of Internet service providers. - Providers *[]string `json:"providers,omitempty"` - // States - List of available states in the country. - States *[]AvailableProvidersListState `json:"states,omitempty"` -} - -// AvailableProvidersListParameters constraints that determine the list of available Internet service -// providers. -type AvailableProvidersListParameters struct { - // AzureLocations - A list of Azure regions. - AzureLocations *[]string `json:"azureLocations,omitempty"` - // Country - The country for available providers list. - Country *string `json:"country,omitempty"` - // State - The state for available providers list. - State *string `json:"state,omitempty"` - // City - The city or town for available providers list. - City *string `json:"city,omitempty"` -} - -// AvailableProvidersListState state details. -type AvailableProvidersListState struct { - // StateName - The state name. - StateName *string `json:"stateName,omitempty"` - // Providers - A list of Internet service providers. - Providers *[]string `json:"providers,omitempty"` - // Cities - List of available cities or towns in the state. - Cities *[]AvailableProvidersListCity `json:"cities,omitempty"` -} - -// AvailableServiceAlias the available service alias. -type AvailableServiceAlias struct { - // Name - The name of the service alias. - Name *string `json:"name,omitempty"` - // ID - The ID of the service alias. - ID *string `json:"id,omitempty"` - // Type - The type of the resource. - Type *string `json:"type,omitempty"` - // ResourceName - The resource name of the service alias. - ResourceName *string `json:"resourceName,omitempty"` -} - -// AvailableServiceAliasesResult an array of available service aliases. -type AvailableServiceAliasesResult struct { - autorest.Response `json:"-"` - // Value - An array of available service aliases. - Value *[]AvailableServiceAlias `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for AvailableServiceAliasesResult. -func (asar AvailableServiceAliasesResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if asar.Value != nil { - objectMap["value"] = asar.Value - } - return json.Marshal(objectMap) -} - -// AvailableServiceAliasesResultIterator provides access to a complete listing of AvailableServiceAlias -// values. -type AvailableServiceAliasesResultIterator struct { - i int - page AvailableServiceAliasesResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AvailableServiceAliasesResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableServiceAliasesResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AvailableServiceAliasesResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AvailableServiceAliasesResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AvailableServiceAliasesResultIterator) Response() AvailableServiceAliasesResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AvailableServiceAliasesResultIterator) Value() AvailableServiceAlias { - if !iter.page.NotDone() { - return AvailableServiceAlias{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AvailableServiceAliasesResultIterator type. -func NewAvailableServiceAliasesResultIterator(page AvailableServiceAliasesResultPage) AvailableServiceAliasesResultIterator { - return AvailableServiceAliasesResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (asar AvailableServiceAliasesResult) IsEmpty() bool { - return asar.Value == nil || len(*asar.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (asar AvailableServiceAliasesResult) hasNextLink() bool { - return asar.NextLink != nil && len(*asar.NextLink) != 0 -} - -// availableServiceAliasesResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (asar AvailableServiceAliasesResult) availableServiceAliasesResultPreparer(ctx context.Context) (*http.Request, error) { - if !asar.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(asar.NextLink))) -} - -// AvailableServiceAliasesResultPage contains a page of AvailableServiceAlias values. -type AvailableServiceAliasesResultPage struct { - fn func(context.Context, AvailableServiceAliasesResult) (AvailableServiceAliasesResult, error) - asar AvailableServiceAliasesResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AvailableServiceAliasesResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AvailableServiceAliasesResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.asar) - if err != nil { - return err - } - page.asar = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AvailableServiceAliasesResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AvailableServiceAliasesResultPage) NotDone() bool { - return !page.asar.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AvailableServiceAliasesResultPage) Response() AvailableServiceAliasesResult { - return page.asar -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AvailableServiceAliasesResultPage) Values() []AvailableServiceAlias { - if page.asar.IsEmpty() { - return nil - } - return *page.asar.Value -} - -// Creates a new instance of the AvailableServiceAliasesResultPage type. -func NewAvailableServiceAliasesResultPage(cur AvailableServiceAliasesResult, getNextPage func(context.Context, AvailableServiceAliasesResult) (AvailableServiceAliasesResult, error)) AvailableServiceAliasesResultPage { - return AvailableServiceAliasesResultPage{ - fn: getNextPage, - asar: cur, - } -} - -// AzureAsyncOperationResult 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. -type AzureAsyncOperationResult struct { - // Status - Status of the Azure async operation. Possible values include: 'OperationStatusInProgress', 'OperationStatusSucceeded', 'OperationStatusFailed' - Status OperationStatus `json:"status,omitempty"` - // Error - Details of the error occurred during specified asynchronous operation. - Error *Error `json:"error,omitempty"` -} - -// AzureFirewall azure Firewall resource. -type AzureFirewall struct { - autorest.Response `json:"-"` - // AzureFirewallPropertiesFormat - Properties of the azure firewall. - *AzureFirewallPropertiesFormat `json:"properties,omitempty"` - // Zones - A list of availability zones denoting where the resource needs to come from. - Zones *[]string `json:"zones,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for AzureFirewall. -func (af AzureFirewall) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if af.AzureFirewallPropertiesFormat != nil { - objectMap["properties"] = af.AzureFirewallPropertiesFormat - } - if af.Zones != nil { - objectMap["zones"] = af.Zones - } - if af.ID != nil { - objectMap["id"] = af.ID - } - if af.Location != nil { - objectMap["location"] = af.Location - } - if af.Tags != nil { - objectMap["tags"] = af.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AzureFirewall struct. -func (af *AzureFirewall) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var azureFirewallPropertiesFormat AzureFirewallPropertiesFormat - err = json.Unmarshal(*v, &azureFirewallPropertiesFormat) - if err != nil { - return err - } - af.AzureFirewallPropertiesFormat = &azureFirewallPropertiesFormat - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - af.Zones = &zones - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - af.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - af.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - af.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - af.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - af.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - af.Tags = tags - } - } - } - - return nil -} - -// AzureFirewallApplicationRule properties of an application rule. -type AzureFirewallApplicationRule struct { - // Name - Name of the application rule. - Name *string `json:"name,omitempty"` - // Description - Description of the rule. - Description *string `json:"description,omitempty"` - // SourceAddresses - List of source IP addresses for this rule. - SourceAddresses *[]string `json:"sourceAddresses,omitempty"` - // Protocols - Array of ApplicationRuleProtocols. - Protocols *[]AzureFirewallApplicationRuleProtocol `json:"protocols,omitempty"` - // TargetFqdns - List of FQDNs for this rule. - TargetFqdns *[]string `json:"targetFqdns,omitempty"` - // FqdnTags - List of FQDN Tags for this rule. - FqdnTags *[]string `json:"fqdnTags,omitempty"` - // SourceIPGroups - List of source IpGroups for this rule. - SourceIPGroups *[]string `json:"sourceIpGroups,omitempty"` -} - -// AzureFirewallApplicationRuleCollection application rule collection resource. -type AzureFirewallApplicationRuleCollection struct { - // AzureFirewallApplicationRuleCollectionPropertiesFormat - Properties of the azure firewall application rule collection. - *AzureFirewallApplicationRuleCollectionPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within the Azure firewall. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallApplicationRuleCollection. -func (afarc AzureFirewallApplicationRuleCollection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afarc.AzureFirewallApplicationRuleCollectionPropertiesFormat != nil { - objectMap["properties"] = afarc.AzureFirewallApplicationRuleCollectionPropertiesFormat - } - if afarc.Name != nil { - objectMap["name"] = afarc.Name - } - if afarc.ID != nil { - objectMap["id"] = afarc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AzureFirewallApplicationRuleCollection struct. -func (afarc *AzureFirewallApplicationRuleCollection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var azureFirewallApplicationRuleCollectionPropertiesFormat AzureFirewallApplicationRuleCollectionPropertiesFormat - err = json.Unmarshal(*v, &azureFirewallApplicationRuleCollectionPropertiesFormat) - if err != nil { - return err - } - afarc.AzureFirewallApplicationRuleCollectionPropertiesFormat = &azureFirewallApplicationRuleCollectionPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - afarc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - afarc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - afarc.ID = &ID - } - } - } - - return nil -} - -// AzureFirewallApplicationRuleCollectionPropertiesFormat properties of the application rule collection. -type AzureFirewallApplicationRuleCollectionPropertiesFormat struct { - // Priority - Priority of the application rule collection resource. - Priority *int32 `json:"priority,omitempty"` - // Action - The action type of a rule collection. - Action *AzureFirewallRCAction `json:"action,omitempty"` - // Rules - Collection of rules used by a application rule collection. - Rules *[]AzureFirewallApplicationRule `json:"rules,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the application rule collection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallApplicationRuleCollectionPropertiesFormat. -func (afarcpf AzureFirewallApplicationRuleCollectionPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afarcpf.Priority != nil { - objectMap["priority"] = afarcpf.Priority - } - if afarcpf.Action != nil { - objectMap["action"] = afarcpf.Action - } - if afarcpf.Rules != nil { - objectMap["rules"] = afarcpf.Rules - } - return json.Marshal(objectMap) -} - -// AzureFirewallApplicationRuleProtocol properties of the application rule protocol. -type AzureFirewallApplicationRuleProtocol struct { - // ProtocolType - Protocol type. Possible values include: 'AzureFirewallApplicationRuleProtocolTypeHTTP', 'AzureFirewallApplicationRuleProtocolTypeHTTPS', 'AzureFirewallApplicationRuleProtocolTypeMssql' - ProtocolType AzureFirewallApplicationRuleProtocolType `json:"protocolType,omitempty"` - // Port - Port number for the protocol, cannot be greater than 64000. This field is optional. - Port *int32 `json:"port,omitempty"` -} - -// AzureFirewallFqdnTag azure Firewall FQDN Tag Resource. -type AzureFirewallFqdnTag struct { - // AzureFirewallFqdnTagPropertiesFormat - Properties of the azure firewall FQDN tag. - *AzureFirewallFqdnTagPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallFqdnTag. -func (afft AzureFirewallFqdnTag) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afft.AzureFirewallFqdnTagPropertiesFormat != nil { - objectMap["properties"] = afft.AzureFirewallFqdnTagPropertiesFormat - } - if afft.ID != nil { - objectMap["id"] = afft.ID - } - if afft.Location != nil { - objectMap["location"] = afft.Location - } - if afft.Tags != nil { - objectMap["tags"] = afft.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AzureFirewallFqdnTag struct. -func (afft *AzureFirewallFqdnTag) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var azureFirewallFqdnTagPropertiesFormat AzureFirewallFqdnTagPropertiesFormat - err = json.Unmarshal(*v, &azureFirewallFqdnTagPropertiesFormat) - if err != nil { - return err - } - afft.AzureFirewallFqdnTagPropertiesFormat = &azureFirewallFqdnTagPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - afft.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - afft.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - afft.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - afft.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - afft.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - afft.Tags = tags - } - } - } - - return nil -} - -// AzureFirewallFqdnTagListResult response for ListAzureFirewallFqdnTags API service call. -type AzureFirewallFqdnTagListResult struct { - autorest.Response `json:"-"` - // Value - List of Azure Firewall FQDN Tags in a resource group. - Value *[]AzureFirewallFqdnTag `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// AzureFirewallFqdnTagListResultIterator provides access to a complete listing of AzureFirewallFqdnTag -// values. -type AzureFirewallFqdnTagListResultIterator struct { - i int - page AzureFirewallFqdnTagListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AzureFirewallFqdnTagListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallFqdnTagListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AzureFirewallFqdnTagListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AzureFirewallFqdnTagListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AzureFirewallFqdnTagListResultIterator) Response() AzureFirewallFqdnTagListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AzureFirewallFqdnTagListResultIterator) Value() AzureFirewallFqdnTag { - if !iter.page.NotDone() { - return AzureFirewallFqdnTag{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AzureFirewallFqdnTagListResultIterator type. -func NewAzureFirewallFqdnTagListResultIterator(page AzureFirewallFqdnTagListResultPage) AzureFirewallFqdnTagListResultIterator { - return AzureFirewallFqdnTagListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (afftlr AzureFirewallFqdnTagListResult) IsEmpty() bool { - return afftlr.Value == nil || len(*afftlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (afftlr AzureFirewallFqdnTagListResult) hasNextLink() bool { - return afftlr.NextLink != nil && len(*afftlr.NextLink) != 0 -} - -// azureFirewallFqdnTagListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (afftlr AzureFirewallFqdnTagListResult) azureFirewallFqdnTagListResultPreparer(ctx context.Context) (*http.Request, error) { - if !afftlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(afftlr.NextLink))) -} - -// AzureFirewallFqdnTagListResultPage contains a page of AzureFirewallFqdnTag values. -type AzureFirewallFqdnTagListResultPage struct { - fn func(context.Context, AzureFirewallFqdnTagListResult) (AzureFirewallFqdnTagListResult, error) - afftlr AzureFirewallFqdnTagListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AzureFirewallFqdnTagListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallFqdnTagListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.afftlr) - if err != nil { - return err - } - page.afftlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AzureFirewallFqdnTagListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AzureFirewallFqdnTagListResultPage) NotDone() bool { - return !page.afftlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AzureFirewallFqdnTagListResultPage) Response() AzureFirewallFqdnTagListResult { - return page.afftlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AzureFirewallFqdnTagListResultPage) Values() []AzureFirewallFqdnTag { - if page.afftlr.IsEmpty() { - return nil - } - return *page.afftlr.Value -} - -// Creates a new instance of the AzureFirewallFqdnTagListResultPage type. -func NewAzureFirewallFqdnTagListResultPage(cur AzureFirewallFqdnTagListResult, getNextPage func(context.Context, AzureFirewallFqdnTagListResult) (AzureFirewallFqdnTagListResult, error)) AzureFirewallFqdnTagListResultPage { - return AzureFirewallFqdnTagListResultPage{ - fn: getNextPage, - afftlr: cur, - } -} - -// AzureFirewallFqdnTagPropertiesFormat azure Firewall FQDN Tag Properties. -type AzureFirewallFqdnTagPropertiesFormat struct { - // ProvisioningState - READ-ONLY; The provisioning state of the Azure firewall FQDN tag resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // FqdnTagName - READ-ONLY; The name of this FQDN Tag. - FqdnTagName *string `json:"fqdnTagName,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallFqdnTagPropertiesFormat. -func (afftpf AzureFirewallFqdnTagPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// AzureFirewallIPConfiguration IP configuration of an Azure Firewall. -type AzureFirewallIPConfiguration struct { - // AzureFirewallIPConfigurationPropertiesFormat - Properties of the azure firewall IP configuration. - *AzureFirewallIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallIPConfiguration. -func (afic AzureFirewallIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afic.AzureFirewallIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = afic.AzureFirewallIPConfigurationPropertiesFormat - } - if afic.Name != nil { - objectMap["name"] = afic.Name - } - if afic.ID != nil { - objectMap["id"] = afic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AzureFirewallIPConfiguration struct. -func (afic *AzureFirewallIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var azureFirewallIPConfigurationPropertiesFormat AzureFirewallIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &azureFirewallIPConfigurationPropertiesFormat) - if err != nil { - return err - } - afic.AzureFirewallIPConfigurationPropertiesFormat = &azureFirewallIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - afic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - afic.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - afic.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - afic.ID = &ID - } - } - } - - return nil -} - -// AzureFirewallIPConfigurationPropertiesFormat properties of IP configuration of an Azure Firewall. -type AzureFirewallIPConfigurationPropertiesFormat struct { - // PrivateIPAddress - READ-ONLY; The Firewall Internal Load Balancer IP to be used as the next hop in User Defined Routes. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // Subnet - Reference to the subnet resource. This resource must be named 'AzureFirewallSubnet' or 'AzureFirewallManagementSubnet'. - Subnet *SubResource `json:"subnet,omitempty"` - // PublicIPAddress - Reference to the PublicIP resource. This field is a mandatory input if subnet is not null. - PublicIPAddress *SubResource `json:"publicIPAddress,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the Azure firewall IP configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallIPConfigurationPropertiesFormat. -func (aficpf AzureFirewallIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if aficpf.Subnet != nil { - objectMap["subnet"] = aficpf.Subnet - } - if aficpf.PublicIPAddress != nil { - objectMap["publicIPAddress"] = aficpf.PublicIPAddress - } - return json.Marshal(objectMap) -} - -// AzureFirewallIPGroups ipGroups associated with azure firewall. -type AzureFirewallIPGroups struct { - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // ChangeNumber - READ-ONLY; The iteration number. - ChangeNumber *string `json:"changeNumber,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallIPGroups. -func (afig AzureFirewallIPGroups) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// AzureFirewallListResult response for ListAzureFirewalls API service call. -type AzureFirewallListResult struct { - autorest.Response `json:"-"` - // Value - List of Azure Firewalls in a resource group. - Value *[]AzureFirewall `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// AzureFirewallListResultIterator provides access to a complete listing of AzureFirewall values. -type AzureFirewallListResultIterator struct { - i int - page AzureFirewallListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AzureFirewallListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AzureFirewallListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AzureFirewallListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AzureFirewallListResultIterator) Response() AzureFirewallListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AzureFirewallListResultIterator) Value() AzureFirewall { - if !iter.page.NotDone() { - return AzureFirewall{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AzureFirewallListResultIterator type. -func NewAzureFirewallListResultIterator(page AzureFirewallListResultPage) AzureFirewallListResultIterator { - return AzureFirewallListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (aflr AzureFirewallListResult) IsEmpty() bool { - return aflr.Value == nil || len(*aflr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (aflr AzureFirewallListResult) hasNextLink() bool { - return aflr.NextLink != nil && len(*aflr.NextLink) != 0 -} - -// azureFirewallListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (aflr AzureFirewallListResult) azureFirewallListResultPreparer(ctx context.Context) (*http.Request, error) { - if !aflr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(aflr.NextLink))) -} - -// AzureFirewallListResultPage contains a page of AzureFirewall values. -type AzureFirewallListResultPage struct { - fn func(context.Context, AzureFirewallListResult) (AzureFirewallListResult, error) - aflr AzureFirewallListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AzureFirewallListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureFirewallListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.aflr) - if err != nil { - return err - } - page.aflr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AzureFirewallListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AzureFirewallListResultPage) NotDone() bool { - return !page.aflr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AzureFirewallListResultPage) Response() AzureFirewallListResult { - return page.aflr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AzureFirewallListResultPage) Values() []AzureFirewall { - if page.aflr.IsEmpty() { - return nil - } - return *page.aflr.Value -} - -// Creates a new instance of the AzureFirewallListResultPage type. -func NewAzureFirewallListResultPage(cur AzureFirewallListResult, getNextPage func(context.Context, AzureFirewallListResult) (AzureFirewallListResult, error)) AzureFirewallListResultPage { - return AzureFirewallListResultPage{ - fn: getNextPage, - aflr: cur, - } -} - -// AzureFirewallNatRCAction azureFirewall NAT Rule Collection Action. -type AzureFirewallNatRCAction struct { - // Type - The type of action. Possible values include: 'Snat', 'Dnat' - Type AzureFirewallNatRCActionType `json:"type,omitempty"` -} - -// AzureFirewallNatRule properties of a NAT rule. -type AzureFirewallNatRule struct { - // Name - Name of the NAT rule. - Name *string `json:"name,omitempty"` - // Description - Description of the rule. - Description *string `json:"description,omitempty"` - // SourceAddresses - List of source IP addresses for this rule. - SourceAddresses *[]string `json:"sourceAddresses,omitempty"` - // DestinationAddresses - List of destination IP addresses for this rule. Supports IP ranges, prefixes, and service tags. - DestinationAddresses *[]string `json:"destinationAddresses,omitempty"` - // DestinationPorts - List of destination ports. - DestinationPorts *[]string `json:"destinationPorts,omitempty"` - // Protocols - Array of AzureFirewallNetworkRuleProtocols applicable to this NAT rule. - Protocols *[]AzureFirewallNetworkRuleProtocol `json:"protocols,omitempty"` - // TranslatedAddress - The translated address for this NAT rule. - TranslatedAddress *string `json:"translatedAddress,omitempty"` - // TranslatedPort - The translated port for this NAT rule. - TranslatedPort *string `json:"translatedPort,omitempty"` - // TranslatedFqdn - The translated FQDN for this NAT rule. - TranslatedFqdn *string `json:"translatedFqdn,omitempty"` - // SourceIPGroups - List of source IpGroups for this rule. - SourceIPGroups *[]string `json:"sourceIpGroups,omitempty"` -} - -// AzureFirewallNatRuleCollection NAT rule collection resource. -type AzureFirewallNatRuleCollection struct { - // AzureFirewallNatRuleCollectionProperties - Properties of the azure firewall NAT rule collection. - *AzureFirewallNatRuleCollectionProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within the Azure firewall. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallNatRuleCollection. -func (afnrc AzureFirewallNatRuleCollection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afnrc.AzureFirewallNatRuleCollectionProperties != nil { - objectMap["properties"] = afnrc.AzureFirewallNatRuleCollectionProperties - } - if afnrc.Name != nil { - objectMap["name"] = afnrc.Name - } - if afnrc.ID != nil { - objectMap["id"] = afnrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AzureFirewallNatRuleCollection struct. -func (afnrc *AzureFirewallNatRuleCollection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var azureFirewallNatRuleCollectionProperties AzureFirewallNatRuleCollectionProperties - err = json.Unmarshal(*v, &azureFirewallNatRuleCollectionProperties) - if err != nil { - return err - } - afnrc.AzureFirewallNatRuleCollectionProperties = &azureFirewallNatRuleCollectionProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - afnrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - afnrc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - afnrc.ID = &ID - } - } - } - - return nil -} - -// AzureFirewallNatRuleCollectionProperties properties of the NAT rule collection. -type AzureFirewallNatRuleCollectionProperties struct { - // Priority - Priority of the NAT rule collection resource. - Priority *int32 `json:"priority,omitempty"` - // Action - The action type of a NAT rule collection. - Action *AzureFirewallNatRCAction `json:"action,omitempty"` - // Rules - Collection of rules used by a NAT rule collection. - Rules *[]AzureFirewallNatRule `json:"rules,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the NAT rule collection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallNatRuleCollectionProperties. -func (afnrcp AzureFirewallNatRuleCollectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afnrcp.Priority != nil { - objectMap["priority"] = afnrcp.Priority - } - if afnrcp.Action != nil { - objectMap["action"] = afnrcp.Action - } - if afnrcp.Rules != nil { - objectMap["rules"] = afnrcp.Rules - } - return json.Marshal(objectMap) -} - -// AzureFirewallNetworkRule properties of the network rule. -type AzureFirewallNetworkRule struct { - // Name - Name of the network rule. - Name *string `json:"name,omitempty"` - // Description - Description of the rule. - Description *string `json:"description,omitempty"` - // Protocols - Array of AzureFirewallNetworkRuleProtocols. - Protocols *[]AzureFirewallNetworkRuleProtocol `json:"protocols,omitempty"` - // SourceAddresses - List of source IP addresses for this rule. - SourceAddresses *[]string `json:"sourceAddresses,omitempty"` - // DestinationAddresses - List of destination IP addresses. - DestinationAddresses *[]string `json:"destinationAddresses,omitempty"` - // DestinationPorts - List of destination ports. - DestinationPorts *[]string `json:"destinationPorts,omitempty"` - // DestinationFqdns - List of destination FQDNs. - DestinationFqdns *[]string `json:"destinationFqdns,omitempty"` - // SourceIPGroups - List of source IpGroups for this rule. - SourceIPGroups *[]string `json:"sourceIpGroups,omitempty"` - // DestinationIPGroups - List of destination IpGroups for this rule. - DestinationIPGroups *[]string `json:"destinationIpGroups,omitempty"` -} - -// AzureFirewallNetworkRuleCollection network rule collection resource. -type AzureFirewallNetworkRuleCollection struct { - // AzureFirewallNetworkRuleCollectionPropertiesFormat - Properties of the azure firewall network rule collection. - *AzureFirewallNetworkRuleCollectionPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within the Azure firewall. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallNetworkRuleCollection. -func (afnrc AzureFirewallNetworkRuleCollection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afnrc.AzureFirewallNetworkRuleCollectionPropertiesFormat != nil { - objectMap["properties"] = afnrc.AzureFirewallNetworkRuleCollectionPropertiesFormat - } - if afnrc.Name != nil { - objectMap["name"] = afnrc.Name - } - if afnrc.ID != nil { - objectMap["id"] = afnrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AzureFirewallNetworkRuleCollection struct. -func (afnrc *AzureFirewallNetworkRuleCollection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var azureFirewallNetworkRuleCollectionPropertiesFormat AzureFirewallNetworkRuleCollectionPropertiesFormat - err = json.Unmarshal(*v, &azureFirewallNetworkRuleCollectionPropertiesFormat) - if err != nil { - return err - } - afnrc.AzureFirewallNetworkRuleCollectionPropertiesFormat = &azureFirewallNetworkRuleCollectionPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - afnrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - afnrc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - afnrc.ID = &ID - } - } - } - - return nil -} - -// AzureFirewallNetworkRuleCollectionPropertiesFormat properties of the network rule collection. -type AzureFirewallNetworkRuleCollectionPropertiesFormat struct { - // Priority - Priority of the network rule collection resource. - Priority *int32 `json:"priority,omitempty"` - // Action - The action type of a rule collection. - Action *AzureFirewallRCAction `json:"action,omitempty"` - // Rules - Collection of rules used by a network rule collection. - Rules *[]AzureFirewallNetworkRule `json:"rules,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the network rule collection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallNetworkRuleCollectionPropertiesFormat. -func (afnrcpf AzureFirewallNetworkRuleCollectionPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afnrcpf.Priority != nil { - objectMap["priority"] = afnrcpf.Priority - } - if afnrcpf.Action != nil { - objectMap["action"] = afnrcpf.Action - } - if afnrcpf.Rules != nil { - objectMap["rules"] = afnrcpf.Rules - } - return json.Marshal(objectMap) -} - -// AzureFirewallPropertiesFormat properties of the Azure Firewall. -type AzureFirewallPropertiesFormat struct { - // ApplicationRuleCollections - Collection of application rule collections used by Azure Firewall. - ApplicationRuleCollections *[]AzureFirewallApplicationRuleCollection `json:"applicationRuleCollections,omitempty"` - // NatRuleCollections - Collection of NAT rule collections used by Azure Firewall. - NatRuleCollections *[]AzureFirewallNatRuleCollection `json:"natRuleCollections,omitempty"` - // NetworkRuleCollections - Collection of network rule collections used by Azure Firewall. - NetworkRuleCollections *[]AzureFirewallNetworkRuleCollection `json:"networkRuleCollections,omitempty"` - // IPConfigurations - IP configuration of the Azure Firewall resource. - IPConfigurations *[]AzureFirewallIPConfiguration `json:"ipConfigurations,omitempty"` - // ManagementIPConfiguration - IP configuration of the Azure Firewall used for management traffic. - ManagementIPConfiguration *AzureFirewallIPConfiguration `json:"managementIpConfiguration,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the Azure firewall resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ThreatIntelMode - The operation mode for Threat Intelligence. Possible values include: 'AzureFirewallThreatIntelModeAlert', 'AzureFirewallThreatIntelModeDeny', 'AzureFirewallThreatIntelModeOff' - ThreatIntelMode AzureFirewallThreatIntelMode `json:"threatIntelMode,omitempty"` - // VirtualHub - The virtualHub to which the firewall belongs. - VirtualHub *SubResource `json:"virtualHub,omitempty"` - // FirewallPolicy - The firewallPolicy associated with this azure firewall. - FirewallPolicy *SubResource `json:"firewallPolicy,omitempty"` - // HubIPAddresses - IP addresses associated with AzureFirewall. - HubIPAddresses *HubIPAddresses `json:"hubIPAddresses,omitempty"` - // IPGroups - READ-ONLY; IpGroups associated with AzureFirewall. - IPGroups *[]AzureFirewallIPGroups `json:"ipGroups,omitempty"` - // Sku - The Azure Firewall Resource SKU. - Sku *AzureFirewallSku `json:"sku,omitempty"` - // AdditionalProperties - The additional properties used to further config this azure firewall. - AdditionalProperties map[string]*string `json:"additionalProperties"` -} - -// MarshalJSON is the custom marshaler for AzureFirewallPropertiesFormat. -func (afpf AzureFirewallPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if afpf.ApplicationRuleCollections != nil { - objectMap["applicationRuleCollections"] = afpf.ApplicationRuleCollections - } - if afpf.NatRuleCollections != nil { - objectMap["natRuleCollections"] = afpf.NatRuleCollections - } - if afpf.NetworkRuleCollections != nil { - objectMap["networkRuleCollections"] = afpf.NetworkRuleCollections - } - if afpf.IPConfigurations != nil { - objectMap["ipConfigurations"] = afpf.IPConfigurations - } - if afpf.ManagementIPConfiguration != nil { - objectMap["managementIpConfiguration"] = afpf.ManagementIPConfiguration - } - if afpf.ThreatIntelMode != "" { - objectMap["threatIntelMode"] = afpf.ThreatIntelMode - } - if afpf.VirtualHub != nil { - objectMap["virtualHub"] = afpf.VirtualHub - } - if afpf.FirewallPolicy != nil { - objectMap["firewallPolicy"] = afpf.FirewallPolicy - } - if afpf.HubIPAddresses != nil { - objectMap["hubIPAddresses"] = afpf.HubIPAddresses - } - if afpf.Sku != nil { - objectMap["sku"] = afpf.Sku - } - if afpf.AdditionalProperties != nil { - objectMap["additionalProperties"] = afpf.AdditionalProperties - } - return json.Marshal(objectMap) -} - -// AzureFirewallPublicIPAddress public IP Address associated with azure firewall. -type AzureFirewallPublicIPAddress struct { - // Address - Public IP Address value. - Address *string `json:"address,omitempty"` -} - -// AzureFirewallRCAction properties of the AzureFirewallRCAction. -type AzureFirewallRCAction struct { - // Type - The type of action. Possible values include: 'AzureFirewallRCActionTypeAllow', 'AzureFirewallRCActionTypeDeny' - Type AzureFirewallRCActionType `json:"type,omitempty"` -} - -// AzureFirewallsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type AzureFirewallsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AzureFirewallsClient) (AzureFirewall, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AzureFirewallsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AzureFirewallsCreateOrUpdateFuture.Result. -func (future *AzureFirewallsCreateOrUpdateFuture) result(client AzureFirewallsClient) (af AzureFirewall, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - af.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.AzureFirewallsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if af.Response.Response, err = future.GetResult(sender); err == nil && af.Response.Response.StatusCode != http.StatusNoContent { - af, err = client.CreateOrUpdateResponder(af.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsCreateOrUpdateFuture", "Result", af.Response.Response, "Failure responding to request") - } - } - return -} - -// AzureFirewallsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type AzureFirewallsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AzureFirewallsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AzureFirewallsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AzureFirewallsDeleteFuture.Result. -func (future *AzureFirewallsDeleteFuture) result(client AzureFirewallsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.AzureFirewallsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// AzureFirewallSku SKU of an Azure Firewall. -type AzureFirewallSku struct { - // Name - Name of an Azure Firewall SKU. Possible values include: 'AZFWVNet', 'AZFWHub' - Name AzureFirewallSkuName `json:"name,omitempty"` - // Tier - Tier of an Azure Firewall. Possible values include: 'AzureFirewallSkuTierStandard', 'AzureFirewallSkuTierPremium', 'AzureFirewallSkuTierBasic' - Tier AzureFirewallSkuTier `json:"tier,omitempty"` -} - -// AzureFirewallsListLearnedPrefixesFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type AzureFirewallsListLearnedPrefixesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AzureFirewallsClient) (IPPrefixesList, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AzureFirewallsListLearnedPrefixesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AzureFirewallsListLearnedPrefixesFuture.Result. -func (future *AzureFirewallsListLearnedPrefixesFuture) result(client AzureFirewallsClient) (ipl IPPrefixesList, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsListLearnedPrefixesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ipl.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.AzureFirewallsListLearnedPrefixesFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ipl.Response.Response, err = future.GetResult(sender); err == nil && ipl.Response.Response.StatusCode != http.StatusNoContent { - ipl, err = client.ListLearnedPrefixesResponder(ipl.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsListLearnedPrefixesFuture", "Result", ipl.Response.Response, "Failure responding to request") - } - } - return -} - -// AzureFirewallsUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type AzureFirewallsUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(AzureFirewallsClient) (AzureFirewall, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *AzureFirewallsUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for AzureFirewallsUpdateTagsFuture.Result. -func (future *AzureFirewallsUpdateTagsFuture) result(client AzureFirewallsClient) (af AzureFirewall, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - af.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.AzureFirewallsUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if af.Response.Response, err = future.GetResult(sender); err == nil && af.Response.Response.StatusCode != http.StatusNoContent { - af, err = client.UpdateTagsResponder(af.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.AzureFirewallsUpdateTagsFuture", "Result", af.Response.Response, "Failure responding to request") - } - } - return -} - -// AzureReachabilityReport azure reachability report details. -type AzureReachabilityReport struct { - autorest.Response `json:"-"` - // AggregationLevel - The aggregation level of Azure reachability report. Can be Country, State or City. - AggregationLevel *string `json:"aggregationLevel,omitempty"` - // ProviderLocation - Parameters that define a geographic location. - ProviderLocation *AzureReachabilityReportLocation `json:"providerLocation,omitempty"` - // ReachabilityReport - List of Azure reachability report items. - ReachabilityReport *[]AzureReachabilityReportItem `json:"reachabilityReport,omitempty"` -} - -// AzureReachabilityReportItem azure reachability report details for a given provider location. -type AzureReachabilityReportItem struct { - // Provider - The Internet service provider. - Provider *string `json:"provider,omitempty"` - // AzureLocation - The Azure region. - AzureLocation *string `json:"azureLocation,omitempty"` - // Latencies - List of latency details for each of the time series. - Latencies *[]AzureReachabilityReportLatencyInfo `json:"latencies,omitempty"` -} - -// AzureReachabilityReportLatencyInfo details on latency for a time series. -type AzureReachabilityReportLatencyInfo struct { - // TimeStamp - The time stamp. - TimeStamp *date.Time `json:"timeStamp,omitempty"` - // Score - The relative latency score between 1 and 100, higher values indicating a faster connection. - Score *int32 `json:"score,omitempty"` -} - -// AzureReachabilityReportLocation parameters that define a geographic location. -type AzureReachabilityReportLocation struct { - // Country - The name of the country. - Country *string `json:"country,omitempty"` - // State - The name of the state. - State *string `json:"state,omitempty"` - // City - The name of the city or town. - City *string `json:"city,omitempty"` -} - -// AzureReachabilityReportParameters geographic and time constraints for Azure reachability report. -type AzureReachabilityReportParameters struct { - // ProviderLocation - Parameters that define a geographic location. - ProviderLocation *AzureReachabilityReportLocation `json:"providerLocation,omitempty"` - // Providers - List of Internet service providers. - Providers *[]string `json:"providers,omitempty"` - // AzureLocations - Optional Azure regions to scope the query to. - AzureLocations *[]string `json:"azureLocations,omitempty"` - // StartTime - The start time for the Azure reachability report. - StartTime *date.Time `json:"startTime,omitempty"` - // EndTime - The end time for the Azure reachability report. - EndTime *date.Time `json:"endTime,omitempty"` -} - -// AzureWebCategory azure Web Category Resource. -type AzureWebCategory struct { - autorest.Response `json:"-"` - // AzureWebCategoryPropertiesFormat - Properties of the Azure Web Category. - *AzureWebCategoryPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureWebCategory. -func (awc AzureWebCategory) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if awc.AzureWebCategoryPropertiesFormat != nil { - objectMap["properties"] = awc.AzureWebCategoryPropertiesFormat - } - if awc.ID != nil { - objectMap["id"] = awc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for AzureWebCategory struct. -func (awc *AzureWebCategory) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var azureWebCategoryPropertiesFormat AzureWebCategoryPropertiesFormat - err = json.Unmarshal(*v, &azureWebCategoryPropertiesFormat) - if err != nil { - return err - } - awc.AzureWebCategoryPropertiesFormat = &azureWebCategoryPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - awc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - awc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - awc.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - awc.Etag = &etag - } - } - } - - return nil -} - -// AzureWebCategoryListResult response for ListAzureWebCategories API service call. -type AzureWebCategoryListResult struct { - autorest.Response `json:"-"` - // Value - List of Azure Web Categories for a given Subscription. - Value *[]AzureWebCategory `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// AzureWebCategoryListResultIterator provides access to a complete listing of AzureWebCategory values. -type AzureWebCategoryListResultIterator struct { - i int - page AzureWebCategoryListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *AzureWebCategoryListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureWebCategoryListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *AzureWebCategoryListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter AzureWebCategoryListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter AzureWebCategoryListResultIterator) Response() AzureWebCategoryListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter AzureWebCategoryListResultIterator) Value() AzureWebCategory { - if !iter.page.NotDone() { - return AzureWebCategory{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the AzureWebCategoryListResultIterator type. -func NewAzureWebCategoryListResultIterator(page AzureWebCategoryListResultPage) AzureWebCategoryListResultIterator { - return AzureWebCategoryListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (awclr AzureWebCategoryListResult) IsEmpty() bool { - return awclr.Value == nil || len(*awclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (awclr AzureWebCategoryListResult) hasNextLink() bool { - return awclr.NextLink != nil && len(*awclr.NextLink) != 0 -} - -// azureWebCategoryListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (awclr AzureWebCategoryListResult) azureWebCategoryListResultPreparer(ctx context.Context) (*http.Request, error) { - if !awclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(awclr.NextLink))) -} - -// AzureWebCategoryListResultPage contains a page of AzureWebCategory values. -type AzureWebCategoryListResultPage struct { - fn func(context.Context, AzureWebCategoryListResult) (AzureWebCategoryListResult, error) - awclr AzureWebCategoryListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *AzureWebCategoryListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/AzureWebCategoryListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.awclr) - if err != nil { - return err - } - page.awclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *AzureWebCategoryListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page AzureWebCategoryListResultPage) NotDone() bool { - return !page.awclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page AzureWebCategoryListResultPage) Response() AzureWebCategoryListResult { - return page.awclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page AzureWebCategoryListResultPage) Values() []AzureWebCategory { - if page.awclr.IsEmpty() { - return nil - } - return *page.awclr.Value -} - -// Creates a new instance of the AzureWebCategoryListResultPage type. -func NewAzureWebCategoryListResultPage(cur AzureWebCategoryListResult, getNextPage func(context.Context, AzureWebCategoryListResult) (AzureWebCategoryListResult, error)) AzureWebCategoryListResultPage { - return AzureWebCategoryListResultPage{ - fn: getNextPage, - awclr: cur, - } -} - -// AzureWebCategoryPropertiesFormat azure Web Category Properties. -type AzureWebCategoryPropertiesFormat struct { - // Group - READ-ONLY; The name of the group that the category belongs to. - Group *string `json:"group,omitempty"` -} - -// MarshalJSON is the custom marshaler for AzureWebCategoryPropertiesFormat. -func (awcpf AzureWebCategoryPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// BackendAddressInboundNatRulePortMappings the response for a QueryInboundNatRulePortMapping API. -type BackendAddressInboundNatRulePortMappings struct { - autorest.Response `json:"-"` - // InboundNatRulePortMappings - Collection of inbound NAT rule port mappings. - InboundNatRulePortMappings *[]InboundNatRulePortMapping `json:"inboundNatRulePortMappings,omitempty"` -} - -// BackendAddressPool pool of backend IP addresses. -type BackendAddressPool struct { - autorest.Response `json:"-"` - // BackendAddressPoolPropertiesFormat - Properties of load balancer backend address pool. - *BackendAddressPoolPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within the set of backend address pools used by the load balancer. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for BackendAddressPool. -func (bap BackendAddressPool) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bap.BackendAddressPoolPropertiesFormat != nil { - objectMap["properties"] = bap.BackendAddressPoolPropertiesFormat - } - if bap.Name != nil { - objectMap["name"] = bap.Name - } - if bap.ID != nil { - objectMap["id"] = bap.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for BackendAddressPool struct. -func (bap *BackendAddressPool) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var backendAddressPoolPropertiesFormat BackendAddressPoolPropertiesFormat - err = json.Unmarshal(*v, &backendAddressPoolPropertiesFormat) - if err != nil { - return err - } - bap.BackendAddressPoolPropertiesFormat = &backendAddressPoolPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - bap.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - bap.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - bap.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - bap.ID = &ID - } - } - } - - return nil -} - -// BackendAddressPoolPropertiesFormat properties of the backend address pool. -type BackendAddressPoolPropertiesFormat struct { - // Location - The location of the backend address pool. - Location *string `json:"location,omitempty"` - // TunnelInterfaces - An array of gateway load balancer tunnel interfaces. - TunnelInterfaces *[]GatewayLoadBalancerTunnelInterface `json:"tunnelInterfaces,omitempty"` - // LoadBalancerBackendAddresses - An array of backend addresses. - LoadBalancerBackendAddresses *[]LoadBalancerBackendAddress `json:"loadBalancerBackendAddresses,omitempty"` - // BackendIPConfigurations - READ-ONLY; An array of references to IP addresses defined in network interfaces. - BackendIPConfigurations *[]InterfaceIPConfiguration `json:"backendIPConfigurations,omitempty"` - // LoadBalancingRules - READ-ONLY; An array of references to load balancing rules that use this backend address pool. - LoadBalancingRules *[]SubResource `json:"loadBalancingRules,omitempty"` - // OutboundRule - READ-ONLY; A reference to an outbound rule that uses this backend address pool. - OutboundRule *SubResource `json:"outboundRule,omitempty"` - // OutboundRules - READ-ONLY; An array of references to outbound rules that use this backend address pool. - OutboundRules *[]SubResource `json:"outboundRules,omitempty"` - // InboundNatRules - READ-ONLY; An array of references to inbound NAT rules that use this backend address pool. - InboundNatRules *[]SubResource `json:"inboundNatRules,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the backend address pool resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // DrainPeriodInSeconds - Amount of seconds Load Balancer waits for before sending RESET to client and backend address. - DrainPeriodInSeconds *int32 `json:"drainPeriodInSeconds,omitempty"` - // VirtualNetwork - A reference to a virtual network. - VirtualNetwork *SubResource `json:"virtualNetwork,omitempty"` -} - -// MarshalJSON is the custom marshaler for BackendAddressPoolPropertiesFormat. -func (bappf BackendAddressPoolPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bappf.Location != nil { - objectMap["location"] = bappf.Location - } - if bappf.TunnelInterfaces != nil { - objectMap["tunnelInterfaces"] = bappf.TunnelInterfaces - } - if bappf.LoadBalancerBackendAddresses != nil { - objectMap["loadBalancerBackendAddresses"] = bappf.LoadBalancerBackendAddresses - } - if bappf.DrainPeriodInSeconds != nil { - objectMap["drainPeriodInSeconds"] = bappf.DrainPeriodInSeconds - } - if bappf.VirtualNetwork != nil { - objectMap["virtualNetwork"] = bappf.VirtualNetwork - } - return json.Marshal(objectMap) -} - -// BasicBaseAdminRule network base admin rule. -type BasicBaseAdminRule interface { - AsAdminRule() (*AdminRule, bool) - AsDefaultAdminRule() (*DefaultAdminRule, bool) - AsBaseAdminRule() (*BaseAdminRule, bool) -} - -// BaseAdminRule network base admin rule. -type BaseAdminRule struct { - autorest.Response `json:"-"` - // SystemData - READ-ONLY; The system metadata related to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // Kind - Possible values include: 'KindBasicBaseAdminRuleKindBaseAdminRule', 'KindBasicBaseAdminRuleKindCustom', 'KindBasicBaseAdminRuleKindDefault' - Kind KindBasicBaseAdminRule `json:"kind,omitempty"` - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -func unmarshalBasicBaseAdminRule(body []byte) (BasicBaseAdminRule, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["kind"] { - case string(KindBasicBaseAdminRuleKindCustom): - var ar AdminRule - err := json.Unmarshal(body, &ar) - return ar, err - case string(KindBasicBaseAdminRuleKindDefault): - var dar DefaultAdminRule - err := json.Unmarshal(body, &dar) - return dar, err - default: - var bar BaseAdminRule - err := json.Unmarshal(body, &bar) - return bar, err - } -} -func unmarshalBasicBaseAdminRuleArray(body []byte) ([]BasicBaseAdminRule, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - barArray := make([]BasicBaseAdminRule, len(rawMessages)) - - for index, rawMessage := range rawMessages { - bar, err := unmarshalBasicBaseAdminRule(*rawMessage) - if err != nil { - return nil, err - } - barArray[index] = bar - } - return barArray, nil -} - -// MarshalJSON is the custom marshaler for BaseAdminRule. -func (bar BaseAdminRule) MarshalJSON() ([]byte, error) { - bar.Kind = KindBasicBaseAdminRuleKindBaseAdminRule - objectMap := make(map[string]interface{}) - if bar.Kind != "" { - objectMap["kind"] = bar.Kind - } - return json.Marshal(objectMap) -} - -// AsAdminRule is the BasicBaseAdminRule implementation for BaseAdminRule. -func (bar BaseAdminRule) AsAdminRule() (*AdminRule, bool) { - return nil, false -} - -// AsDefaultAdminRule is the BasicBaseAdminRule implementation for BaseAdminRule. -func (bar BaseAdminRule) AsDefaultAdminRule() (*DefaultAdminRule, bool) { - return nil, false -} - -// AsBaseAdminRule is the BasicBaseAdminRule implementation for BaseAdminRule. -func (bar BaseAdminRule) AsBaseAdminRule() (*BaseAdminRule, bool) { - return &bar, true -} - -// AsBasicBaseAdminRule is the BasicBaseAdminRule implementation for BaseAdminRule. -func (bar BaseAdminRule) AsBasicBaseAdminRule() (BasicBaseAdminRule, bool) { - return &bar, true -} - -// BaseAdminRuleModel ... -type BaseAdminRuleModel struct { - autorest.Response `json:"-"` - Value BasicBaseAdminRule `json:"value,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for BaseAdminRuleModel struct. -func (barm *BaseAdminRuleModel) UnmarshalJSON(body []byte) error { - bar, err := unmarshalBasicBaseAdminRule(body) - if err != nil { - return err - } - barm.Value = bar - - return nil -} - -// BastionActiveSession the session detail for a target. -type BastionActiveSession struct { - // SessionID - READ-ONLY; A unique id for the session. - SessionID *string `json:"sessionId,omitempty"` - // StartTime - READ-ONLY; The time when the session started. - StartTime interface{} `json:"startTime,omitempty"` - // TargetSubscriptionID - READ-ONLY; The subscription id for the target virtual machine. - TargetSubscriptionID *string `json:"targetSubscriptionId,omitempty"` - // ResourceType - READ-ONLY; The type of the resource. - ResourceType *string `json:"resourceType,omitempty"` - // TargetHostName - READ-ONLY; The host name of the target. - TargetHostName *string `json:"targetHostName,omitempty"` - // TargetResourceGroup - READ-ONLY; The resource group of the target. - TargetResourceGroup *string `json:"targetResourceGroup,omitempty"` - // UserName - READ-ONLY; The user name who is active on this session. - UserName *string `json:"userName,omitempty"` - // TargetIPAddress - READ-ONLY; The IP Address of the target. - TargetIPAddress *string `json:"targetIpAddress,omitempty"` - // Protocol - READ-ONLY; The protocol used to connect to the target. Possible values include: 'SSH', 'RDP' - Protocol BastionConnectProtocol `json:"protocol,omitempty"` - // TargetResourceID - READ-ONLY; The resource id of the target. - TargetResourceID *string `json:"targetResourceId,omitempty"` - // SessionDurationInMins - READ-ONLY; Duration in mins the session has been active. - SessionDurationInMins *float64 `json:"sessionDurationInMins,omitempty"` -} - -// MarshalJSON is the custom marshaler for BastionActiveSession. -func (bas BastionActiveSession) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// BastionActiveSessionListResult response for GetActiveSessions. -type BastionActiveSessionListResult struct { - autorest.Response `json:"-"` - // Value - List of active sessions on the bastion. - Value *[]BastionActiveSession `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// BastionActiveSessionListResultIterator provides access to a complete listing of BastionActiveSession -// values. -type BastionActiveSessionListResultIterator struct { - i int - page BastionActiveSessionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *BastionActiveSessionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionActiveSessionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *BastionActiveSessionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter BastionActiveSessionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter BastionActiveSessionListResultIterator) Response() BastionActiveSessionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter BastionActiveSessionListResultIterator) Value() BastionActiveSession { - if !iter.page.NotDone() { - return BastionActiveSession{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the BastionActiveSessionListResultIterator type. -func NewBastionActiveSessionListResultIterator(page BastionActiveSessionListResultPage) BastionActiveSessionListResultIterator { - return BastionActiveSessionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (baslr BastionActiveSessionListResult) IsEmpty() bool { - return baslr.Value == nil || len(*baslr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (baslr BastionActiveSessionListResult) hasNextLink() bool { - return baslr.NextLink != nil && len(*baslr.NextLink) != 0 -} - -// bastionActiveSessionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (baslr BastionActiveSessionListResult) bastionActiveSessionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !baslr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(baslr.NextLink))) -} - -// BastionActiveSessionListResultPage contains a page of BastionActiveSession values. -type BastionActiveSessionListResultPage struct { - fn func(context.Context, BastionActiveSessionListResult) (BastionActiveSessionListResult, error) - baslr BastionActiveSessionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *BastionActiveSessionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionActiveSessionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.baslr) - if err != nil { - return err - } - page.baslr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *BastionActiveSessionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page BastionActiveSessionListResultPage) NotDone() bool { - return !page.baslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page BastionActiveSessionListResultPage) Response() BastionActiveSessionListResult { - return page.baslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page BastionActiveSessionListResultPage) Values() []BastionActiveSession { - if page.baslr.IsEmpty() { - return nil - } - return *page.baslr.Value -} - -// Creates a new instance of the BastionActiveSessionListResultPage type. -func NewBastionActiveSessionListResultPage(cur BastionActiveSessionListResult, getNextPage func(context.Context, BastionActiveSessionListResult) (BastionActiveSessionListResult, error)) BastionActiveSessionListResultPage { - return BastionActiveSessionListResultPage{ - fn: getNextPage, - baslr: cur, - } -} - -// BastionHost bastion Host resource. -type BastionHost struct { - autorest.Response `json:"-"` - // BastionHostPropertiesFormat - Represents the bastion host resource. - *BastionHostPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Sku - The sku of this Bastion Host. - Sku *Sku `json:"sku,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for BastionHost. -func (bh BastionHost) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bh.BastionHostPropertiesFormat != nil { - objectMap["properties"] = bh.BastionHostPropertiesFormat - } - if bh.Sku != nil { - objectMap["sku"] = bh.Sku - } - if bh.ID != nil { - objectMap["id"] = bh.ID - } - if bh.Location != nil { - objectMap["location"] = bh.Location - } - if bh.Tags != nil { - objectMap["tags"] = bh.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for BastionHost struct. -func (bh *BastionHost) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var bastionHostPropertiesFormat BastionHostPropertiesFormat - err = json.Unmarshal(*v, &bastionHostPropertiesFormat) - if err != nil { - return err - } - bh.BastionHostPropertiesFormat = &bastionHostPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - bh.Etag = &etag - } - case "sku": - if v != nil { - var sku Sku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - bh.Sku = &sku - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - bh.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - bh.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - bh.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - bh.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - bh.Tags = tags - } - } - } - - return nil -} - -// BastionHostIPConfiguration IP configuration of an Bastion Host. -type BastionHostIPConfiguration struct { - // BastionHostIPConfigurationPropertiesFormat - Represents the ip configuration associated with the resource. - *BastionHostIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Ip configuration type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for BastionHostIPConfiguration. -func (bhic BastionHostIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bhic.BastionHostIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = bhic.BastionHostIPConfigurationPropertiesFormat - } - if bhic.Name != nil { - objectMap["name"] = bhic.Name - } - if bhic.ID != nil { - objectMap["id"] = bhic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for BastionHostIPConfiguration struct. -func (bhic *BastionHostIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var bastionHostIPConfigurationPropertiesFormat BastionHostIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &bastionHostIPConfigurationPropertiesFormat) - if err != nil { - return err - } - bhic.BastionHostIPConfigurationPropertiesFormat = &bastionHostIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - bhic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - bhic.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - bhic.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - bhic.ID = &ID - } - } - } - - return nil -} - -// BastionHostIPConfigurationPropertiesFormat properties of IP configuration of an Bastion Host. -type BastionHostIPConfigurationPropertiesFormat struct { - // Subnet - Reference of the subnet resource. - Subnet *SubResource `json:"subnet,omitempty"` - // PublicIPAddress - Reference of the PublicIP resource. - PublicIPAddress *SubResource `json:"publicIPAddress,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the bastion host IP configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // PrivateIPAllocationMethod - Private IP allocation method. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` -} - -// MarshalJSON is the custom marshaler for BastionHostIPConfigurationPropertiesFormat. -func (bhicpf BastionHostIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bhicpf.Subnet != nil { - objectMap["subnet"] = bhicpf.Subnet - } - if bhicpf.PublicIPAddress != nil { - objectMap["publicIPAddress"] = bhicpf.PublicIPAddress - } - if bhicpf.PrivateIPAllocationMethod != "" { - objectMap["privateIPAllocationMethod"] = bhicpf.PrivateIPAllocationMethod - } - return json.Marshal(objectMap) -} - -// BastionHostListResult response for ListBastionHosts API service call. -type BastionHostListResult struct { - autorest.Response `json:"-"` - // Value - List of Bastion Hosts in a resource group. - Value *[]BastionHost `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// BastionHostListResultIterator provides access to a complete listing of BastionHost values. -type BastionHostListResultIterator struct { - i int - page BastionHostListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *BastionHostListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionHostListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *BastionHostListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter BastionHostListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter BastionHostListResultIterator) Response() BastionHostListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter BastionHostListResultIterator) Value() BastionHost { - if !iter.page.NotDone() { - return BastionHost{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the BastionHostListResultIterator type. -func NewBastionHostListResultIterator(page BastionHostListResultPage) BastionHostListResultIterator { - return BastionHostListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (bhlr BastionHostListResult) IsEmpty() bool { - return bhlr.Value == nil || len(*bhlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (bhlr BastionHostListResult) hasNextLink() bool { - return bhlr.NextLink != nil && len(*bhlr.NextLink) != 0 -} - -// bastionHostListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (bhlr BastionHostListResult) bastionHostListResultPreparer(ctx context.Context) (*http.Request, error) { - if !bhlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(bhlr.NextLink))) -} - -// BastionHostListResultPage contains a page of BastionHost values. -type BastionHostListResultPage struct { - fn func(context.Context, BastionHostListResult) (BastionHostListResult, error) - bhlr BastionHostListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *BastionHostListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionHostListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.bhlr) - if err != nil { - return err - } - page.bhlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *BastionHostListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page BastionHostListResultPage) NotDone() bool { - return !page.bhlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page BastionHostListResultPage) Response() BastionHostListResult { - return page.bhlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page BastionHostListResultPage) Values() []BastionHost { - if page.bhlr.IsEmpty() { - return nil - } - return *page.bhlr.Value -} - -// Creates a new instance of the BastionHostListResultPage type. -func NewBastionHostListResultPage(cur BastionHostListResult, getNextPage func(context.Context, BastionHostListResult) (BastionHostListResult, error)) BastionHostListResultPage { - return BastionHostListResultPage{ - fn: getNextPage, - bhlr: cur, - } -} - -// BastionHostPropertiesFormat properties of the Bastion Host. -type BastionHostPropertiesFormat struct { - // IPConfigurations - IP configuration of the Bastion Host resource. - IPConfigurations *[]BastionHostIPConfiguration `json:"ipConfigurations,omitempty"` - // DNSName - FQDN for the endpoint on which bastion host is accessible. - DNSName *string `json:"dnsName,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the bastion host resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ScaleUnits - The scale units for the Bastion Host resource. - ScaleUnits *int32 `json:"scaleUnits,omitempty"` - // DisableCopyPaste - Enable/Disable Copy/Paste feature of the Bastion Host resource. - DisableCopyPaste *bool `json:"disableCopyPaste,omitempty"` - // EnableFileCopy - Enable/Disable File Copy feature of the Bastion Host resource. - EnableFileCopy *bool `json:"enableFileCopy,omitempty"` - // EnableIPConnect - Enable/Disable IP Connect feature of the Bastion Host resource. - EnableIPConnect *bool `json:"enableIpConnect,omitempty"` - // EnableShareableLink - Enable/Disable Shareable Link of the Bastion Host resource. - EnableShareableLink *bool `json:"enableShareableLink,omitempty"` - // EnableTunneling - Enable/Disable Tunneling feature of the Bastion Host resource. - EnableTunneling *bool `json:"enableTunneling,omitempty"` -} - -// MarshalJSON is the custom marshaler for BastionHostPropertiesFormat. -func (bhpf BastionHostPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bhpf.IPConfigurations != nil { - objectMap["ipConfigurations"] = bhpf.IPConfigurations - } - if bhpf.DNSName != nil { - objectMap["dnsName"] = bhpf.DNSName - } - if bhpf.ScaleUnits != nil { - objectMap["scaleUnits"] = bhpf.ScaleUnits - } - if bhpf.DisableCopyPaste != nil { - objectMap["disableCopyPaste"] = bhpf.DisableCopyPaste - } - if bhpf.EnableFileCopy != nil { - objectMap["enableFileCopy"] = bhpf.EnableFileCopy - } - if bhpf.EnableIPConnect != nil { - objectMap["enableIpConnect"] = bhpf.EnableIPConnect - } - if bhpf.EnableShareableLink != nil { - objectMap["enableShareableLink"] = bhpf.EnableShareableLink - } - if bhpf.EnableTunneling != nil { - objectMap["enableTunneling"] = bhpf.EnableTunneling - } - return json.Marshal(objectMap) -} - -// BastionHostsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type BastionHostsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BastionHostsClient) (BastionHost, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BastionHostsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BastionHostsCreateOrUpdateFuture.Result. -func (future *BastionHostsCreateOrUpdateFuture) result(client BastionHostsClient) (bh BastionHost, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - bh.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.BastionHostsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if bh.Response.Response, err = future.GetResult(sender); err == nil && bh.Response.Response.StatusCode != http.StatusNoContent { - bh, err = client.CreateOrUpdateResponder(bh.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsCreateOrUpdateFuture", "Result", bh.Response.Response, "Failure responding to request") - } - } - return -} - -// BastionHostsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type BastionHostsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BastionHostsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BastionHostsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BastionHostsDeleteFuture.Result. -func (future *BastionHostsDeleteFuture) result(client BastionHostsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.BastionHostsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// BastionHostsUpdateTagsFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type BastionHostsUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BastionHostsClient) (BastionHost, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *BastionHostsUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for BastionHostsUpdateTagsFuture.Result. -func (future *BastionHostsUpdateTagsFuture) result(client BastionHostsClient) (bh BastionHost, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - bh.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.BastionHostsUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if bh.Response.Response, err = future.GetResult(sender); err == nil && bh.Response.Response.StatusCode != http.StatusNoContent { - bh, err = client.UpdateTagsResponder(bh.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.BastionHostsUpdateTagsFuture", "Result", bh.Response.Response, "Failure responding to request") - } - } - return -} - -// BastionSessionDeleteResult response for DisconnectActiveSessions. -type BastionSessionDeleteResult struct { - autorest.Response `json:"-"` - // Value - List of sessions with their corresponding state. - Value *[]BastionSessionState `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// BastionSessionDeleteResultIterator provides access to a complete listing of BastionSessionState values. -type BastionSessionDeleteResultIterator struct { - i int - page BastionSessionDeleteResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *BastionSessionDeleteResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionSessionDeleteResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *BastionSessionDeleteResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter BastionSessionDeleteResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter BastionSessionDeleteResultIterator) Response() BastionSessionDeleteResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter BastionSessionDeleteResultIterator) Value() BastionSessionState { - if !iter.page.NotDone() { - return BastionSessionState{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the BastionSessionDeleteResultIterator type. -func NewBastionSessionDeleteResultIterator(page BastionSessionDeleteResultPage) BastionSessionDeleteResultIterator { - return BastionSessionDeleteResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (bsdr BastionSessionDeleteResult) IsEmpty() bool { - return bsdr.Value == nil || len(*bsdr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (bsdr BastionSessionDeleteResult) hasNextLink() bool { - return bsdr.NextLink != nil && len(*bsdr.NextLink) != 0 -} - -// bastionSessionDeleteResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (bsdr BastionSessionDeleteResult) bastionSessionDeleteResultPreparer(ctx context.Context) (*http.Request, error) { - if !bsdr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(bsdr.NextLink))) -} - -// BastionSessionDeleteResultPage contains a page of BastionSessionState values. -type BastionSessionDeleteResultPage struct { - fn func(context.Context, BastionSessionDeleteResult) (BastionSessionDeleteResult, error) - bsdr BastionSessionDeleteResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *BastionSessionDeleteResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionSessionDeleteResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.bsdr) - if err != nil { - return err - } - page.bsdr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *BastionSessionDeleteResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page BastionSessionDeleteResultPage) NotDone() bool { - return !page.bsdr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page BastionSessionDeleteResultPage) Response() BastionSessionDeleteResult { - return page.bsdr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page BastionSessionDeleteResultPage) Values() []BastionSessionState { - if page.bsdr.IsEmpty() { - return nil - } - return *page.bsdr.Value -} - -// Creates a new instance of the BastionSessionDeleteResultPage type. -func NewBastionSessionDeleteResultPage(cur BastionSessionDeleteResult, getNextPage func(context.Context, BastionSessionDeleteResult) (BastionSessionDeleteResult, error)) BastionSessionDeleteResultPage { - return BastionSessionDeleteResultPage{ - fn: getNextPage, - bsdr: cur, - } -} - -// BastionSessionState the session state detail for a target. -type BastionSessionState struct { - // SessionID - READ-ONLY; A unique id for the session. - SessionID *string `json:"sessionId,omitempty"` - // Message - READ-ONLY; Used for extra information. - Message *string `json:"message,omitempty"` - // State - READ-ONLY; The state of the session. Disconnected/Failed/NotFound. - State *string `json:"state,omitempty"` -} - -// MarshalJSON is the custom marshaler for BastionSessionState. -func (bss BastionSessionState) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// BastionShareableLink bastion Shareable Link. -type BastionShareableLink struct { - // VM - Reference of the virtual machine resource. - VM *VM `json:"vm,omitempty"` - // Bsl - READ-ONLY; The unique Bastion Shareable Link to the virtual machine. - Bsl *string `json:"bsl,omitempty"` - // CreatedAt - READ-ONLY; The time when the link was created. - CreatedAt *string `json:"createdAt,omitempty"` - // Message - READ-ONLY; Optional field indicating the warning or error message related to the vm in case of partial failure. - Message *string `json:"message,omitempty"` -} - -// MarshalJSON is the custom marshaler for BastionShareableLink. -func (bsl BastionShareableLink) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bsl.VM != nil { - objectMap["vm"] = bsl.VM - } - return json.Marshal(objectMap) -} - -// BastionShareableLinkListRequest post request for all the Bastion Shareable Link endpoints. -type BastionShareableLinkListRequest struct { - // Vms - List of VM references. - Vms *[]BastionShareableLink `json:"vms,omitempty"` -} - -// BastionShareableLinkListResult response for all the Bastion Shareable Link endpoints. -type BastionShareableLinkListResult struct { - autorest.Response `json:"-"` - // Value - List of Bastion Shareable Links for the request. - Value *[]BastionShareableLink `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// BastionShareableLinkListResultIterator provides access to a complete listing of BastionShareableLink -// values. -type BastionShareableLinkListResultIterator struct { - i int - page BastionShareableLinkListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *BastionShareableLinkListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionShareableLinkListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *BastionShareableLinkListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter BastionShareableLinkListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter BastionShareableLinkListResultIterator) Response() BastionShareableLinkListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter BastionShareableLinkListResultIterator) Value() BastionShareableLink { - if !iter.page.NotDone() { - return BastionShareableLink{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the BastionShareableLinkListResultIterator type. -func NewBastionShareableLinkListResultIterator(page BastionShareableLinkListResultPage) BastionShareableLinkListResultIterator { - return BastionShareableLinkListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (bsllr BastionShareableLinkListResult) IsEmpty() bool { - return bsllr.Value == nil || len(*bsllr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (bsllr BastionShareableLinkListResult) hasNextLink() bool { - return bsllr.NextLink != nil && len(*bsllr.NextLink) != 0 -} - -// bastionShareableLinkListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (bsllr BastionShareableLinkListResult) bastionShareableLinkListResultPreparer(ctx context.Context) (*http.Request, error) { - if !bsllr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(bsllr.NextLink))) -} - -// BastionShareableLinkListResultPage contains a page of BastionShareableLink values. -type BastionShareableLinkListResultPage struct { - fn func(context.Context, BastionShareableLinkListResult) (BastionShareableLinkListResult, error) - bsllr BastionShareableLinkListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *BastionShareableLinkListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BastionShareableLinkListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.bsllr) - if err != nil { - return err - } - page.bsllr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *BastionShareableLinkListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page BastionShareableLinkListResultPage) NotDone() bool { - return !page.bsllr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page BastionShareableLinkListResultPage) Response() BastionShareableLinkListResult { - return page.bsllr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page BastionShareableLinkListResultPage) Values() []BastionShareableLink { - if page.bsllr.IsEmpty() { - return nil - } - return *page.bsllr.Value -} - -// Creates a new instance of the BastionShareableLinkListResultPage type. -func NewBastionShareableLinkListResultPage(cur BastionShareableLinkListResult, getNextPage func(context.Context, BastionShareableLinkListResult) (BastionShareableLinkListResult, error)) BastionShareableLinkListResultPage { - return BastionShareableLinkListResultPage{ - fn: getNextPage, - bsllr: cur, - } -} - -// BGPCommunity contains bgp community information offered in Service Community resources. -type BGPCommunity struct { - // ServiceSupportedRegion - The region which the service support. e.g. For O365, region is Global. - ServiceSupportedRegion *string `json:"serviceSupportedRegion,omitempty"` - // CommunityName - The name of the bgp community. e.g. Skype. - CommunityName *string `json:"communityName,omitempty"` - // CommunityValue - The value of the bgp community. For more information: https://docs.microsoft.com/en-us/azure/expressroute/expressroute-routing. - CommunityValue *string `json:"communityValue,omitempty"` - // CommunityPrefixes - The prefixes that the bgp community contains. - CommunityPrefixes *[]string `json:"communityPrefixes,omitempty"` - // IsAuthorizedToUse - Customer is authorized to use bgp community or not. - IsAuthorizedToUse *bool `json:"isAuthorizedToUse,omitempty"` - // ServiceGroup - The service group of the bgp community contains. - ServiceGroup *string `json:"serviceGroup,omitempty"` -} - -// BgpConnection virtual Appliance Site resource. -type BgpConnection struct { - autorest.Response `json:"-"` - // BgpConnectionProperties - The properties of the Bgp connections. - *BgpConnectionProperties `json:"properties,omitempty"` - // Name - Name of the connection. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Connection type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for BgpConnection. -func (bc BgpConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bc.BgpConnectionProperties != nil { - objectMap["properties"] = bc.BgpConnectionProperties - } - if bc.Name != nil { - objectMap["name"] = bc.Name - } - if bc.ID != nil { - objectMap["id"] = bc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for BgpConnection struct. -func (bc *BgpConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var bgpConnectionProperties BgpConnectionProperties - err = json.Unmarshal(*v, &bgpConnectionProperties) - if err != nil { - return err - } - bc.BgpConnectionProperties = &bgpConnectionProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - bc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - bc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - bc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - bc.ID = &ID - } - } - } - - return nil -} - -// BgpConnectionProperties properties of the bgp connection. -type BgpConnectionProperties struct { - // PeerAsn - Peer ASN. - PeerAsn *int64 `json:"peerAsn,omitempty"` - // PeerIP - Peer IP. - PeerIP *string `json:"peerIp,omitempty"` - // HubVirtualNetworkConnection - The reference to the HubVirtualNetworkConnection resource. - HubVirtualNetworkConnection *SubResource `json:"hubVirtualNetworkConnection,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ConnectionState - READ-ONLY; The current state of the VirtualHub to Peer. Possible values include: 'HubBgpConnectionStatusUnknown', 'HubBgpConnectionStatusConnecting', 'HubBgpConnectionStatusConnected', 'HubBgpConnectionStatusNotConnected' - ConnectionState HubBgpConnectionStatus `json:"connectionState,omitempty"` -} - -// MarshalJSON is the custom marshaler for BgpConnectionProperties. -func (bcp BgpConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bcp.PeerAsn != nil { - objectMap["peerAsn"] = bcp.PeerAsn - } - if bcp.PeerIP != nil { - objectMap["peerIp"] = bcp.PeerIP - } - if bcp.HubVirtualNetworkConnection != nil { - objectMap["hubVirtualNetworkConnection"] = bcp.HubVirtualNetworkConnection - } - return json.Marshal(objectMap) -} - -// BgpPeerStatus BGP peer status details. -type BgpPeerStatus struct { - // LocalAddress - READ-ONLY; The virtual network gateway's local address. - LocalAddress *string `json:"localAddress,omitempty"` - // Neighbor - READ-ONLY; The remote BGP peer. - Neighbor *string `json:"neighbor,omitempty"` - // Asn - READ-ONLY; The autonomous system number of the remote BGP peer. - Asn *int64 `json:"asn,omitempty"` - // State - READ-ONLY; The BGP peer state. Possible values include: 'BgpPeerStateUnknown', 'BgpPeerStateStopped', 'BgpPeerStateIdle', 'BgpPeerStateConnecting', 'BgpPeerStateConnected' - State BgpPeerState `json:"state,omitempty"` - // ConnectedDuration - READ-ONLY; For how long the peering has been up. - ConnectedDuration *string `json:"connectedDuration,omitempty"` - // RoutesReceived - READ-ONLY; The number of routes learned from this peer. - RoutesReceived *int64 `json:"routesReceived,omitempty"` - // MessagesSent - READ-ONLY; The number of BGP messages sent. - MessagesSent *int64 `json:"messagesSent,omitempty"` - // MessagesReceived - READ-ONLY; The number of BGP messages received. - MessagesReceived *int64 `json:"messagesReceived,omitempty"` -} - -// MarshalJSON is the custom marshaler for BgpPeerStatus. -func (bps BgpPeerStatus) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// BgpPeerStatusListResult response for list BGP peer status API service call. -type BgpPeerStatusListResult struct { - autorest.Response `json:"-"` - // Value - List of BGP peers. - Value *[]BgpPeerStatus `json:"value,omitempty"` -} - -// BgpServiceCommunity service Community Properties. -type BgpServiceCommunity struct { - // BgpServiceCommunityPropertiesFormat - Properties of the BGP service community. - *BgpServiceCommunityPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for BgpServiceCommunity. -func (bsc BgpServiceCommunity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if bsc.BgpServiceCommunityPropertiesFormat != nil { - objectMap["properties"] = bsc.BgpServiceCommunityPropertiesFormat - } - if bsc.ID != nil { - objectMap["id"] = bsc.ID - } - if bsc.Location != nil { - objectMap["location"] = bsc.Location - } - if bsc.Tags != nil { - objectMap["tags"] = bsc.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for BgpServiceCommunity struct. -func (bsc *BgpServiceCommunity) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var bgpServiceCommunityPropertiesFormat BgpServiceCommunityPropertiesFormat - err = json.Unmarshal(*v, &bgpServiceCommunityPropertiesFormat) - if err != nil { - return err - } - bsc.BgpServiceCommunityPropertiesFormat = &bgpServiceCommunityPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - bsc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - bsc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - bsc.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - bsc.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - bsc.Tags = tags - } - } - } - - return nil -} - -// BgpServiceCommunityListResult response for the ListServiceCommunity API service call. -type BgpServiceCommunityListResult struct { - autorest.Response `json:"-"` - // Value - A list of service community resources. - Value *[]BgpServiceCommunity `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// BgpServiceCommunityListResultIterator provides access to a complete listing of BgpServiceCommunity -// values. -type BgpServiceCommunityListResultIterator struct { - i int - page BgpServiceCommunityListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *BgpServiceCommunityListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BgpServiceCommunityListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *BgpServiceCommunityListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter BgpServiceCommunityListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter BgpServiceCommunityListResultIterator) Response() BgpServiceCommunityListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter BgpServiceCommunityListResultIterator) Value() BgpServiceCommunity { - if !iter.page.NotDone() { - return BgpServiceCommunity{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the BgpServiceCommunityListResultIterator type. -func NewBgpServiceCommunityListResultIterator(page BgpServiceCommunityListResultPage) BgpServiceCommunityListResultIterator { - return BgpServiceCommunityListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (bsclr BgpServiceCommunityListResult) IsEmpty() bool { - return bsclr.Value == nil || len(*bsclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (bsclr BgpServiceCommunityListResult) hasNextLink() bool { - return bsclr.NextLink != nil && len(*bsclr.NextLink) != 0 -} - -// bgpServiceCommunityListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (bsclr BgpServiceCommunityListResult) bgpServiceCommunityListResultPreparer(ctx context.Context) (*http.Request, error) { - if !bsclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(bsclr.NextLink))) -} - -// BgpServiceCommunityListResultPage contains a page of BgpServiceCommunity values. -type BgpServiceCommunityListResultPage struct { - fn func(context.Context, BgpServiceCommunityListResult) (BgpServiceCommunityListResult, error) - bsclr BgpServiceCommunityListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *BgpServiceCommunityListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BgpServiceCommunityListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.bsclr) - if err != nil { - return err - } - page.bsclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *BgpServiceCommunityListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page BgpServiceCommunityListResultPage) NotDone() bool { - return !page.bsclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page BgpServiceCommunityListResultPage) Response() BgpServiceCommunityListResult { - return page.bsclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page BgpServiceCommunityListResultPage) Values() []BgpServiceCommunity { - if page.bsclr.IsEmpty() { - return nil - } - return *page.bsclr.Value -} - -// Creates a new instance of the BgpServiceCommunityListResultPage type. -func NewBgpServiceCommunityListResultPage(cur BgpServiceCommunityListResult, getNextPage func(context.Context, BgpServiceCommunityListResult) (BgpServiceCommunityListResult, error)) BgpServiceCommunityListResultPage { - return BgpServiceCommunityListResultPage{ - fn: getNextPage, - bsclr: cur, - } -} - -// BgpServiceCommunityPropertiesFormat properties of Service Community. -type BgpServiceCommunityPropertiesFormat struct { - // ServiceName - The name of the bgp community. e.g. Skype. - ServiceName *string `json:"serviceName,omitempty"` - // BgpCommunities - A list of bgp communities. - BgpCommunities *[]BGPCommunity `json:"bgpCommunities,omitempty"` -} - -// BgpSettings BGP settings details. -type BgpSettings struct { - // Asn - The BGP speaker's ASN. - Asn *int64 `json:"asn,omitempty"` - // BgpPeeringAddress - The BGP peering address and BGP identifier of this BGP speaker. - BgpPeeringAddress *string `json:"bgpPeeringAddress,omitempty"` - // PeerWeight - The weight added to routes learned from this BGP speaker. - PeerWeight *int32 `json:"peerWeight,omitempty"` - // BgpPeeringAddresses - BGP peering address with IP configuration ID for virtual network gateway. - BgpPeeringAddresses *[]IPConfigurationBgpPeeringAddress `json:"bgpPeeringAddresses,omitempty"` -} - -// BreakOutCategoryPolicies network Virtual Appliance Sku Properties. -type BreakOutCategoryPolicies struct { - // Allow - Flag to control breakout of o365 allow category. - Allow *bool `json:"allow,omitempty"` - // Optimize - Flag to control breakout of o365 optimize category. - Optimize *bool `json:"optimize,omitempty"` - // Default - Flag to control breakout of o365 default category. - Default *bool `json:"default,omitempty"` -} - -// CheckPrivateLinkServiceVisibilityRequest request body of the CheckPrivateLinkServiceVisibility API -// service call. -type CheckPrivateLinkServiceVisibilityRequest struct { - // PrivateLinkServiceAlias - The alias of the private link service. - PrivateLinkServiceAlias *string `json:"privateLinkServiceAlias,omitempty"` -} - -// ChildResource proxy resource representation. -type ChildResource struct { - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for ChildResource. -func (cr ChildResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// CloudError an error response from the service. -type CloudError struct { - // Error - Cloud error body. - Error *CloudErrorBody `json:"error,omitempty"` -} - -// CloudErrorBody an error response from the service. -type CloudErrorBody struct { - // Code - An identifier for the error. Codes are invariant and are intended to be consumed programmatically. - Code *string `json:"code,omitempty"` - // Message - A message describing the error, intended to be suitable for display in a user interface. - Message *string `json:"message,omitempty"` - // Target - The target of the particular error. For example, the name of the property in error. - Target *string `json:"target,omitempty"` - // Details - A list of additional details about the error. - Details *[]CloudErrorBody `json:"details,omitempty"` -} - -// ConfigurationDiagnosticParameters parameters to get network configuration diagnostic. -type ConfigurationDiagnosticParameters struct { - // TargetResourceID - The ID of the target resource to perform network configuration diagnostic. Valid options are VM, NetworkInterface, VMSS/NetworkInterface and Application Gateway. - TargetResourceID *string `json:"targetResourceId,omitempty"` - // VerbosityLevel - Verbosity level. Possible values include: 'VerbosityLevelNormal', 'VerbosityLevelMinimum', 'VerbosityLevelFull' - VerbosityLevel VerbosityLevel `json:"verbosityLevel,omitempty"` - // Profiles - List of network configuration diagnostic profiles. - Profiles *[]ConfigurationDiagnosticProfile `json:"profiles,omitempty"` -} - -// ConfigurationDiagnosticProfile parameters to compare with network configuration. -type ConfigurationDiagnosticProfile struct { - // Direction - The direction of the traffic. Possible values include: 'Inbound', 'Outbound' - Direction Direction `json:"direction,omitempty"` - // Protocol - Protocol to be verified on. Accepted values are '*', TCP, UDP. - Protocol *string `json:"protocol,omitempty"` - // Source - Traffic source. Accepted values are '*', IP Address/CIDR, Service Tag. - Source *string `json:"source,omitempty"` - // Destination - Traffic destination. Accepted values are: '*', IP Address/CIDR, Service Tag. - Destination *string `json:"destination,omitempty"` - // DestinationPort - Traffic destination port. Accepted values are '*' and a single port in the range (0 - 65535). - DestinationPort *string `json:"destinationPort,omitempty"` -} - -// ConfigurationDiagnosticResponse results of network configuration diagnostic on the target resource. -type ConfigurationDiagnosticResponse struct { - autorest.Response `json:"-"` - // Results - READ-ONLY; List of network configuration diagnostic results. - Results *[]ConfigurationDiagnosticResult `json:"results,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConfigurationDiagnosticResponse. -func (cdr ConfigurationDiagnosticResponse) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ConfigurationDiagnosticResult network configuration diagnostic result corresponded to provided traffic -// query. -type ConfigurationDiagnosticResult struct { - // Profile - Network configuration diagnostic profile. - Profile *ConfigurationDiagnosticProfile `json:"profile,omitempty"` - // NetworkSecurityGroupResult - Network security group result. - NetworkSecurityGroupResult *SecurityGroupResult `json:"networkSecurityGroupResult,omitempty"` -} - -// ConfigurationGroup the network configuration group resource -type ConfigurationGroup struct { - // ID - Network group ID. - ID *string `json:"id,omitempty"` - // GroupProperties - The network configuration group properties - *GroupProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConfigurationGroup. -func (cg ConfigurationGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cg.ID != nil { - objectMap["id"] = cg.ID - } - if cg.GroupProperties != nil { - objectMap["properties"] = cg.GroupProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ConfigurationGroup struct. -func (cg *ConfigurationGroup) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cg.ID = &ID - } - case "properties": - if v != nil { - var groupProperties GroupProperties - err = json.Unmarshal(*v, &groupProperties) - if err != nil { - return err - } - cg.GroupProperties = &groupProperties - } - } - } - - return nil -} - -// ConfigurationPolicyGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type ConfigurationPolicyGroupsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConfigurationPolicyGroupsClient) (VpnServerConfigurationPolicyGroup, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConfigurationPolicyGroupsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConfigurationPolicyGroupsCreateOrUpdateFuture.Result. -func (future *ConfigurationPolicyGroupsCreateOrUpdateFuture) result(client ConfigurationPolicyGroupsClient) (vscpg VpnServerConfigurationPolicyGroup, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vscpg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ConfigurationPolicyGroupsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vscpg.Response.Response, err = future.GetResult(sender); err == nil && vscpg.Response.Response.StatusCode != http.StatusNoContent { - vscpg, err = client.CreateOrUpdateResponder(vscpg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsCreateOrUpdateFuture", "Result", vscpg.Response.Response, "Failure responding to request") - } - } - return -} - -// ConfigurationPolicyGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ConfigurationPolicyGroupsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConfigurationPolicyGroupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConfigurationPolicyGroupsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConfigurationPolicyGroupsDeleteFuture.Result. -func (future *ConfigurationPolicyGroupsDeleteFuture) result(client ConfigurationPolicyGroupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConfigurationPolicyGroupsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ConfigurationPolicyGroupsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ConnectionMonitor parameters that define the operation to create a connection monitor. -type ConnectionMonitor struct { - // Location - Connection monitor location. - Location *string `json:"location,omitempty"` - // Tags - Connection monitor tags. - Tags map[string]*string `json:"tags"` - // ConnectionMonitorParameters - Properties of the connection monitor. - *ConnectionMonitorParameters `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectionMonitor. -func (cm ConnectionMonitor) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cm.Location != nil { - objectMap["location"] = cm.Location - } - if cm.Tags != nil { - objectMap["tags"] = cm.Tags - } - if cm.ConnectionMonitorParameters != nil { - objectMap["properties"] = cm.ConnectionMonitorParameters - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ConnectionMonitor struct. -func (cm *ConnectionMonitor) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - cm.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - cm.Tags = tags - } - case "properties": - if v != nil { - var connectionMonitorParameters ConnectionMonitorParameters - err = json.Unmarshal(*v, &connectionMonitorParameters) - if err != nil { - return err - } - cm.ConnectionMonitorParameters = &connectionMonitorParameters - } - } - } - - return nil -} - -// ConnectionMonitorDestination describes the destination of connection monitor. -type ConnectionMonitorDestination struct { - // ResourceID - The ID of the resource used as the destination by connection monitor. - ResourceID *string `json:"resourceId,omitempty"` - // Address - Address of the connection monitor destination (IP or domain name). - Address *string `json:"address,omitempty"` - // Port - The destination port used by connection monitor. - Port *int32 `json:"port,omitempty"` -} - -// ConnectionMonitorEndpoint describes the connection monitor endpoint. -type ConnectionMonitorEndpoint struct { - // Name - The name of the connection monitor endpoint. - Name *string `json:"name,omitempty"` - // Type - The endpoint type. Possible values include: 'AzureVM', 'AzureVNet', 'AzureSubnet', 'ExternalAddress', 'MMAWorkspaceMachine', 'MMAWorkspaceNetwork', 'AzureArcVM', 'AzureVMSS' - Type EndpointType `json:"type,omitempty"` - // ResourceID - Resource ID of the connection monitor endpoint. - ResourceID *string `json:"resourceId,omitempty"` - // Address - Address of the connection monitor endpoint (IP or domain name). - Address *string `json:"address,omitempty"` - // Filter - Filter for sub-items within the endpoint. - Filter *ConnectionMonitorEndpointFilter `json:"filter,omitempty"` - // Scope - Endpoint scope. - Scope *ConnectionMonitorEndpointScope `json:"scope,omitempty"` - // CoverageLevel - Test coverage for the endpoint. Possible values include: 'Default', 'Low', 'BelowAverage', 'Average', 'AboveAverage', 'Full' - CoverageLevel CoverageLevel `json:"coverageLevel,omitempty"` -} - -// ConnectionMonitorEndpointFilter describes the connection monitor endpoint filter. -type ConnectionMonitorEndpointFilter struct { - // Type - The behavior of the endpoint filter. Currently only 'Include' is supported. Possible values include: 'Include' - Type ConnectionMonitorEndpointFilterType `json:"type,omitempty"` - // Items - List of items in the filter. - Items *[]ConnectionMonitorEndpointFilterItem `json:"items,omitempty"` -} - -// ConnectionMonitorEndpointFilterItem describes the connection monitor endpoint filter item. -type ConnectionMonitorEndpointFilterItem struct { - // Type - The type of item included in the filter. Currently only 'AgentAddress' is supported. Possible values include: 'AgentAddress' - Type ConnectionMonitorEndpointFilterItemType `json:"type,omitempty"` - // Address - The address of the filter item. - Address *string `json:"address,omitempty"` -} - -// ConnectionMonitorEndpointScope describes the connection monitor endpoint scope. -type ConnectionMonitorEndpointScope struct { - // Include - List of items which needs to be included to the endpoint scope. - Include *[]ConnectionMonitorEndpointScopeItem `json:"include,omitempty"` - // Exclude - List of items which needs to be excluded from the endpoint scope. - Exclude *[]ConnectionMonitorEndpointScopeItem `json:"exclude,omitempty"` -} - -// ConnectionMonitorEndpointScopeItem describes the connection monitor endpoint scope item. -type ConnectionMonitorEndpointScopeItem struct { - // Address - The address of the endpoint item. Supported types are IPv4/IPv6 subnet mask or IPv4/IPv6 IP address. - Address *string `json:"address,omitempty"` -} - -// ConnectionMonitorHTTPConfiguration describes the HTTP configuration. -type ConnectionMonitorHTTPConfiguration struct { - // Port - The port to connect to. - Port *int32 `json:"port,omitempty"` - // Method - The HTTP method to use. Possible values include: 'Get', 'Post' - Method HTTPConfigurationMethod `json:"method,omitempty"` - // Path - The path component of the URI. For instance, "/dir1/dir2". - Path *string `json:"path,omitempty"` - // RequestHeaders - The HTTP headers to transmit with the request. - RequestHeaders *[]HTTPHeader `json:"requestHeaders,omitempty"` - // ValidStatusCodeRanges - HTTP status codes to consider successful. For instance, "2xx,301-304,418". - ValidStatusCodeRanges *[]string `json:"validStatusCodeRanges,omitempty"` - // PreferHTTPS - Value indicating whether HTTPS is preferred over HTTP in cases where the choice is not explicit. - PreferHTTPS *bool `json:"preferHTTPS,omitempty"` -} - -// ConnectionMonitorIcmpConfiguration describes the ICMP configuration. -type ConnectionMonitorIcmpConfiguration struct { - // DisableTraceRoute - Value indicating whether path evaluation with trace route should be disabled. - DisableTraceRoute *bool `json:"disableTraceRoute,omitempty"` -} - -// ConnectionMonitorListResult list of connection monitors. -type ConnectionMonitorListResult struct { - autorest.Response `json:"-"` - // Value - Information about connection monitors. - Value *[]ConnectionMonitorResult `json:"value,omitempty"` -} - -// ConnectionMonitorOutput describes a connection monitor output destination. -type ConnectionMonitorOutput struct { - // Type - Connection monitor output destination type. Currently, only "Workspace" is supported. Possible values include: 'Workspace' - Type OutputType `json:"type,omitempty"` - // WorkspaceSettings - Describes the settings for producing output into a log analytics workspace. - WorkspaceSettings *ConnectionMonitorWorkspaceSettings `json:"workspaceSettings,omitempty"` -} - -// ConnectionMonitorParameters parameters that define the operation to create a connection monitor. -type ConnectionMonitorParameters struct { - // Source - Describes the source of connection monitor. - Source *ConnectionMonitorSource `json:"source,omitempty"` - // Destination - Describes the destination of connection monitor. - Destination *ConnectionMonitorDestination `json:"destination,omitempty"` - // AutoStart - Determines if the connection monitor will start automatically once created. - AutoStart *bool `json:"autoStart,omitempty"` - // MonitoringIntervalInSeconds - Monitoring interval in seconds. - MonitoringIntervalInSeconds *int32 `json:"monitoringIntervalInSeconds,omitempty"` - // Endpoints - List of connection monitor endpoints. - Endpoints *[]ConnectionMonitorEndpoint `json:"endpoints,omitempty"` - // TestConfigurations - List of connection monitor test configurations. - TestConfigurations *[]ConnectionMonitorTestConfiguration `json:"testConfigurations,omitempty"` - // TestGroups - List of connection monitor test groups. - TestGroups *[]ConnectionMonitorTestGroup `json:"testGroups,omitempty"` - // Outputs - List of connection monitor outputs. - Outputs *[]ConnectionMonitorOutput `json:"outputs,omitempty"` - // Notes - Optional notes to be associated with the connection monitor. - Notes *string `json:"notes,omitempty"` -} - -// ConnectionMonitorQueryResult list of connection states snapshots. -type ConnectionMonitorQueryResult struct { - autorest.Response `json:"-"` - // SourceStatus - Status of connection monitor source. Possible values include: 'ConnectionMonitorSourceStatusUnknown', 'ConnectionMonitorSourceStatusActive', 'ConnectionMonitorSourceStatusInactive' - SourceStatus ConnectionMonitorSourceStatus `json:"sourceStatus,omitempty"` - // States - Information about connection states. - States *[]ConnectionStateSnapshot `json:"states,omitempty"` -} - -// ConnectionMonitorResult information about the connection monitor. -type ConnectionMonitorResult struct { - autorest.Response `json:"-"` - // Name - READ-ONLY; Name of the connection monitor. - Name *string `json:"name,omitempty"` - // ID - READ-ONLY; ID of the connection monitor. - ID *string `json:"id,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Connection monitor type. - Type *string `json:"type,omitempty"` - // Location - Connection monitor location. - Location *string `json:"location,omitempty"` - // Tags - Connection monitor tags. - Tags map[string]*string `json:"tags"` - // ConnectionMonitorResultProperties - Properties of the connection monitor result. - *ConnectionMonitorResultProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectionMonitorResult. -func (cmr ConnectionMonitorResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cmr.Location != nil { - objectMap["location"] = cmr.Location - } - if cmr.Tags != nil { - objectMap["tags"] = cmr.Tags - } - if cmr.ConnectionMonitorResultProperties != nil { - objectMap["properties"] = cmr.ConnectionMonitorResultProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ConnectionMonitorResult struct. -func (cmr *ConnectionMonitorResult) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cmr.Name = &name - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cmr.ID = &ID - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - cmr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cmr.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - cmr.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - cmr.Tags = tags - } - case "properties": - if v != nil { - var connectionMonitorResultProperties ConnectionMonitorResultProperties - err = json.Unmarshal(*v, &connectionMonitorResultProperties) - if err != nil { - return err - } - cmr.ConnectionMonitorResultProperties = &connectionMonitorResultProperties - } - } - } - - return nil -} - -// ConnectionMonitorResultProperties describes the properties of a connection monitor. -type ConnectionMonitorResultProperties struct { - // ProvisioningState - READ-ONLY; The provisioning state of the connection monitor. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // StartTime - READ-ONLY; The date and time when the connection monitor was started. - StartTime *date.Time `json:"startTime,omitempty"` - // MonitoringStatus - READ-ONLY; The monitoring status of the connection monitor. - MonitoringStatus *string `json:"monitoringStatus,omitempty"` - // ConnectionMonitorType - READ-ONLY; Type of connection monitor. Possible values include: 'MultiEndpoint', 'SingleSourceDestination' - ConnectionMonitorType ConnectionMonitorType `json:"connectionMonitorType,omitempty"` - // Source - Describes the source of connection monitor. - Source *ConnectionMonitorSource `json:"source,omitempty"` - // Destination - Describes the destination of connection monitor. - Destination *ConnectionMonitorDestination `json:"destination,omitempty"` - // AutoStart - Determines if the connection monitor will start automatically once created. - AutoStart *bool `json:"autoStart,omitempty"` - // MonitoringIntervalInSeconds - Monitoring interval in seconds. - MonitoringIntervalInSeconds *int32 `json:"monitoringIntervalInSeconds,omitempty"` - // Endpoints - List of connection monitor endpoints. - Endpoints *[]ConnectionMonitorEndpoint `json:"endpoints,omitempty"` - // TestConfigurations - List of connection monitor test configurations. - TestConfigurations *[]ConnectionMonitorTestConfiguration `json:"testConfigurations,omitempty"` - // TestGroups - List of connection monitor test groups. - TestGroups *[]ConnectionMonitorTestGroup `json:"testGroups,omitempty"` - // Outputs - List of connection monitor outputs. - Outputs *[]ConnectionMonitorOutput `json:"outputs,omitempty"` - // Notes - Optional notes to be associated with the connection monitor. - Notes *string `json:"notes,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectionMonitorResultProperties. -func (cmrp ConnectionMonitorResultProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cmrp.Source != nil { - objectMap["source"] = cmrp.Source - } - if cmrp.Destination != nil { - objectMap["destination"] = cmrp.Destination - } - if cmrp.AutoStart != nil { - objectMap["autoStart"] = cmrp.AutoStart - } - if cmrp.MonitoringIntervalInSeconds != nil { - objectMap["monitoringIntervalInSeconds"] = cmrp.MonitoringIntervalInSeconds - } - if cmrp.Endpoints != nil { - objectMap["endpoints"] = cmrp.Endpoints - } - if cmrp.TestConfigurations != nil { - objectMap["testConfigurations"] = cmrp.TestConfigurations - } - if cmrp.TestGroups != nil { - objectMap["testGroups"] = cmrp.TestGroups - } - if cmrp.Outputs != nil { - objectMap["outputs"] = cmrp.Outputs - } - if cmrp.Notes != nil { - objectMap["notes"] = cmrp.Notes - } - return json.Marshal(objectMap) -} - -// ConnectionMonitorsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ConnectionMonitorsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConnectionMonitorsClient) (ConnectionMonitorResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConnectionMonitorsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConnectionMonitorsCreateOrUpdateFuture.Result. -func (future *ConnectionMonitorsCreateOrUpdateFuture) result(client ConnectionMonitorsClient) (cmr ConnectionMonitorResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cmr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ConnectionMonitorsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cmr.Response.Response, err = future.GetResult(sender); err == nil && cmr.Response.Response.StatusCode != http.StatusNoContent { - cmr, err = client.CreateOrUpdateResponder(cmr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsCreateOrUpdateFuture", "Result", cmr.Response.Response, "Failure responding to request") - } - } - return -} - -// ConnectionMonitorsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ConnectionMonitorsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConnectionMonitorsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConnectionMonitorsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConnectionMonitorsDeleteFuture.Result. -func (future *ConnectionMonitorsDeleteFuture) result(client ConnectionMonitorsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ConnectionMonitorsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ConnectionMonitorSource describes the source of connection monitor. -type ConnectionMonitorSource struct { - // ResourceID - The ID of the resource used as the source by connection monitor. - ResourceID *string `json:"resourceId,omitempty"` - // Port - The source port used by connection monitor. - Port *int32 `json:"port,omitempty"` -} - -// ConnectionMonitorsQueryFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ConnectionMonitorsQueryFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConnectionMonitorsClient) (ConnectionMonitorQueryResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConnectionMonitorsQueryFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConnectionMonitorsQueryFuture.Result. -func (future *ConnectionMonitorsQueryFuture) result(client ConnectionMonitorsClient) (cmqr ConnectionMonitorQueryResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsQueryFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cmqr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ConnectionMonitorsQueryFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cmqr.Response.Response, err = future.GetResult(sender); err == nil && cmqr.Response.Response.StatusCode != http.StatusNoContent { - cmqr, err = client.QueryResponder(cmqr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsQueryFuture", "Result", cmqr.Response.Response, "Failure responding to request") - } - } - return -} - -// ConnectionMonitorsStartFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ConnectionMonitorsStartFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConnectionMonitorsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConnectionMonitorsStartFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConnectionMonitorsStartFuture.Result. -func (future *ConnectionMonitorsStartFuture) result(client ConnectionMonitorsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsStartFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ConnectionMonitorsStartFuture") - return - } - ar.Response = future.Response() - return -} - -// ConnectionMonitorsStopFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ConnectionMonitorsStopFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConnectionMonitorsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConnectionMonitorsStopFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConnectionMonitorsStopFuture.Result. -func (future *ConnectionMonitorsStopFuture) result(client ConnectionMonitorsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectionMonitorsStopFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ConnectionMonitorsStopFuture") - return - } - ar.Response = future.Response() - return -} - -// ConnectionMonitorSuccessThreshold describes the threshold for declaring a test successful. -type ConnectionMonitorSuccessThreshold struct { - // ChecksFailedPercent - The maximum percentage of failed checks permitted for a test to evaluate as successful. - ChecksFailedPercent *int32 `json:"checksFailedPercent,omitempty"` - // RoundTripTimeMs - The maximum round-trip time in milliseconds permitted for a test to evaluate as successful. - RoundTripTimeMs *float64 `json:"roundTripTimeMs,omitempty"` -} - -// ConnectionMonitorTCPConfiguration describes the TCP configuration. -type ConnectionMonitorTCPConfiguration struct { - // Port - The port to connect to. - Port *int32 `json:"port,omitempty"` - // DisableTraceRoute - Value indicating whether path evaluation with trace route should be disabled. - DisableTraceRoute *bool `json:"disableTraceRoute,omitempty"` - // DestinationPortBehavior - Destination port behavior. Possible values include: 'DestinationPortBehaviorNone', 'DestinationPortBehaviorListenIfAvailable' - DestinationPortBehavior DestinationPortBehavior `json:"destinationPortBehavior,omitempty"` -} - -// ConnectionMonitorTestConfiguration describes a connection monitor test configuration. -type ConnectionMonitorTestConfiguration struct { - // Name - The name of the connection monitor test configuration. - Name *string `json:"name,omitempty"` - // TestFrequencySec - The frequency of test evaluation, in seconds. - TestFrequencySec *int32 `json:"testFrequencySec,omitempty"` - // Protocol - The protocol to use in test evaluation. Possible values include: 'ConnectionMonitorTestConfigurationProtocolTCP', 'ConnectionMonitorTestConfigurationProtocolHTTP', 'ConnectionMonitorTestConfigurationProtocolIcmp' - Protocol ConnectionMonitorTestConfigurationProtocol `json:"protocol,omitempty"` - // PreferredIPVersion - The preferred IP version to use in test evaluation. The connection monitor may choose to use a different version depending on other parameters. Possible values include: 'PreferredIPVersionIPv4', 'PreferredIPVersionIPv6' - PreferredIPVersion PreferredIPVersion `json:"preferredIPVersion,omitempty"` - // HTTPConfiguration - The parameters used to perform test evaluation over HTTP. - HTTPConfiguration *ConnectionMonitorHTTPConfiguration `json:"httpConfiguration,omitempty"` - // TCPConfiguration - The parameters used to perform test evaluation over TCP. - TCPConfiguration *ConnectionMonitorTCPConfiguration `json:"tcpConfiguration,omitempty"` - // IcmpConfiguration - The parameters used to perform test evaluation over ICMP. - IcmpConfiguration *ConnectionMonitorIcmpConfiguration `json:"icmpConfiguration,omitempty"` - // SuccessThreshold - The threshold for declaring a test successful. - SuccessThreshold *ConnectionMonitorSuccessThreshold `json:"successThreshold,omitempty"` -} - -// ConnectionMonitorTestGroup describes the connection monitor test group. -type ConnectionMonitorTestGroup struct { - // Name - The name of the connection monitor test group. - Name *string `json:"name,omitempty"` - // Disable - Value indicating whether test group is disabled. - Disable *bool `json:"disable,omitempty"` - // TestConfigurations - List of test configuration names. - TestConfigurations *[]string `json:"testConfigurations,omitempty"` - // Sources - List of source endpoint names. - Sources *[]string `json:"sources,omitempty"` - // Destinations - List of destination endpoint names. - Destinations *[]string `json:"destinations,omitempty"` -} - -// ConnectionMonitorWorkspaceSettings describes the settings for producing output into a log analytics -// workspace. -type ConnectionMonitorWorkspaceSettings struct { - // WorkspaceResourceID - Log analytics workspace resource ID. - WorkspaceResourceID *string `json:"workspaceResourceId,omitempty"` -} - -// ConnectionResetSharedKey the virtual network connection reset shared key. -type ConnectionResetSharedKey struct { - autorest.Response `json:"-"` - // KeyLength - The virtual network connection reset shared key length, should between 1 and 128. - KeyLength *int32 `json:"keyLength,omitempty"` -} - -// ConnectionSharedKey response for GetConnectionSharedKey API service call. -type ConnectionSharedKey struct { - autorest.Response `json:"-"` - // Value - The virtual network connection shared key value. - Value *string `json:"value,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// ConnectionStateSnapshot connection state snapshot. -type ConnectionStateSnapshot struct { - // ConnectionState - The connection state. Possible values include: 'ConnectionStateReachable', 'ConnectionStateUnreachable', 'ConnectionStateUnknown' - ConnectionState ConnectionState `json:"connectionState,omitempty"` - // StartTime - The start time of the connection snapshot. - StartTime *date.Time `json:"startTime,omitempty"` - // EndTime - The end time of the connection snapshot. - EndTime *date.Time `json:"endTime,omitempty"` - // EvaluationState - Connectivity analysis evaluation state. Possible values include: 'EvaluationStateNotStarted', 'EvaluationStateInProgress', 'EvaluationStateCompleted' - EvaluationState EvaluationState `json:"evaluationState,omitempty"` - // AvgLatencyInMs - Average latency in ms. - AvgLatencyInMs *int64 `json:"avgLatencyInMs,omitempty"` - // MinLatencyInMs - Minimum latency in ms. - MinLatencyInMs *int64 `json:"minLatencyInMs,omitempty"` - // MaxLatencyInMs - Maximum latency in ms. - MaxLatencyInMs *int64 `json:"maxLatencyInMs,omitempty"` - // ProbesSent - The number of sent probes. - ProbesSent *int64 `json:"probesSent,omitempty"` - // ProbesFailed - The number of failed probes. - ProbesFailed *int64 `json:"probesFailed,omitempty"` - // Hops - READ-ONLY; List of hops between the source and the destination. - Hops *[]ConnectivityHop `json:"hops,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectionStateSnapshot. -func (CSS ConnectionStateSnapshot) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if CSS.ConnectionState != "" { - objectMap["connectionState"] = CSS.ConnectionState - } - if CSS.StartTime != nil { - objectMap["startTime"] = CSS.StartTime - } - if CSS.EndTime != nil { - objectMap["endTime"] = CSS.EndTime - } - if CSS.EvaluationState != "" { - objectMap["evaluationState"] = CSS.EvaluationState - } - if CSS.AvgLatencyInMs != nil { - objectMap["avgLatencyInMs"] = CSS.AvgLatencyInMs - } - if CSS.MinLatencyInMs != nil { - objectMap["minLatencyInMs"] = CSS.MinLatencyInMs - } - if CSS.MaxLatencyInMs != nil { - objectMap["maxLatencyInMs"] = CSS.MaxLatencyInMs - } - if CSS.ProbesSent != nil { - objectMap["probesSent"] = CSS.ProbesSent - } - if CSS.ProbesFailed != nil { - objectMap["probesFailed"] = CSS.ProbesFailed - } - return json.Marshal(objectMap) -} - -// ConnectivityConfiguration the network manager connectivity configuration resource -type ConnectivityConfiguration struct { - autorest.Response `json:"-"` - // ConnectivityConfigurationProperties - Properties of a network manager connectivity configuration - *ConnectivityConfigurationProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system metadata related to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectivityConfiguration. -func (cc ConnectivityConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cc.ConnectivityConfigurationProperties != nil { - objectMap["properties"] = cc.ConnectivityConfigurationProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ConnectivityConfiguration struct. -func (cc *ConnectivityConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var connectivityConfigurationProperties ConnectivityConfigurationProperties - err = json.Unmarshal(*v, &connectivityConfigurationProperties) - if err != nil { - return err - } - cc.ConnectivityConfigurationProperties = &connectivityConfigurationProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - cc.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cc.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - cc.Etag = &etag - } - } - } - - return nil -} - -// ConnectivityConfigurationListResult result of the request to list network manager connectivity -// configurations. It contains a list of configurations and a link to get the next set of results. -type ConnectivityConfigurationListResult struct { - autorest.Response `json:"-"` - // Value - Gets a page of Connectivity Configurations - Value *[]ConnectivityConfiguration `json:"value,omitempty"` - // NextLink - Gets the URL to get the next page of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ConnectivityConfigurationListResultIterator provides access to a complete listing of -// ConnectivityConfiguration values. -type ConnectivityConfigurationListResultIterator struct { - i int - page ConnectivityConfigurationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ConnectivityConfigurationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectivityConfigurationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ConnectivityConfigurationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ConnectivityConfigurationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ConnectivityConfigurationListResultIterator) Response() ConnectivityConfigurationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ConnectivityConfigurationListResultIterator) Value() ConnectivityConfiguration { - if !iter.page.NotDone() { - return ConnectivityConfiguration{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ConnectivityConfigurationListResultIterator type. -func NewConnectivityConfigurationListResultIterator(page ConnectivityConfigurationListResultPage) ConnectivityConfigurationListResultIterator { - return ConnectivityConfigurationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (cclr ConnectivityConfigurationListResult) IsEmpty() bool { - return cclr.Value == nil || len(*cclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (cclr ConnectivityConfigurationListResult) hasNextLink() bool { - return cclr.NextLink != nil && len(*cclr.NextLink) != 0 -} - -// connectivityConfigurationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (cclr ConnectivityConfigurationListResult) connectivityConfigurationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !cclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(cclr.NextLink))) -} - -// ConnectivityConfigurationListResultPage contains a page of ConnectivityConfiguration values. -type ConnectivityConfigurationListResultPage struct { - fn func(context.Context, ConnectivityConfigurationListResult) (ConnectivityConfigurationListResult, error) - cclr ConnectivityConfigurationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ConnectivityConfigurationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ConnectivityConfigurationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.cclr) - if err != nil { - return err - } - page.cclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ConnectivityConfigurationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ConnectivityConfigurationListResultPage) NotDone() bool { - return !page.cclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ConnectivityConfigurationListResultPage) Response() ConnectivityConfigurationListResult { - return page.cclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ConnectivityConfigurationListResultPage) Values() []ConnectivityConfiguration { - if page.cclr.IsEmpty() { - return nil - } - return *page.cclr.Value -} - -// Creates a new instance of the ConnectivityConfigurationListResultPage type. -func NewConnectivityConfigurationListResultPage(cur ConnectivityConfigurationListResult, getNextPage func(context.Context, ConnectivityConfigurationListResult) (ConnectivityConfigurationListResult, error)) ConnectivityConfigurationListResultPage { - return ConnectivityConfigurationListResultPage{ - fn: getNextPage, - cclr: cur, - } -} - -// ConnectivityConfigurationProperties properties of network manager connectivity configuration -type ConnectivityConfigurationProperties struct { - // Description - A description of the connectivity configuration. - Description *string `json:"description,omitempty"` - // ConnectivityTopology - Connectivity topology type. Possible values include: 'HubAndSpoke', 'Mesh' - ConnectivityTopology ConnectivityTopology `json:"connectivityTopology,omitempty"` - // Hubs - List of hubItems - Hubs *[]Hub `json:"hubs,omitempty"` - // IsGlobal - Flag if global mesh is supported. Possible values include: 'IsGlobalFalse', 'IsGlobalTrue' - IsGlobal IsGlobal `json:"isGlobal,omitempty"` - // AppliesToGroups - Groups for configuration - AppliesToGroups *[]ConnectivityGroupItem `json:"appliesToGroups,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the connectivity configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // DeleteExistingPeering - Flag if need to remove current existing peerings. Possible values include: 'False', 'True' - DeleteExistingPeering DeleteExistingPeering `json:"deleteExistingPeering,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectivityConfigurationProperties. -func (ccp ConnectivityConfigurationProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ccp.Description != nil { - objectMap["description"] = ccp.Description - } - if ccp.ConnectivityTopology != "" { - objectMap["connectivityTopology"] = ccp.ConnectivityTopology - } - if ccp.Hubs != nil { - objectMap["hubs"] = ccp.Hubs - } - if ccp.IsGlobal != "" { - objectMap["isGlobal"] = ccp.IsGlobal - } - if ccp.AppliesToGroups != nil { - objectMap["appliesToGroups"] = ccp.AppliesToGroups - } - if ccp.DeleteExistingPeering != "" { - objectMap["deleteExistingPeering"] = ccp.DeleteExistingPeering - } - return json.Marshal(objectMap) -} - -// ConnectivityConfigurationsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ConnectivityConfigurationsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ConnectivityConfigurationsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ConnectivityConfigurationsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ConnectivityConfigurationsDeleteFuture.Result. -func (future *ConnectivityConfigurationsDeleteFuture) result(client ConnectivityConfigurationsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ConnectivityConfigurationsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ConnectivityConfigurationsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ConnectivityDestination parameters that define destination of connection. -type ConnectivityDestination struct { - // ResourceID - The ID of the resource to which a connection attempt will be made. - ResourceID *string `json:"resourceId,omitempty"` - // Address - The IP address or URI the resource to which a connection attempt will be made. - Address *string `json:"address,omitempty"` - // Port - Port on which check connectivity will be performed. - Port *int32 `json:"port,omitempty"` -} - -// ConnectivityGroupItem connectivity group item. -type ConnectivityGroupItem struct { - // NetworkGroupID - Network group Id. - NetworkGroupID *string `json:"networkGroupId,omitempty"` - // UseHubGateway - Flag if need to use hub gateway. Possible values include: 'UseHubGatewayFalse', 'UseHubGatewayTrue' - UseHubGateway UseHubGateway `json:"useHubGateway,omitempty"` - // IsGlobal - Flag if global is supported. Possible values include: 'IsGlobalFalse', 'IsGlobalTrue' - IsGlobal IsGlobal `json:"isGlobal,omitempty"` - // GroupConnectivity - Group connectivity type. Possible values include: 'GroupConnectivityNone', 'GroupConnectivityDirectlyConnected' - GroupConnectivity GroupConnectivity `json:"groupConnectivity,omitempty"` -} - -// ConnectivityHop information about a hop between the source and the destination. -type ConnectivityHop struct { - // Type - READ-ONLY; The type of the hop. - Type *string `json:"type,omitempty"` - // ID - READ-ONLY; The ID of the hop. - ID *string `json:"id,omitempty"` - // Address - READ-ONLY; The IP address of the hop. - Address *string `json:"address,omitempty"` - // ResourceID - READ-ONLY; The ID of the resource corresponding to this hop. - ResourceID *string `json:"resourceId,omitempty"` - // NextHopIds - READ-ONLY; List of next hop identifiers. - NextHopIds *[]string `json:"nextHopIds,omitempty"` - // PreviousHopIds - READ-ONLY; List of previous hop identifiers. - PreviousHopIds *[]string `json:"previousHopIds,omitempty"` - // Links - READ-ONLY; List of hop links. - Links *[]HopLink `json:"links,omitempty"` - // PreviousLinks - READ-ONLY; List of previous hop links. - PreviousLinks *[]HopLink `json:"previousLinks,omitempty"` - // Issues - READ-ONLY; List of issues. - Issues *[]ConnectivityIssue `json:"issues,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectivityHop. -func (ch ConnectivityHop) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ConnectivityInformation information on the connectivity status. -type ConnectivityInformation struct { - autorest.Response `json:"-"` - // Hops - READ-ONLY; List of hops between the source and the destination. - Hops *[]ConnectivityHop `json:"hops,omitempty"` - // ConnectionStatus - READ-ONLY; The connection status. Possible values include: 'ConnectionStatusUnknown', 'ConnectionStatusConnected', 'ConnectionStatusDisconnected', 'ConnectionStatusDegraded' - ConnectionStatus ConnectionStatus `json:"connectionStatus,omitempty"` - // AvgLatencyInMs - READ-ONLY; Average latency in milliseconds. - AvgLatencyInMs *int32 `json:"avgLatencyInMs,omitempty"` - // MinLatencyInMs - READ-ONLY; Minimum latency in milliseconds. - MinLatencyInMs *int32 `json:"minLatencyInMs,omitempty"` - // MaxLatencyInMs - READ-ONLY; Maximum latency in milliseconds. - MaxLatencyInMs *int32 `json:"maxLatencyInMs,omitempty"` - // ProbesSent - READ-ONLY; Total number of probes sent. - ProbesSent *int32 `json:"probesSent,omitempty"` - // ProbesFailed - READ-ONLY; Number of failed probes. - ProbesFailed *int32 `json:"probesFailed,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectivityInformation. -func (ci ConnectivityInformation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ConnectivityIssue information about an issue encountered in the process of checking for connectivity. -type ConnectivityIssue struct { - // Origin - READ-ONLY; The origin of the issue. Possible values include: 'OriginLocal', 'OriginInbound', 'OriginOutbound' - Origin Origin `json:"origin,omitempty"` - // Severity - READ-ONLY; The severity of the issue. Possible values include: 'SeverityError', 'SeverityWarning' - Severity Severity `json:"severity,omitempty"` - // Type - READ-ONLY; The type of issue. Possible values include: 'IssueTypeUnknown', 'IssueTypeAgentStopped', 'IssueTypeGuestFirewall', 'IssueTypeDNSResolution', 'IssueTypeSocketBind', 'IssueTypeNetworkSecurityRule', 'IssueTypeUserDefinedRoute', 'IssueTypePortThrottled', 'IssueTypePlatform' - Type IssueType `json:"type,omitempty"` - // Context - READ-ONLY; Provides additional context on the issue. - Context *[]map[string]*string `json:"context,omitempty"` -} - -// MarshalJSON is the custom marshaler for ConnectivityIssue. -func (ci ConnectivityIssue) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ConnectivityParameters parameters that determine how the connectivity check will be performed. -type ConnectivityParameters struct { - // Source - The source of the connection. - Source *ConnectivitySource `json:"source,omitempty"` - // Destination - The destination of connection. - Destination *ConnectivityDestination `json:"destination,omitempty"` - // Protocol - Network protocol. Possible values include: 'ProtocolTCP', 'ProtocolHTTP', 'ProtocolHTTPS', 'ProtocolIcmp' - Protocol Protocol `json:"protocol,omitempty"` - // ProtocolConfiguration - Configuration of the protocol. - ProtocolConfiguration *ProtocolConfiguration `json:"protocolConfiguration,omitempty"` - // PreferredIPVersion - Preferred IP version of the connection. Possible values include: 'IPv4', 'IPv6' - PreferredIPVersion IPVersion `json:"preferredIPVersion,omitempty"` -} - -// ConnectivitySource parameters that define the source of the connection. -type ConnectivitySource struct { - // ResourceID - The ID of the resource from which a connectivity check will be initiated. - ResourceID *string `json:"resourceId,omitempty"` - // Port - The source port from which a connectivity check will be performed. - Port *int32 `json:"port,omitempty"` -} - -// Container reference to container resource in remote resource provider. -type Container struct { - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// ContainerNetworkInterface container network interface child resource. -type ContainerNetworkInterface struct { - // ContainerNetworkInterfacePropertiesFormat - Container network interface properties. - *ContainerNetworkInterfacePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Sub Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerNetworkInterface. -func (cni ContainerNetworkInterface) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cni.ContainerNetworkInterfacePropertiesFormat != nil { - objectMap["properties"] = cni.ContainerNetworkInterfacePropertiesFormat - } - if cni.Name != nil { - objectMap["name"] = cni.Name - } - if cni.ID != nil { - objectMap["id"] = cni.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ContainerNetworkInterface struct. -func (cni *ContainerNetworkInterface) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var containerNetworkInterfacePropertiesFormat ContainerNetworkInterfacePropertiesFormat - err = json.Unmarshal(*v, &containerNetworkInterfacePropertiesFormat) - if err != nil { - return err - } - cni.ContainerNetworkInterfacePropertiesFormat = &containerNetworkInterfacePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cni.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cni.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - cni.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cni.ID = &ID - } - } - } - - return nil -} - -// ContainerNetworkInterfaceConfiguration container network interface configuration child resource. -type ContainerNetworkInterfaceConfiguration struct { - // ContainerNetworkInterfaceConfigurationPropertiesFormat - Container network interface configuration properties. - *ContainerNetworkInterfaceConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Sub Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerNetworkInterfaceConfiguration. -func (cnic ContainerNetworkInterfaceConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cnic.ContainerNetworkInterfaceConfigurationPropertiesFormat != nil { - objectMap["properties"] = cnic.ContainerNetworkInterfaceConfigurationPropertiesFormat - } - if cnic.Name != nil { - objectMap["name"] = cnic.Name - } - if cnic.ID != nil { - objectMap["id"] = cnic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ContainerNetworkInterfaceConfiguration struct. -func (cnic *ContainerNetworkInterfaceConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var containerNetworkInterfaceConfigurationPropertiesFormat ContainerNetworkInterfaceConfigurationPropertiesFormat - err = json.Unmarshal(*v, &containerNetworkInterfaceConfigurationPropertiesFormat) - if err != nil { - return err - } - cnic.ContainerNetworkInterfaceConfigurationPropertiesFormat = &containerNetworkInterfaceConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cnic.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cnic.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - cnic.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cnic.ID = &ID - } - } - } - - return nil -} - -// ContainerNetworkInterfaceConfigurationPropertiesFormat container network interface configuration -// properties. -type ContainerNetworkInterfaceConfigurationPropertiesFormat struct { - // IPConfigurations - A list of ip configurations of the container network interface configuration. - IPConfigurations *[]IPConfigurationProfile `json:"ipConfigurations,omitempty"` - // ContainerNetworkInterfaces - A list of container network interfaces created from this container network interface configuration. - ContainerNetworkInterfaces *[]SubResource `json:"containerNetworkInterfaces,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the container network interface configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerNetworkInterfaceConfigurationPropertiesFormat. -func (cnicpf ContainerNetworkInterfaceConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cnicpf.IPConfigurations != nil { - objectMap["ipConfigurations"] = cnicpf.IPConfigurations - } - if cnicpf.ContainerNetworkInterfaces != nil { - objectMap["containerNetworkInterfaces"] = cnicpf.ContainerNetworkInterfaces - } - return json.Marshal(objectMap) -} - -// ContainerNetworkInterfaceIPConfiguration the ip configuration for a container network interface. -type ContainerNetworkInterfaceIPConfiguration struct { - // ContainerNetworkInterfaceIPConfigurationPropertiesFormat - Properties of the container network interface IP configuration. - *ContainerNetworkInterfaceIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Sub Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerNetworkInterfaceIPConfiguration. -func (cniic ContainerNetworkInterfaceIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cniic.ContainerNetworkInterfaceIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = cniic.ContainerNetworkInterfaceIPConfigurationPropertiesFormat - } - if cniic.Name != nil { - objectMap["name"] = cniic.Name - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ContainerNetworkInterfaceIPConfiguration struct. -func (cniic *ContainerNetworkInterfaceIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var containerNetworkInterfaceIPConfigurationPropertiesFormat ContainerNetworkInterfaceIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &containerNetworkInterfaceIPConfigurationPropertiesFormat) - if err != nil { - return err - } - cniic.ContainerNetworkInterfaceIPConfigurationPropertiesFormat = &containerNetworkInterfaceIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cniic.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cniic.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - cniic.Etag = &etag - } - } - } - - return nil -} - -// ContainerNetworkInterfaceIPConfigurationPropertiesFormat properties of the container network interface -// IP configuration. -type ContainerNetworkInterfaceIPConfigurationPropertiesFormat struct { - // ProvisioningState - READ-ONLY; The provisioning state of the container network interface IP configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerNetworkInterfaceIPConfigurationPropertiesFormat. -func (cniicpf ContainerNetworkInterfaceIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ContainerNetworkInterfacePropertiesFormat properties of container network interface. -type ContainerNetworkInterfacePropertiesFormat struct { - // ContainerNetworkInterfaceConfiguration - READ-ONLY; Container network interface configuration from which this container network interface is created. - ContainerNetworkInterfaceConfiguration *ContainerNetworkInterfaceConfiguration `json:"containerNetworkInterfaceConfiguration,omitempty"` - // Container - Reference to the container to which this container network interface is attached. - Container *Container `json:"container,omitempty"` - // IPConfigurations - READ-ONLY; Reference to the ip configuration on this container nic. - IPConfigurations *[]ContainerNetworkInterfaceIPConfiguration `json:"ipConfigurations,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the container network interface resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ContainerNetworkInterfacePropertiesFormat. -func (cnipf ContainerNetworkInterfacePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cnipf.Container != nil { - objectMap["container"] = cnipf.Container - } - return json.Marshal(objectMap) -} - -// Criterion a matching criteria which matches routes based on route prefix, community, and AS path. -type Criterion struct { - // RoutePrefix - List of route prefixes which this criteria matches. - RoutePrefix *[]string `json:"routePrefix,omitempty"` - // Community - List of BGP communities which this criteria matches. - Community *[]string `json:"community,omitempty"` - // AsPath - List of AS paths which this criteria matches. - AsPath *[]string `json:"asPath,omitempty"` - // MatchCondition - Match condition to apply RouteMap rules. Possible values include: 'RouteMapMatchConditionUnknown', 'RouteMapMatchConditionContains', 'RouteMapMatchConditionEquals', 'RouteMapMatchConditionNotContains', 'RouteMapMatchConditionNotEquals' - MatchCondition RouteMapMatchCondition `json:"matchCondition,omitempty"` -} - -// CrossTenantScopes cross tenant scopes. -type CrossTenantScopes struct { - // TenantID - READ-ONLY; Tenant ID. - TenantID *string `json:"tenantId,omitempty"` - // ManagementGroups - READ-ONLY; List of management groups. - ManagementGroups *[]string `json:"managementGroups,omitempty"` - // Subscriptions - READ-ONLY; List of subscriptions. - Subscriptions *[]string `json:"subscriptions,omitempty"` -} - -// MarshalJSON is the custom marshaler for CrossTenantScopes. -func (cts CrossTenantScopes) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// CustomDNSConfigPropertiesFormat contains custom Dns resolution configuration from customer. -type CustomDNSConfigPropertiesFormat struct { - // Fqdn - Fqdn that resolves to private endpoint ip address. - Fqdn *string `json:"fqdn,omitempty"` - // IPAddresses - A list of private ip addresses of the private endpoint. - IPAddresses *[]string `json:"ipAddresses,omitempty"` -} - -// CustomIPPrefix custom IP prefix resource. -type CustomIPPrefix struct { - autorest.Response `json:"-"` - // ExtendedLocation - The extended location of the custom IP prefix. - ExtendedLocation *ExtendedLocation `json:"extendedLocation,omitempty"` - // CustomIPPrefixPropertiesFormat - Custom IP prefix properties. - *CustomIPPrefixPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Zones - A list of availability zones denoting the IP allocated for the resource needs to come from. - Zones *[]string `json:"zones,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for CustomIPPrefix. -func (cip CustomIPPrefix) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cip.ExtendedLocation != nil { - objectMap["extendedLocation"] = cip.ExtendedLocation - } - if cip.CustomIPPrefixPropertiesFormat != nil { - objectMap["properties"] = cip.CustomIPPrefixPropertiesFormat - } - if cip.Zones != nil { - objectMap["zones"] = cip.Zones - } - if cip.ID != nil { - objectMap["id"] = cip.ID - } - if cip.Location != nil { - objectMap["location"] = cip.Location - } - if cip.Tags != nil { - objectMap["tags"] = cip.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for CustomIPPrefix struct. -func (cip *CustomIPPrefix) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "extendedLocation": - if v != nil { - var extendedLocation ExtendedLocation - err = json.Unmarshal(*v, &extendedLocation) - if err != nil { - return err - } - cip.ExtendedLocation = &extendedLocation - } - case "properties": - if v != nil { - var customIPPrefixPropertiesFormat CustomIPPrefixPropertiesFormat - err = json.Unmarshal(*v, &customIPPrefixPropertiesFormat) - if err != nil { - return err - } - cip.CustomIPPrefixPropertiesFormat = &customIPPrefixPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - cip.Etag = &etag - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - cip.Zones = &zones - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - cip.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - cip.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - cip.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - cip.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - cip.Tags = tags - } - } - } - - return nil -} - -// CustomIPPrefixesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type CustomIPPrefixesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(CustomIPPrefixesClient) (CustomIPPrefix, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *CustomIPPrefixesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for CustomIPPrefixesCreateOrUpdateFuture.Result. -func (future *CustomIPPrefixesCreateOrUpdateFuture) result(client CustomIPPrefixesClient) (cip CustomIPPrefix, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cip.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.CustomIPPrefixesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cip.Response.Response, err = future.GetResult(sender); err == nil && cip.Response.Response.StatusCode != http.StatusNoContent { - cip, err = client.CreateOrUpdateResponder(cip.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesCreateOrUpdateFuture", "Result", cip.Response.Response, "Failure responding to request") - } - } - return -} - -// CustomIPPrefixesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type CustomIPPrefixesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(CustomIPPrefixesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *CustomIPPrefixesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for CustomIPPrefixesDeleteFuture.Result. -func (future *CustomIPPrefixesDeleteFuture) result(client CustomIPPrefixesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.CustomIPPrefixesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.CustomIPPrefixesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// CustomIPPrefixListResult response for ListCustomIpPrefixes API service call. -type CustomIPPrefixListResult struct { - autorest.Response `json:"-"` - // Value - A list of Custom IP prefixes that exists in a resource group. - Value *[]CustomIPPrefix `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// CustomIPPrefixListResultIterator provides access to a complete listing of CustomIPPrefix values. -type CustomIPPrefixListResultIterator struct { - i int - page CustomIPPrefixListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *CustomIPPrefixListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomIPPrefixListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *CustomIPPrefixListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter CustomIPPrefixListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter CustomIPPrefixListResultIterator) Response() CustomIPPrefixListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter CustomIPPrefixListResultIterator) Value() CustomIPPrefix { - if !iter.page.NotDone() { - return CustomIPPrefix{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the CustomIPPrefixListResultIterator type. -func NewCustomIPPrefixListResultIterator(page CustomIPPrefixListResultPage) CustomIPPrefixListResultIterator { - return CustomIPPrefixListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ciplr CustomIPPrefixListResult) IsEmpty() bool { - return ciplr.Value == nil || len(*ciplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ciplr CustomIPPrefixListResult) hasNextLink() bool { - return ciplr.NextLink != nil && len(*ciplr.NextLink) != 0 -} - -// customIPPrefixListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ciplr CustomIPPrefixListResult) customIPPrefixListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ciplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ciplr.NextLink))) -} - -// CustomIPPrefixListResultPage contains a page of CustomIPPrefix values. -type CustomIPPrefixListResultPage struct { - fn func(context.Context, CustomIPPrefixListResult) (CustomIPPrefixListResult, error) - ciplr CustomIPPrefixListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *CustomIPPrefixListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CustomIPPrefixListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ciplr) - if err != nil { - return err - } - page.ciplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *CustomIPPrefixListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page CustomIPPrefixListResultPage) NotDone() bool { - return !page.ciplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page CustomIPPrefixListResultPage) Response() CustomIPPrefixListResult { - return page.ciplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page CustomIPPrefixListResultPage) Values() []CustomIPPrefix { - if page.ciplr.IsEmpty() { - return nil - } - return *page.ciplr.Value -} - -// Creates a new instance of the CustomIPPrefixListResultPage type. -func NewCustomIPPrefixListResultPage(cur CustomIPPrefixListResult, getNextPage func(context.Context, CustomIPPrefixListResult) (CustomIPPrefixListResult, error)) CustomIPPrefixListResultPage { - return CustomIPPrefixListResultPage{ - fn: getNextPage, - ciplr: cur, - } -} - -// CustomIPPrefixPropertiesFormat custom IP prefix properties. -type CustomIPPrefixPropertiesFormat struct { - // Asn - The ASN for CIDR advertising. Should be an integer as string. - Asn *string `json:"asn,omitempty"` - // Cidr - The prefix range in CIDR notation. Should include the start address and the prefix length. - Cidr *string `json:"cidr,omitempty"` - // SignedMessage - Signed message for WAN validation. - SignedMessage *string `json:"signedMessage,omitempty"` - // AuthorizationMessage - Authorization message for WAN validation. - AuthorizationMessage *string `json:"authorizationMessage,omitempty"` - // CustomIPPrefixParent - The Parent CustomIpPrefix for IPv6 /64 CustomIpPrefix. - CustomIPPrefixParent *SubResource `json:"customIpPrefixParent,omitempty"` - // ChildCustomIPPrefixes - READ-ONLY; The list of all Children for IPv6 /48 CustomIpPrefix. - ChildCustomIPPrefixes *[]SubResource `json:"childCustomIpPrefixes,omitempty"` - // CommissionedState - The commissioned state of the Custom IP Prefix. Possible values include: 'Provisioning', 'Provisioned', 'Commissioning', 'CommissionedNoInternetAdvertise', 'Commissioned', 'Decommissioning', 'Deprovisioning', 'Deprovisioned' - CommissionedState CommissionedState `json:"commissionedState,omitempty"` - // ExpressRouteAdvertise - Whether to do express route advertise. - ExpressRouteAdvertise *bool `json:"expressRouteAdvertise,omitempty"` - // Geo - The Geo for CIDR advertising. Should be an Geo code. Possible values include: 'GLOBAL', 'AFRI', 'APAC', 'EURO', 'LATAM', 'NAM', 'ME', 'OCEANIA', 'AQ' - Geo Geo `json:"geo,omitempty"` - // NoInternetAdvertise - Whether to Advertise the range to Internet. - NoInternetAdvertise *bool `json:"noInternetAdvertise,omitempty"` - // PrefixType - Type of custom IP prefix. Should be Singular, Parent, or Child. Possible values include: 'Singular', 'Parent', 'Child' - PrefixType CustomIPPrefixType `json:"prefixType,omitempty"` - // PublicIPPrefixes - READ-ONLY; The list of all referenced PublicIpPrefixes. - PublicIPPrefixes *[]SubResource `json:"publicIpPrefixes,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the custom IP prefix resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // FailedReason - READ-ONLY; The reason why resource is in failed state. - FailedReason *string `json:"failedReason,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the custom IP prefix resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for CustomIPPrefixPropertiesFormat. -func (cippf CustomIPPrefixPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cippf.Asn != nil { - objectMap["asn"] = cippf.Asn - } - if cippf.Cidr != nil { - objectMap["cidr"] = cippf.Cidr - } - if cippf.SignedMessage != nil { - objectMap["signedMessage"] = cippf.SignedMessage - } - if cippf.AuthorizationMessage != nil { - objectMap["authorizationMessage"] = cippf.AuthorizationMessage - } - if cippf.CustomIPPrefixParent != nil { - objectMap["customIpPrefixParent"] = cippf.CustomIPPrefixParent - } - if cippf.CommissionedState != "" { - objectMap["commissionedState"] = cippf.CommissionedState - } - if cippf.ExpressRouteAdvertise != nil { - objectMap["expressRouteAdvertise"] = cippf.ExpressRouteAdvertise - } - if cippf.Geo != "" { - objectMap["geo"] = cippf.Geo - } - if cippf.NoInternetAdvertise != nil { - objectMap["noInternetAdvertise"] = cippf.NoInternetAdvertise - } - if cippf.PrefixType != "" { - objectMap["prefixType"] = cippf.PrefixType - } - return json.Marshal(objectMap) -} - -// DdosCustomPoliciesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type DdosCustomPoliciesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DdosCustomPoliciesClient) (DdosCustomPolicy, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DdosCustomPoliciesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DdosCustomPoliciesCreateOrUpdateFuture.Result. -func (future *DdosCustomPoliciesCreateOrUpdateFuture) result(client DdosCustomPoliciesClient) (dcp DdosCustomPolicy, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosCustomPoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - dcp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.DdosCustomPoliciesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if dcp.Response.Response, err = future.GetResult(sender); err == nil && dcp.Response.Response.StatusCode != http.StatusNoContent { - dcp, err = client.CreateOrUpdateResponder(dcp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosCustomPoliciesCreateOrUpdateFuture", "Result", dcp.Response.Response, "Failure responding to request") - } - } - return -} - -// DdosCustomPoliciesDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type DdosCustomPoliciesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DdosCustomPoliciesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DdosCustomPoliciesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DdosCustomPoliciesDeleteFuture.Result. -func (future *DdosCustomPoliciesDeleteFuture) result(client DdosCustomPoliciesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosCustomPoliciesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.DdosCustomPoliciesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// DdosCustomPolicy a DDoS custom policy in a resource group. -type DdosCustomPolicy struct { - autorest.Response `json:"-"` - // DdosCustomPolicyPropertiesFormat - Properties of the DDoS custom policy. - *DdosCustomPolicyPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for DdosCustomPolicy. -func (dcp DdosCustomPolicy) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dcp.DdosCustomPolicyPropertiesFormat != nil { - objectMap["properties"] = dcp.DdosCustomPolicyPropertiesFormat - } - if dcp.ID != nil { - objectMap["id"] = dcp.ID - } - if dcp.Location != nil { - objectMap["location"] = dcp.Location - } - if dcp.Tags != nil { - objectMap["tags"] = dcp.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for DdosCustomPolicy struct. -func (dcp *DdosCustomPolicy) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var ddosCustomPolicyPropertiesFormat DdosCustomPolicyPropertiesFormat - err = json.Unmarshal(*v, &ddosCustomPolicyPropertiesFormat) - if err != nil { - return err - } - dcp.DdosCustomPolicyPropertiesFormat = &ddosCustomPolicyPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - dcp.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - dcp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - dcp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - dcp.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - dcp.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - dcp.Tags = tags - } - } - } - - return nil -} - -// DdosCustomPolicyPropertiesFormat dDoS custom policy properties. -type DdosCustomPolicyPropertiesFormat struct { - // ResourceGUID - READ-ONLY; The resource GUID property of the DDoS custom policy resource. It uniquely identifies the resource, even if the user changes its name or migrate the resource across subscriptions or resource groups. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the DDoS custom policy resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for DdosCustomPolicyPropertiesFormat. -func (dcppf DdosCustomPolicyPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// DdosProtectionPlan a DDoS protection plan in a resource group. -type DdosProtectionPlan struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` - // DdosProtectionPlanPropertiesFormat - Properties of the DDoS protection plan. - *DdosProtectionPlanPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for DdosProtectionPlan. -func (dpp DdosProtectionPlan) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dpp.Location != nil { - objectMap["location"] = dpp.Location - } - if dpp.Tags != nil { - objectMap["tags"] = dpp.Tags - } - if dpp.DdosProtectionPlanPropertiesFormat != nil { - objectMap["properties"] = dpp.DdosProtectionPlanPropertiesFormat - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for DdosProtectionPlan struct. -func (dpp *DdosProtectionPlan) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - dpp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - dpp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - dpp.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - dpp.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - dpp.Tags = tags - } - case "properties": - if v != nil { - var ddosProtectionPlanPropertiesFormat DdosProtectionPlanPropertiesFormat - err = json.Unmarshal(*v, &ddosProtectionPlanPropertiesFormat) - if err != nil { - return err - } - dpp.DdosProtectionPlanPropertiesFormat = &ddosProtectionPlanPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - dpp.Etag = &etag - } - } - } - - return nil -} - -// DdosProtectionPlanListResult a list of DDoS protection plans. -type DdosProtectionPlanListResult struct { - autorest.Response `json:"-"` - // Value - A list of DDoS protection plans. - Value *[]DdosProtectionPlan `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for DdosProtectionPlanListResult. -func (dpplr DdosProtectionPlanListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dpplr.Value != nil { - objectMap["value"] = dpplr.Value - } - return json.Marshal(objectMap) -} - -// DdosProtectionPlanListResultIterator provides access to a complete listing of DdosProtectionPlan values. -type DdosProtectionPlanListResultIterator struct { - i int - page DdosProtectionPlanListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *DdosProtectionPlanListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlanListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *DdosProtectionPlanListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter DdosProtectionPlanListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter DdosProtectionPlanListResultIterator) Response() DdosProtectionPlanListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter DdosProtectionPlanListResultIterator) Value() DdosProtectionPlan { - if !iter.page.NotDone() { - return DdosProtectionPlan{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the DdosProtectionPlanListResultIterator type. -func NewDdosProtectionPlanListResultIterator(page DdosProtectionPlanListResultPage) DdosProtectionPlanListResultIterator { - return DdosProtectionPlanListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (dpplr DdosProtectionPlanListResult) IsEmpty() bool { - return dpplr.Value == nil || len(*dpplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (dpplr DdosProtectionPlanListResult) hasNextLink() bool { - return dpplr.NextLink != nil && len(*dpplr.NextLink) != 0 -} - -// ddosProtectionPlanListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (dpplr DdosProtectionPlanListResult) ddosProtectionPlanListResultPreparer(ctx context.Context) (*http.Request, error) { - if !dpplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(dpplr.NextLink))) -} - -// DdosProtectionPlanListResultPage contains a page of DdosProtectionPlan values. -type DdosProtectionPlanListResultPage struct { - fn func(context.Context, DdosProtectionPlanListResult) (DdosProtectionPlanListResult, error) - dpplr DdosProtectionPlanListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *DdosProtectionPlanListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DdosProtectionPlanListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.dpplr) - if err != nil { - return err - } - page.dpplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *DdosProtectionPlanListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page DdosProtectionPlanListResultPage) NotDone() bool { - return !page.dpplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page DdosProtectionPlanListResultPage) Response() DdosProtectionPlanListResult { - return page.dpplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page DdosProtectionPlanListResultPage) Values() []DdosProtectionPlan { - if page.dpplr.IsEmpty() { - return nil - } - return *page.dpplr.Value -} - -// Creates a new instance of the DdosProtectionPlanListResultPage type. -func NewDdosProtectionPlanListResultPage(cur DdosProtectionPlanListResult, getNextPage func(context.Context, DdosProtectionPlanListResult) (DdosProtectionPlanListResult, error)) DdosProtectionPlanListResultPage { - return DdosProtectionPlanListResultPage{ - fn: getNextPage, - dpplr: cur, - } -} - -// DdosProtectionPlanPropertiesFormat dDoS protection plan properties. -type DdosProtectionPlanPropertiesFormat struct { - // ResourceGUID - READ-ONLY; The resource GUID property of the DDoS protection plan resource. It uniquely identifies the resource, even if the user changes its name or migrate the resource across subscriptions or resource groups. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the DDoS protection plan resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // PublicIPAddresses - READ-ONLY; The list of public IPs associated with the DDoS protection plan resource. This list is read-only. - PublicIPAddresses *[]SubResource `json:"publicIPAddresses,omitempty"` - // VirtualNetworks - READ-ONLY; The list of virtual networks associated with the DDoS protection plan resource. This list is read-only. - VirtualNetworks *[]SubResource `json:"virtualNetworks,omitempty"` -} - -// MarshalJSON is the custom marshaler for DdosProtectionPlanPropertiesFormat. -func (dpppf DdosProtectionPlanPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// DdosProtectionPlansCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type DdosProtectionPlansCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DdosProtectionPlansClient) (DdosProtectionPlan, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DdosProtectionPlansCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DdosProtectionPlansCreateOrUpdateFuture.Result. -func (future *DdosProtectionPlansCreateOrUpdateFuture) result(client DdosProtectionPlansClient) (dpp DdosProtectionPlan, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - dpp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.DdosProtectionPlansCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if dpp.Response.Response, err = future.GetResult(sender); err == nil && dpp.Response.Response.StatusCode != http.StatusNoContent { - dpp, err = client.CreateOrUpdateResponder(dpp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansCreateOrUpdateFuture", "Result", dpp.Response.Response, "Failure responding to request") - } - } - return -} - -// DdosProtectionPlansDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type DdosProtectionPlansDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DdosProtectionPlansClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DdosProtectionPlansDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DdosProtectionPlansDeleteFuture.Result. -func (future *DdosProtectionPlansDeleteFuture) result(client DdosProtectionPlansClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DdosProtectionPlansDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.DdosProtectionPlansDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// DdosSettings contains the DDoS protection settings of the public IP. -type DdosSettings struct { - // ProtectionMode - The DDoS protection mode of the public IP. Possible values include: 'DdosSettingsProtectionModeVirtualNetworkInherited', 'DdosSettingsProtectionModeEnabled', 'DdosSettingsProtectionModeDisabled' - ProtectionMode DdosSettingsProtectionMode `json:"protectionMode,omitempty"` - // DdosProtectionPlan - The DDoS protection plan associated with the public IP. Can only be set if ProtectionMode is Enabled - DdosProtectionPlan *SubResource `json:"ddosProtectionPlan,omitempty"` -} - -// DefaultAdminPropertiesFormat security default admin rule resource. -type DefaultAdminPropertiesFormat struct { - // Description - READ-ONLY; A description for this rule. Restricted to 140 chars. - Description *string `json:"description,omitempty"` - // Flag - Default rule flag. - Flag *string `json:"flag,omitempty"` - // Protocol - READ-ONLY; Network protocol this rule applies to. Possible values include: 'SecurityConfigurationRuleProtocolTCP', 'SecurityConfigurationRuleProtocolUDP', 'SecurityConfigurationRuleProtocolIcmp', 'SecurityConfigurationRuleProtocolEsp', 'SecurityConfigurationRuleProtocolAny', 'SecurityConfigurationRuleProtocolAh' - Protocol SecurityConfigurationRuleProtocol `json:"protocol,omitempty"` - // Sources - READ-ONLY; The CIDR or source IP ranges. - Sources *[]AddressPrefixItem `json:"sources,omitempty"` - // Destinations - READ-ONLY; The destination address prefixes. CIDR or destination IP ranges. - Destinations *[]AddressPrefixItem `json:"destinations,omitempty"` - // SourcePortRanges - READ-ONLY; The source port ranges. - SourcePortRanges *[]string `json:"sourcePortRanges,omitempty"` - // DestinationPortRanges - READ-ONLY; The destination port ranges. - DestinationPortRanges *[]string `json:"destinationPortRanges,omitempty"` - // Access - READ-ONLY; Indicates the access allowed for this particular rule. Possible values include: 'SecurityConfigurationRuleAccessAllow', 'SecurityConfigurationRuleAccessDeny', 'SecurityConfigurationRuleAccessAlwaysAllow' - Access SecurityConfigurationRuleAccess `json:"access,omitempty"` - // Priority - READ-ONLY; The priority of the rule. The value can be between 1 and 4096. The priority number must be unique for each rule in the collection. The lower the priority number, the higher the priority of the rule. - Priority *int32 `json:"priority,omitempty"` - // Direction - READ-ONLY; Indicates if the traffic matched against the rule in inbound or outbound. Possible values include: 'SecurityConfigurationRuleDirectionInbound', 'SecurityConfigurationRuleDirectionOutbound' - Direction SecurityConfigurationRuleDirection `json:"direction,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for DefaultAdminPropertiesFormat. -func (dapf DefaultAdminPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dapf.Flag != nil { - objectMap["flag"] = dapf.Flag - } - return json.Marshal(objectMap) -} - -// DefaultAdminRule network default admin rule. -type DefaultAdminRule struct { - // DefaultAdminPropertiesFormat - Indicates the properties of the security admin rule - *DefaultAdminPropertiesFormat `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system metadata related to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // Kind - Possible values include: 'KindBasicBaseAdminRuleKindBaseAdminRule', 'KindBasicBaseAdminRuleKindCustom', 'KindBasicBaseAdminRuleKindDefault' - Kind KindBasicBaseAdminRule `json:"kind,omitempty"` - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for DefaultAdminRule. -func (dar DefaultAdminRule) MarshalJSON() ([]byte, error) { - dar.Kind = KindBasicBaseAdminRuleKindDefault - objectMap := make(map[string]interface{}) - if dar.DefaultAdminPropertiesFormat != nil { - objectMap["properties"] = dar.DefaultAdminPropertiesFormat - } - if dar.Kind != "" { - objectMap["kind"] = dar.Kind - } - return json.Marshal(objectMap) -} - -// AsAdminRule is the BasicBaseAdminRule implementation for DefaultAdminRule. -func (dar DefaultAdminRule) AsAdminRule() (*AdminRule, bool) { - return nil, false -} - -// AsDefaultAdminRule is the BasicBaseAdminRule implementation for DefaultAdminRule. -func (dar DefaultAdminRule) AsDefaultAdminRule() (*DefaultAdminRule, bool) { - return &dar, true -} - -// AsBaseAdminRule is the BasicBaseAdminRule implementation for DefaultAdminRule. -func (dar DefaultAdminRule) AsBaseAdminRule() (*BaseAdminRule, bool) { - return nil, false -} - -// AsBasicBaseAdminRule is the BasicBaseAdminRule implementation for DefaultAdminRule. -func (dar DefaultAdminRule) AsBasicBaseAdminRule() (BasicBaseAdminRule, bool) { - return &dar, true -} - -// UnmarshalJSON is the custom unmarshaler for DefaultAdminRule struct. -func (dar *DefaultAdminRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var defaultAdminPropertiesFormat DefaultAdminPropertiesFormat - err = json.Unmarshal(*v, &defaultAdminPropertiesFormat) - if err != nil { - return err - } - dar.DefaultAdminPropertiesFormat = &defaultAdminPropertiesFormat - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - dar.SystemData = &systemData - } - case "kind": - if v != nil { - var kind KindBasicBaseAdminRule - err = json.Unmarshal(*v, &kind) - if err != nil { - return err - } - dar.Kind = kind - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - dar.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - dar.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - dar.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - dar.Etag = &etag - } - } - } - - return nil -} - -// DefaultRuleSetPropertyFormat the default web application firewall rule set. -type DefaultRuleSetPropertyFormat struct { - // RuleSetType - The type of the web application firewall rule set. - RuleSetType *string `json:"ruleSetType,omitempty"` - // RuleSetVersion - The version of the web application firewall rule set type. - RuleSetVersion *string `json:"ruleSetVersion,omitempty"` -} - -// Delegation details the service to which the subnet is delegated. -type Delegation struct { - // ServiceDelegationPropertiesFormat - Properties of the subnet. - *ServiceDelegationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a subnet. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for Delegation. -func (d Delegation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if d.ServiceDelegationPropertiesFormat != nil { - objectMap["properties"] = d.ServiceDelegationPropertiesFormat - } - if d.Name != nil { - objectMap["name"] = d.Name - } - if d.Type != nil { - objectMap["type"] = d.Type - } - if d.ID != nil { - objectMap["id"] = d.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Delegation struct. -func (d *Delegation) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var serviceDelegationPropertiesFormat ServiceDelegationPropertiesFormat - err = json.Unmarshal(*v, &serviceDelegationPropertiesFormat) - if err != nil { - return err - } - d.ServiceDelegationPropertiesFormat = &serviceDelegationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - d.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - d.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - d.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - d.ID = &ID - } - } - } - - return nil -} - -// DelegationProperties properties of the delegation. -type DelegationProperties struct { - // ServiceName - The service name to which the NVA is delegated. - ServiceName *string `json:"serviceName,omitempty"` - // ProvisioningState - READ-ONLY; Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for DelegationProperties. -func (dp DelegationProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dp.ServiceName != nil { - objectMap["serviceName"] = dp.ServiceName - } - return json.Marshal(objectMap) -} - -// DeleteBastionShareableLinkFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type DeleteBastionShareableLinkFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BaseClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DeleteBastionShareableLinkFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DeleteBastionShareableLinkFuture.Result. -func (future *DeleteBastionShareableLinkFuture) result(client BaseClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DeleteBastionShareableLinkFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.DeleteBastionShareableLinkFuture") - return - } - ar.Response = future.Response() - return -} - -// DeviceProperties list of properties of the device. -type DeviceProperties struct { - // DeviceVendor - Name of the device Vendor. - DeviceVendor *string `json:"deviceVendor,omitempty"` - // DeviceModel - Model of the device. - DeviceModel *string `json:"deviceModel,omitempty"` - // LinkSpeedInMbps - Link speed. - LinkSpeedInMbps *int32 `json:"linkSpeedInMbps,omitempty"` -} - -// DhcpOptions 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 - The list of DNS servers IP addresses. - DNSServers *[]string `json:"dnsServers,omitempty"` -} - -// Dimension dimension of the metric. -type Dimension struct { - // Name - The name of the dimension. - Name *string `json:"name,omitempty"` - // DisplayName - The display name of the dimension. - DisplayName *string `json:"displayName,omitempty"` - // InternalName - The internal name of the dimension. - InternalName *string `json:"internalName,omitempty"` -} - -// DNSNameAvailabilityResult response for the CheckDnsNameAvailability API service call. -type DNSNameAvailabilityResult struct { - autorest.Response `json:"-"` - // Available - Domain availability (True/False). - Available *bool `json:"available,omitempty"` -} - -// DNSSettings DNS Proxy Settings in Firewall Policy. -type DNSSettings struct { - // Servers - List of Custom DNS Servers. - Servers *[]string `json:"servers,omitempty"` - // EnableProxy - Enable DNS Proxy on Firewalls attached to the Firewall Policy. - EnableProxy *bool `json:"enableProxy,omitempty"` - // RequireProxyForNetworkRules - FQDNs in Network Rules are supported when set to true. - RequireProxyForNetworkRules *bool `json:"requireProxyForNetworkRules,omitempty"` -} - -// DscpConfiguration differentiated Services Code Point configuration for any given network interface -type DscpConfiguration struct { - autorest.Response `json:"-"` - // DscpConfigurationPropertiesFormat - Properties of the network interface. - *DscpConfigurationPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for DscpConfiguration. -func (dc DscpConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dc.DscpConfigurationPropertiesFormat != nil { - objectMap["properties"] = dc.DscpConfigurationPropertiesFormat - } - if dc.ID != nil { - objectMap["id"] = dc.ID - } - if dc.Location != nil { - objectMap["location"] = dc.Location - } - if dc.Tags != nil { - objectMap["tags"] = dc.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for DscpConfiguration struct. -func (dc *DscpConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var dscpConfigurationPropertiesFormat DscpConfigurationPropertiesFormat - err = json.Unmarshal(*v, &dscpConfigurationPropertiesFormat) - if err != nil { - return err - } - dc.DscpConfigurationPropertiesFormat = &dscpConfigurationPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - dc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - dc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - dc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - dc.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - dc.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - dc.Tags = tags - } - } - } - - return nil -} - -// DscpConfigurationCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type DscpConfigurationCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DscpConfigurationClient) (DscpConfiguration, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DscpConfigurationCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DscpConfigurationCreateOrUpdateFuture.Result. -func (future *DscpConfigurationCreateOrUpdateFuture) result(client DscpConfigurationClient) (dc DscpConfiguration, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - dc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.DscpConfigurationCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if dc.Response.Response, err = future.GetResult(sender); err == nil && dc.Response.Response.StatusCode != http.StatusNoContent { - dc, err = client.CreateOrUpdateResponder(dc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationCreateOrUpdateFuture", "Result", dc.Response.Response, "Failure responding to request") - } - } - return -} - -// DscpConfigurationDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DscpConfigurationDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(DscpConfigurationClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *DscpConfigurationDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for DscpConfigurationDeleteFuture.Result. -func (future *DscpConfigurationDeleteFuture) result(client DscpConfigurationClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.DscpConfigurationDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.DscpConfigurationDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// DscpConfigurationListResult response for the DscpConfigurationList API service call. -type DscpConfigurationListResult struct { - autorest.Response `json:"-"` - // Value - A list of dscp configurations in a resource group. - Value *[]DscpConfiguration `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for DscpConfigurationListResult. -func (dclr DscpConfigurationListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dclr.Value != nil { - objectMap["value"] = dclr.Value - } - return json.Marshal(objectMap) -} - -// DscpConfigurationListResultIterator provides access to a complete listing of DscpConfiguration values. -type DscpConfigurationListResultIterator struct { - i int - page DscpConfigurationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *DscpConfigurationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DscpConfigurationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *DscpConfigurationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter DscpConfigurationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter DscpConfigurationListResultIterator) Response() DscpConfigurationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter DscpConfigurationListResultIterator) Value() DscpConfiguration { - if !iter.page.NotDone() { - return DscpConfiguration{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the DscpConfigurationListResultIterator type. -func NewDscpConfigurationListResultIterator(page DscpConfigurationListResultPage) DscpConfigurationListResultIterator { - return DscpConfigurationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (dclr DscpConfigurationListResult) IsEmpty() bool { - return dclr.Value == nil || len(*dclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (dclr DscpConfigurationListResult) hasNextLink() bool { - return dclr.NextLink != nil && len(*dclr.NextLink) != 0 -} - -// dscpConfigurationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (dclr DscpConfigurationListResult) dscpConfigurationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !dclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(dclr.NextLink))) -} - -// DscpConfigurationListResultPage contains a page of DscpConfiguration values. -type DscpConfigurationListResultPage struct { - fn func(context.Context, DscpConfigurationListResult) (DscpConfigurationListResult, error) - dclr DscpConfigurationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *DscpConfigurationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DscpConfigurationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.dclr) - if err != nil { - return err - } - page.dclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *DscpConfigurationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page DscpConfigurationListResultPage) NotDone() bool { - return !page.dclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page DscpConfigurationListResultPage) Response() DscpConfigurationListResult { - return page.dclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page DscpConfigurationListResultPage) Values() []DscpConfiguration { - if page.dclr.IsEmpty() { - return nil - } - return *page.dclr.Value -} - -// Creates a new instance of the DscpConfigurationListResultPage type. -func NewDscpConfigurationListResultPage(cur DscpConfigurationListResult, getNextPage func(context.Context, DscpConfigurationListResult) (DscpConfigurationListResult, error)) DscpConfigurationListResultPage { - return DscpConfigurationListResultPage{ - fn: getNextPage, - dclr: cur, - } -} - -// DscpConfigurationPropertiesFormat differentiated Services Code Point configuration properties. -type DscpConfigurationPropertiesFormat struct { - // Markings - List of markings to be used in the configuration. - Markings *[]int32 `json:"markings,omitempty"` - // SourceIPRanges - Source IP ranges. - SourceIPRanges *[]QosIPRange `json:"sourceIpRanges,omitempty"` - // DestinationIPRanges - Destination IP ranges. - DestinationIPRanges *[]QosIPRange `json:"destinationIpRanges,omitempty"` - // SourcePortRanges - Sources port ranges. - SourcePortRanges *[]QosPortRange `json:"sourcePortRanges,omitempty"` - // DestinationPortRanges - Destination port ranges. - DestinationPortRanges *[]QosPortRange `json:"destinationPortRanges,omitempty"` - // Protocol - RNM supported protocol types. Possible values include: 'ProtocolTypeDoNotUse', 'ProtocolTypeIcmp', 'ProtocolTypeTCP', 'ProtocolTypeUDP', 'ProtocolTypeGre', 'ProtocolTypeEsp', 'ProtocolTypeAh', 'ProtocolTypeVxlan', 'ProtocolTypeAll' - Protocol ProtocolType `json:"protocol,omitempty"` - // QosDefinitionCollection - QoS object definitions - QosDefinitionCollection *[]QosDefinition `json:"qosDefinitionCollection,omitempty"` - // QosCollectionID - READ-ONLY; Qos Collection ID generated by RNM. - QosCollectionID *string `json:"qosCollectionId,omitempty"` - // AssociatedNetworkInterfaces - READ-ONLY; Associated Network Interfaces to the DSCP Configuration. - AssociatedNetworkInterfaces *[]Interface `json:"associatedNetworkInterfaces,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the DSCP Configuration resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the DSCP Configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for DscpConfigurationPropertiesFormat. -func (dcpf DscpConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dcpf.Markings != nil { - objectMap["markings"] = dcpf.Markings - } - if dcpf.SourceIPRanges != nil { - objectMap["sourceIpRanges"] = dcpf.SourceIPRanges - } - if dcpf.DestinationIPRanges != nil { - objectMap["destinationIpRanges"] = dcpf.DestinationIPRanges - } - if dcpf.SourcePortRanges != nil { - objectMap["sourcePortRanges"] = dcpf.SourcePortRanges - } - if dcpf.DestinationPortRanges != nil { - objectMap["destinationPortRanges"] = dcpf.DestinationPortRanges - } - if dcpf.Protocol != "" { - objectMap["protocol"] = dcpf.Protocol - } - if dcpf.QosDefinitionCollection != nil { - objectMap["qosDefinitionCollection"] = dcpf.QosDefinitionCollection - } - return json.Marshal(objectMap) -} - -// BasicEffectiveBaseSecurityAdminRule network base admin rule. -type BasicEffectiveBaseSecurityAdminRule interface { - AsEffectiveSecurityAdminRule() (*EffectiveSecurityAdminRule, bool) - AsEffectiveDefaultSecurityAdminRule() (*EffectiveDefaultSecurityAdminRule, bool) - AsEffectiveBaseSecurityAdminRule() (*EffectiveBaseSecurityAdminRule, bool) -} - -// EffectiveBaseSecurityAdminRule network base admin rule. -type EffectiveBaseSecurityAdminRule struct { - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // ConfigurationDescription - A description of the security admin configuration. - ConfigurationDescription *string `json:"configurationDescription,omitempty"` - // RuleCollectionDescription - A description of the rule collection. - RuleCollectionDescription *string `json:"ruleCollectionDescription,omitempty"` - // RuleCollectionAppliesToGroups - Groups for rule collection - RuleCollectionAppliesToGroups *[]ManagerSecurityGroupItem `json:"ruleCollectionAppliesToGroups,omitempty"` - // RuleGroups - Effective configuration groups. - RuleGroups *[]ConfigurationGroup `json:"ruleGroups,omitempty"` - // Kind - Possible values include: 'KindBasicEffectiveBaseSecurityAdminRuleKindEffectiveBaseSecurityAdminRule', 'KindBasicEffectiveBaseSecurityAdminRuleKindCustom', 'KindBasicEffectiveBaseSecurityAdminRuleKindDefault' - Kind KindBasicEffectiveBaseSecurityAdminRule `json:"kind,omitempty"` -} - -func unmarshalBasicEffectiveBaseSecurityAdminRule(body []byte) (BasicEffectiveBaseSecurityAdminRule, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["kind"] { - case string(KindBasicEffectiveBaseSecurityAdminRuleKindCustom): - var esar EffectiveSecurityAdminRule - err := json.Unmarshal(body, &esar) - return esar, err - case string(KindBasicEffectiveBaseSecurityAdminRuleKindDefault): - var edsar EffectiveDefaultSecurityAdminRule - err := json.Unmarshal(body, &edsar) - return edsar, err - default: - var ebsar EffectiveBaseSecurityAdminRule - err := json.Unmarshal(body, &ebsar) - return ebsar, err - } -} -func unmarshalBasicEffectiveBaseSecurityAdminRuleArray(body []byte) ([]BasicEffectiveBaseSecurityAdminRule, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - ebsarArray := make([]BasicEffectiveBaseSecurityAdminRule, len(rawMessages)) - - for index, rawMessage := range rawMessages { - ebsar, err := unmarshalBasicEffectiveBaseSecurityAdminRule(*rawMessage) - if err != nil { - return nil, err - } - ebsarArray[index] = ebsar - } - return ebsarArray, nil -} - -// MarshalJSON is the custom marshaler for EffectiveBaseSecurityAdminRule. -func (ebsar EffectiveBaseSecurityAdminRule) MarshalJSON() ([]byte, error) { - ebsar.Kind = KindBasicEffectiveBaseSecurityAdminRuleKindEffectiveBaseSecurityAdminRule - objectMap := make(map[string]interface{}) - if ebsar.ID != nil { - objectMap["id"] = ebsar.ID - } - if ebsar.ConfigurationDescription != nil { - objectMap["configurationDescription"] = ebsar.ConfigurationDescription - } - if ebsar.RuleCollectionDescription != nil { - objectMap["ruleCollectionDescription"] = ebsar.RuleCollectionDescription - } - if ebsar.RuleCollectionAppliesToGroups != nil { - objectMap["ruleCollectionAppliesToGroups"] = ebsar.RuleCollectionAppliesToGroups - } - if ebsar.RuleGroups != nil { - objectMap["ruleGroups"] = ebsar.RuleGroups - } - if ebsar.Kind != "" { - objectMap["kind"] = ebsar.Kind - } - return json.Marshal(objectMap) -} - -// AsEffectiveSecurityAdminRule is the BasicEffectiveBaseSecurityAdminRule implementation for EffectiveBaseSecurityAdminRule. -func (ebsar EffectiveBaseSecurityAdminRule) AsEffectiveSecurityAdminRule() (*EffectiveSecurityAdminRule, bool) { - return nil, false -} - -// AsEffectiveDefaultSecurityAdminRule is the BasicEffectiveBaseSecurityAdminRule implementation for EffectiveBaseSecurityAdminRule. -func (ebsar EffectiveBaseSecurityAdminRule) AsEffectiveDefaultSecurityAdminRule() (*EffectiveDefaultSecurityAdminRule, bool) { - return nil, false -} - -// AsEffectiveBaseSecurityAdminRule is the BasicEffectiveBaseSecurityAdminRule implementation for EffectiveBaseSecurityAdminRule. -func (ebsar EffectiveBaseSecurityAdminRule) AsEffectiveBaseSecurityAdminRule() (*EffectiveBaseSecurityAdminRule, bool) { - return &ebsar, true -} - -// AsBasicEffectiveBaseSecurityAdminRule is the BasicEffectiveBaseSecurityAdminRule implementation for EffectiveBaseSecurityAdminRule. -func (ebsar EffectiveBaseSecurityAdminRule) AsBasicEffectiveBaseSecurityAdminRule() (BasicEffectiveBaseSecurityAdminRule, bool) { - return &ebsar, true -} - -// EffectiveConnectivityConfiguration the network manager effective connectivity configuration -type EffectiveConnectivityConfiguration struct { - // ID - Connectivity configuration ID. - ID *string `json:"id,omitempty"` - // ConnectivityConfigurationProperties - Properties of a network manager connectivity configuration - *ConnectivityConfigurationProperties `json:"properties,omitempty"` - // ConfigurationGroups - Effective configuration groups. - ConfigurationGroups *[]ConfigurationGroup `json:"configurationGroups,omitempty"` -} - -// MarshalJSON is the custom marshaler for EffectiveConnectivityConfiguration. -func (ecc EffectiveConnectivityConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ecc.ID != nil { - objectMap["id"] = ecc.ID - } - if ecc.ConnectivityConfigurationProperties != nil { - objectMap["properties"] = ecc.ConnectivityConfigurationProperties - } - if ecc.ConfigurationGroups != nil { - objectMap["configurationGroups"] = ecc.ConfigurationGroups - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for EffectiveConnectivityConfiguration struct. -func (ecc *EffectiveConnectivityConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ecc.ID = &ID - } - case "properties": - if v != nil { - var connectivityConfigurationProperties ConnectivityConfigurationProperties - err = json.Unmarshal(*v, &connectivityConfigurationProperties) - if err != nil { - return err - } - ecc.ConnectivityConfigurationProperties = &connectivityConfigurationProperties - } - case "configurationGroups": - if v != nil { - var configurationGroups []ConfigurationGroup - err = json.Unmarshal(*v, &configurationGroups) - if err != nil { - return err - } - ecc.ConfigurationGroups = &configurationGroups - } - } - } - - return nil -} - -// EffectiveDefaultSecurityAdminRule network default admin rule. -type EffectiveDefaultSecurityAdminRule struct { - // DefaultAdminPropertiesFormat - Indicates the properties of the default security admin rule - *DefaultAdminPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // ConfigurationDescription - A description of the security admin configuration. - ConfigurationDescription *string `json:"configurationDescription,omitempty"` - // RuleCollectionDescription - A description of the rule collection. - RuleCollectionDescription *string `json:"ruleCollectionDescription,omitempty"` - // RuleCollectionAppliesToGroups - Groups for rule collection - RuleCollectionAppliesToGroups *[]ManagerSecurityGroupItem `json:"ruleCollectionAppliesToGroups,omitempty"` - // RuleGroups - Effective configuration groups. - RuleGroups *[]ConfigurationGroup `json:"ruleGroups,omitempty"` - // Kind - Possible values include: 'KindBasicEffectiveBaseSecurityAdminRuleKindEffectiveBaseSecurityAdminRule', 'KindBasicEffectiveBaseSecurityAdminRuleKindCustom', 'KindBasicEffectiveBaseSecurityAdminRuleKindDefault' - Kind KindBasicEffectiveBaseSecurityAdminRule `json:"kind,omitempty"` -} - -// MarshalJSON is the custom marshaler for EffectiveDefaultSecurityAdminRule. -func (edsar EffectiveDefaultSecurityAdminRule) MarshalJSON() ([]byte, error) { - edsar.Kind = KindBasicEffectiveBaseSecurityAdminRuleKindDefault - objectMap := make(map[string]interface{}) - if edsar.DefaultAdminPropertiesFormat != nil { - objectMap["properties"] = edsar.DefaultAdminPropertiesFormat - } - if edsar.ID != nil { - objectMap["id"] = edsar.ID - } - if edsar.ConfigurationDescription != nil { - objectMap["configurationDescription"] = edsar.ConfigurationDescription - } - if edsar.RuleCollectionDescription != nil { - objectMap["ruleCollectionDescription"] = edsar.RuleCollectionDescription - } - if edsar.RuleCollectionAppliesToGroups != nil { - objectMap["ruleCollectionAppliesToGroups"] = edsar.RuleCollectionAppliesToGroups - } - if edsar.RuleGroups != nil { - objectMap["ruleGroups"] = edsar.RuleGroups - } - if edsar.Kind != "" { - objectMap["kind"] = edsar.Kind - } - return json.Marshal(objectMap) -} - -// AsEffectiveSecurityAdminRule is the BasicEffectiveBaseSecurityAdminRule implementation for EffectiveDefaultSecurityAdminRule. -func (edsar EffectiveDefaultSecurityAdminRule) AsEffectiveSecurityAdminRule() (*EffectiveSecurityAdminRule, bool) { - return nil, false -} - -// AsEffectiveDefaultSecurityAdminRule is the BasicEffectiveBaseSecurityAdminRule implementation for EffectiveDefaultSecurityAdminRule. -func (edsar EffectiveDefaultSecurityAdminRule) AsEffectiveDefaultSecurityAdminRule() (*EffectiveDefaultSecurityAdminRule, bool) { - return &edsar, true -} - -// AsEffectiveBaseSecurityAdminRule is the BasicEffectiveBaseSecurityAdminRule implementation for EffectiveDefaultSecurityAdminRule. -func (edsar EffectiveDefaultSecurityAdminRule) AsEffectiveBaseSecurityAdminRule() (*EffectiveBaseSecurityAdminRule, bool) { - return nil, false -} - -// AsBasicEffectiveBaseSecurityAdminRule is the BasicEffectiveBaseSecurityAdminRule implementation for EffectiveDefaultSecurityAdminRule. -func (edsar EffectiveDefaultSecurityAdminRule) AsBasicEffectiveBaseSecurityAdminRule() (BasicEffectiveBaseSecurityAdminRule, bool) { - return &edsar, true -} - -// UnmarshalJSON is the custom unmarshaler for EffectiveDefaultSecurityAdminRule struct. -func (edsar *EffectiveDefaultSecurityAdminRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var defaultAdminPropertiesFormat DefaultAdminPropertiesFormat - err = json.Unmarshal(*v, &defaultAdminPropertiesFormat) - if err != nil { - return err - } - edsar.DefaultAdminPropertiesFormat = &defaultAdminPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - edsar.ID = &ID - } - case "configurationDescription": - if v != nil { - var configurationDescription string - err = json.Unmarshal(*v, &configurationDescription) - if err != nil { - return err - } - edsar.ConfigurationDescription = &configurationDescription - } - case "ruleCollectionDescription": - if v != nil { - var ruleCollectionDescription string - err = json.Unmarshal(*v, &ruleCollectionDescription) - if err != nil { - return err - } - edsar.RuleCollectionDescription = &ruleCollectionDescription - } - case "ruleCollectionAppliesToGroups": - if v != nil { - var ruleCollectionAppliesToGroups []ManagerSecurityGroupItem - err = json.Unmarshal(*v, &ruleCollectionAppliesToGroups) - if err != nil { - return err - } - edsar.RuleCollectionAppliesToGroups = &ruleCollectionAppliesToGroups - } - case "ruleGroups": - if v != nil { - var ruleGroups []ConfigurationGroup - err = json.Unmarshal(*v, &ruleGroups) - if err != nil { - return err - } - edsar.RuleGroups = &ruleGroups - } - case "kind": - if v != nil { - var kind KindBasicEffectiveBaseSecurityAdminRule - err = json.Unmarshal(*v, &kind) - if err != nil { - return err - } - edsar.Kind = kind - } - } - } - - return nil -} - -// EffectiveNetworkSecurityGroup effective network security group. -type EffectiveNetworkSecurityGroup struct { - // NetworkSecurityGroup - The ID of network security group that is applied. - NetworkSecurityGroup *SubResource `json:"networkSecurityGroup,omitempty"` - // Association - Associated resources. - Association *EffectiveNetworkSecurityGroupAssociation `json:"association,omitempty"` - // EffectiveSecurityRules - A collection of effective security rules. - EffectiveSecurityRules *[]EffectiveNetworkSecurityRule `json:"effectiveSecurityRules,omitempty"` - // TagMap - Mapping of tags to list of IP Addresses included within the tag. - TagMap map[string][]string `json:"tagMap"` -} - -// MarshalJSON is the custom marshaler for EffectiveNetworkSecurityGroup. -func (ensg EffectiveNetworkSecurityGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ensg.NetworkSecurityGroup != nil { - objectMap["networkSecurityGroup"] = ensg.NetworkSecurityGroup - } - if ensg.Association != nil { - objectMap["association"] = ensg.Association - } - if ensg.EffectiveSecurityRules != nil { - objectMap["effectiveSecurityRules"] = ensg.EffectiveSecurityRules - } - if ensg.TagMap != nil { - objectMap["tagMap"] = ensg.TagMap - } - return json.Marshal(objectMap) -} - -// EffectiveNetworkSecurityGroupAssociation the effective network security group association. -type EffectiveNetworkSecurityGroupAssociation struct { - // NetworkManager - The ID of the Azure network manager if assigned. - NetworkManager *SubResource `json:"networkManager,omitempty"` - // Subnet - The ID of the subnet if assigned. - Subnet *SubResource `json:"subnet,omitempty"` - // NetworkInterface - The ID of the network interface if assigned. - NetworkInterface *SubResource `json:"networkInterface,omitempty"` -} - -// EffectiveNetworkSecurityGroupListResult response for list effective network security groups API service -// call. -type EffectiveNetworkSecurityGroupListResult struct { - autorest.Response `json:"-"` - // Value - A list of effective network security groups. - Value *[]EffectiveNetworkSecurityGroup `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for EffectiveNetworkSecurityGroupListResult. -func (ensglr EffectiveNetworkSecurityGroupListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ensglr.Value != nil { - objectMap["value"] = ensglr.Value - } - return json.Marshal(objectMap) -} - -// EffectiveNetworkSecurityRule effective network security rules. -type EffectiveNetworkSecurityRule struct { - // Name - The name of the security rule specified by the user (if created by the user). - Name *string `json:"name,omitempty"` - // Protocol - The network protocol this rule applies to. Possible values include: 'EffectiveSecurityRuleProtocolTCP', 'EffectiveSecurityRuleProtocolUDP', 'EffectiveSecurityRuleProtocolAll' - Protocol EffectiveSecurityRuleProtocol `json:"protocol,omitempty"` - // SourcePortRange - The source port or range. - SourcePortRange *string `json:"sourcePortRange,omitempty"` - // DestinationPortRange - The destination port or range. - DestinationPortRange *string `json:"destinationPortRange,omitempty"` - // SourcePortRanges - The source port ranges. Expected values include a single integer between 0 and 65535, a range using '-' as separator (e.g. 100-400), or an asterisk (*). - SourcePortRanges *[]string `json:"sourcePortRanges,omitempty"` - // DestinationPortRanges - The destination port ranges. Expected values include a single integer between 0 and 65535, a range using '-' as separator (e.g. 100-400), or an asterisk (*). - DestinationPortRanges *[]string `json:"destinationPortRanges,omitempty"` - // SourceAddressPrefix - The source address prefix. - SourceAddressPrefix *string `json:"sourceAddressPrefix,omitempty"` - // DestinationAddressPrefix - The destination address prefix. - DestinationAddressPrefix *string `json:"destinationAddressPrefix,omitempty"` - // SourceAddressPrefixes - The source address prefixes. Expected values include CIDR IP ranges, Default Tags (VirtualNetwork, AzureLoadBalancer, Internet), System Tags, and the asterisk (*). - SourceAddressPrefixes *[]string `json:"sourceAddressPrefixes,omitempty"` - // DestinationAddressPrefixes - The destination address prefixes. Expected values include CIDR IP ranges, Default Tags (VirtualNetwork, AzureLoadBalancer, Internet), System Tags, and the asterisk (*). - DestinationAddressPrefixes *[]string `json:"destinationAddressPrefixes,omitempty"` - // ExpandedSourceAddressPrefix - The expanded source address prefix. - ExpandedSourceAddressPrefix *[]string `json:"expandedSourceAddressPrefix,omitempty"` - // ExpandedDestinationAddressPrefix - Expanded destination address prefix. - ExpandedDestinationAddressPrefix *[]string `json:"expandedDestinationAddressPrefix,omitempty"` - // Access - Whether network traffic is allowed or denied. Possible values include: 'SecurityRuleAccessAllow', 'SecurityRuleAccessDeny' - Access SecurityRuleAccess `json:"access,omitempty"` - // Priority - The priority of the rule. - Priority *int32 `json:"priority,omitempty"` - // Direction - The direction of the rule. Possible values include: 'SecurityRuleDirectionInbound', 'SecurityRuleDirectionOutbound' - Direction SecurityRuleDirection `json:"direction,omitempty"` -} - -// EffectiveRoute effective Route. -type EffectiveRoute struct { - // Name - The name of the user defined route. This is optional. - Name *string `json:"name,omitempty"` - // DisableBgpRoutePropagation - If true, on-premises routes are not propagated to the network interfaces in the subnet. - DisableBgpRoutePropagation *bool `json:"disableBgpRoutePropagation,omitempty"` - // Source - Who created the route. Possible values include: 'EffectiveRouteSourceUnknown', 'EffectiveRouteSourceUser', 'EffectiveRouteSourceVirtualNetworkGateway', 'EffectiveRouteSourceDefault' - Source EffectiveRouteSource `json:"source,omitempty"` - // State - The value of effective route. Possible values include: 'Active', 'Invalid' - State EffectiveRouteState `json:"state,omitempty"` - // AddressPrefix - The address prefixes of the effective routes in CIDR notation. - AddressPrefix *[]string `json:"addressPrefix,omitempty"` - // NextHopIPAddress - The IP address of the next hop of the effective route. - NextHopIPAddress *[]string `json:"nextHopIpAddress,omitempty"` - // NextHopType - The type of Azure hop the packet should be sent to. Possible values include: 'RouteNextHopTypeVirtualNetworkGateway', 'RouteNextHopTypeVnetLocal', 'RouteNextHopTypeInternet', 'RouteNextHopTypeVirtualAppliance', 'RouteNextHopTypeNone' - NextHopType RouteNextHopType `json:"nextHopType,omitempty"` -} - -// EffectiveRouteListResult response for list effective route API service call. -type EffectiveRouteListResult struct { - autorest.Response `json:"-"` - // Value - A list of effective routes. - Value *[]EffectiveRoute `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for EffectiveRouteListResult. -func (erlr EffectiveRouteListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erlr.Value != nil { - objectMap["value"] = erlr.Value - } - return json.Marshal(objectMap) -} - -// EffectiveRouteMapRoute the effective RouteMap route configured on the connection resource. -type EffectiveRouteMapRoute struct { - // Prefix - The address prefix of the route. - Prefix *[]string `json:"prefix,omitempty"` - // BgpCommunities - BGP communities of the route. - BgpCommunities *string `json:"bgpCommunities,omitempty"` - // AsPath - The ASPath of this route. - AsPath *string `json:"asPath,omitempty"` -} - -// EffectiveRoutesParameters the parameters specifying the resource whose effective routes are being -// requested. -type EffectiveRoutesParameters struct { - // ResourceID - The resource whose effective routes are being requested. - ResourceID *string `json:"resourceId,omitempty"` - // VirtualWanResourceType - The type of the specified resource like RouteTable, ExpressRouteConnection, HubVirtualNetworkConnection, VpnConnection and P2SConnection. - VirtualWanResourceType *string `json:"virtualWanResourceType,omitempty"` -} - -// EffectiveSecurityAdminRule network admin rule. -type EffectiveSecurityAdminRule struct { - // AdminPropertiesFormat - Indicates the properties of the security admin rule - *AdminPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // ConfigurationDescription - A description of the security admin configuration. - ConfigurationDescription *string `json:"configurationDescription,omitempty"` - // RuleCollectionDescription - A description of the rule collection. - RuleCollectionDescription *string `json:"ruleCollectionDescription,omitempty"` - // RuleCollectionAppliesToGroups - Groups for rule collection - RuleCollectionAppliesToGroups *[]ManagerSecurityGroupItem `json:"ruleCollectionAppliesToGroups,omitempty"` - // RuleGroups - Effective configuration groups. - RuleGroups *[]ConfigurationGroup `json:"ruleGroups,omitempty"` - // Kind - Possible values include: 'KindBasicEffectiveBaseSecurityAdminRuleKindEffectiveBaseSecurityAdminRule', 'KindBasicEffectiveBaseSecurityAdminRuleKindCustom', 'KindBasicEffectiveBaseSecurityAdminRuleKindDefault' - Kind KindBasicEffectiveBaseSecurityAdminRule `json:"kind,omitempty"` -} - -// MarshalJSON is the custom marshaler for EffectiveSecurityAdminRule. -func (esar EffectiveSecurityAdminRule) MarshalJSON() ([]byte, error) { - esar.Kind = KindBasicEffectiveBaseSecurityAdminRuleKindCustom - objectMap := make(map[string]interface{}) - if esar.AdminPropertiesFormat != nil { - objectMap["properties"] = esar.AdminPropertiesFormat - } - if esar.ID != nil { - objectMap["id"] = esar.ID - } - if esar.ConfigurationDescription != nil { - objectMap["configurationDescription"] = esar.ConfigurationDescription - } - if esar.RuleCollectionDescription != nil { - objectMap["ruleCollectionDescription"] = esar.RuleCollectionDescription - } - if esar.RuleCollectionAppliesToGroups != nil { - objectMap["ruleCollectionAppliesToGroups"] = esar.RuleCollectionAppliesToGroups - } - if esar.RuleGroups != nil { - objectMap["ruleGroups"] = esar.RuleGroups - } - if esar.Kind != "" { - objectMap["kind"] = esar.Kind - } - return json.Marshal(objectMap) -} - -// AsEffectiveSecurityAdminRule is the BasicEffectiveBaseSecurityAdminRule implementation for EffectiveSecurityAdminRule. -func (esar EffectiveSecurityAdminRule) AsEffectiveSecurityAdminRule() (*EffectiveSecurityAdminRule, bool) { - return &esar, true -} - -// AsEffectiveDefaultSecurityAdminRule is the BasicEffectiveBaseSecurityAdminRule implementation for EffectiveSecurityAdminRule. -func (esar EffectiveSecurityAdminRule) AsEffectiveDefaultSecurityAdminRule() (*EffectiveDefaultSecurityAdminRule, bool) { - return nil, false -} - -// AsEffectiveBaseSecurityAdminRule is the BasicEffectiveBaseSecurityAdminRule implementation for EffectiveSecurityAdminRule. -func (esar EffectiveSecurityAdminRule) AsEffectiveBaseSecurityAdminRule() (*EffectiveBaseSecurityAdminRule, bool) { - return nil, false -} - -// AsBasicEffectiveBaseSecurityAdminRule is the BasicEffectiveBaseSecurityAdminRule implementation for EffectiveSecurityAdminRule. -func (esar EffectiveSecurityAdminRule) AsBasicEffectiveBaseSecurityAdminRule() (BasicEffectiveBaseSecurityAdminRule, bool) { - return &esar, true -} - -// UnmarshalJSON is the custom unmarshaler for EffectiveSecurityAdminRule struct. -func (esar *EffectiveSecurityAdminRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var adminPropertiesFormat AdminPropertiesFormat - err = json.Unmarshal(*v, &adminPropertiesFormat) - if err != nil { - return err - } - esar.AdminPropertiesFormat = &adminPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - esar.ID = &ID - } - case "configurationDescription": - if v != nil { - var configurationDescription string - err = json.Unmarshal(*v, &configurationDescription) - if err != nil { - return err - } - esar.ConfigurationDescription = &configurationDescription - } - case "ruleCollectionDescription": - if v != nil { - var ruleCollectionDescription string - err = json.Unmarshal(*v, &ruleCollectionDescription) - if err != nil { - return err - } - esar.RuleCollectionDescription = &ruleCollectionDescription - } - case "ruleCollectionAppliesToGroups": - if v != nil { - var ruleCollectionAppliesToGroups []ManagerSecurityGroupItem - err = json.Unmarshal(*v, &ruleCollectionAppliesToGroups) - if err != nil { - return err - } - esar.RuleCollectionAppliesToGroups = &ruleCollectionAppliesToGroups - } - case "ruleGroups": - if v != nil { - var ruleGroups []ConfigurationGroup - err = json.Unmarshal(*v, &ruleGroups) - if err != nil { - return err - } - esar.RuleGroups = &ruleGroups - } - case "kind": - if v != nil { - var kind KindBasicEffectiveBaseSecurityAdminRule - err = json.Unmarshal(*v, &kind) - if err != nil { - return err - } - esar.Kind = kind - } - } - } - - return nil -} - -// EndpointServiceResult endpoint service. -type EndpointServiceResult struct { - // Name - READ-ONLY; Name of the endpoint service. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Type of the endpoint service. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for EndpointServiceResult. -func (esr EndpointServiceResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if esr.ID != nil { - objectMap["id"] = esr.ID - } - return json.Marshal(objectMap) -} - -// EndpointServicesListResult response for the ListAvailableEndpointServices API service call. -type EndpointServicesListResult struct { - autorest.Response `json:"-"` - // Value - List of available endpoint services in a region. - Value *[]EndpointServiceResult `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// EndpointServicesListResultIterator provides access to a complete listing of EndpointServiceResult -// values. -type EndpointServicesListResultIterator struct { - i int - page EndpointServicesListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *EndpointServicesListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/EndpointServicesListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *EndpointServicesListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter EndpointServicesListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter EndpointServicesListResultIterator) Response() EndpointServicesListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter EndpointServicesListResultIterator) Value() EndpointServiceResult { - if !iter.page.NotDone() { - return EndpointServiceResult{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the EndpointServicesListResultIterator type. -func NewEndpointServicesListResultIterator(page EndpointServicesListResultPage) EndpointServicesListResultIterator { - return EndpointServicesListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (eslr EndpointServicesListResult) IsEmpty() bool { - return eslr.Value == nil || len(*eslr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (eslr EndpointServicesListResult) hasNextLink() bool { - return eslr.NextLink != nil && len(*eslr.NextLink) != 0 -} - -// endpointServicesListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (eslr EndpointServicesListResult) endpointServicesListResultPreparer(ctx context.Context) (*http.Request, error) { - if !eslr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(eslr.NextLink))) -} - -// EndpointServicesListResultPage contains a page of EndpointServiceResult values. -type EndpointServicesListResultPage struct { - fn func(context.Context, EndpointServicesListResult) (EndpointServicesListResult, error) - eslr EndpointServicesListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *EndpointServicesListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/EndpointServicesListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.eslr) - if err != nil { - return err - } - page.eslr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *EndpointServicesListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page EndpointServicesListResultPage) NotDone() bool { - return !page.eslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page EndpointServicesListResultPage) Response() EndpointServicesListResult { - return page.eslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page EndpointServicesListResultPage) Values() []EndpointServiceResult { - if page.eslr.IsEmpty() { - return nil - } - return *page.eslr.Value -} - -// Creates a new instance of the EndpointServicesListResultPage type. -func NewEndpointServicesListResultPage(cur EndpointServicesListResult, getNextPage func(context.Context, EndpointServicesListResult) (EndpointServicesListResult, error)) EndpointServicesListResultPage { - return EndpointServicesListResultPage{ - fn: getNextPage, - eslr: cur, - } -} - -// Error common error representation. -type Error struct { - // Code - Error code. - Code *string `json:"code,omitempty"` - // Message - Error message. - Message *string `json:"message,omitempty"` - // Target - Error target. - Target *string `json:"target,omitempty"` - // Details - Error details. - Details *[]ErrorDetails `json:"details,omitempty"` - // InnerError - Inner error message. - InnerError *string `json:"innerError,omitempty"` -} - -// ErrorDetails common error details representation. -type ErrorDetails struct { - // Code - Error code. - Code *string `json:"code,omitempty"` - // Target - Error target. - Target *string `json:"target,omitempty"` - // Message - Error message. - Message *string `json:"message,omitempty"` -} - -// ErrorResponse the error object. -type ErrorResponse struct { - // Error - The error details object. - Error *ErrorDetails `json:"error,omitempty"` -} - -// EvaluatedNetworkSecurityGroup results of network security group evaluation. -type EvaluatedNetworkSecurityGroup struct { - // NetworkSecurityGroupID - Network security group ID. - NetworkSecurityGroupID *string `json:"networkSecurityGroupId,omitempty"` - // AppliedTo - Resource ID of nic or subnet to which network security group is applied. - AppliedTo *string `json:"appliedTo,omitempty"` - // MatchedRule - Matched network security rule. - MatchedRule *MatchedRule `json:"matchedRule,omitempty"` - // RulesEvaluationResult - READ-ONLY; List of network security rules evaluation results. - RulesEvaluationResult *[]SecurityRulesEvaluationResult `json:"rulesEvaluationResult,omitempty"` -} - -// MarshalJSON is the custom marshaler for EvaluatedNetworkSecurityGroup. -func (ensg EvaluatedNetworkSecurityGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ensg.NetworkSecurityGroupID != nil { - objectMap["networkSecurityGroupId"] = ensg.NetworkSecurityGroupID - } - if ensg.AppliedTo != nil { - objectMap["appliedTo"] = ensg.AppliedTo - } - if ensg.MatchedRule != nil { - objectMap["matchedRule"] = ensg.MatchedRule - } - return json.Marshal(objectMap) -} - -// ExclusionManagedRule defines a managed rule to use for exclusion. -type ExclusionManagedRule struct { - // RuleID - Identifier for the managed rule. - RuleID *string `json:"ruleId,omitempty"` -} - -// ExclusionManagedRuleGroup defines a managed rule group to use for exclusion. -type ExclusionManagedRuleGroup struct { - // RuleGroupName - The managed rule group for exclusion. - RuleGroupName *string `json:"ruleGroupName,omitempty"` - // Rules - List of rules that will be excluded. If none specified, all rules in the group will be excluded. - Rules *[]ExclusionManagedRule `json:"rules,omitempty"` -} - -// ExclusionManagedRuleSet defines a managed rule set for Exclusions. -type ExclusionManagedRuleSet struct { - // RuleSetType - Defines the rule set type to use. - RuleSetType *string `json:"ruleSetType,omitempty"` - // RuleSetVersion - Defines the version of the rule set to use. - RuleSetVersion *string `json:"ruleSetVersion,omitempty"` - // RuleGroups - Defines the rule groups to apply to the rule set. - RuleGroups *[]ExclusionManagedRuleGroup `json:"ruleGroups,omitempty"` -} - -// ExplicitProxy explicit Proxy Settings in Firewall Policy. -type ExplicitProxy struct { - // EnableExplicitProxy - When set to true, explicit proxy mode is enabled. - EnableExplicitProxy *bool `json:"enableExplicitProxy,omitempty"` - // HTTPPort - Port number for explicit proxy http protocol, cannot be greater than 64000. - HTTPPort *int32 `json:"httpPort,omitempty"` - // HTTPSPort - Port number for explicit proxy https protocol, cannot be greater than 64000. - HTTPSPort *int32 `json:"httpsPort,omitempty"` - // EnablePacFile - When set to true, pac file port and url needs to be provided. - EnablePacFile *bool `json:"enablePacFile,omitempty"` - // PacFilePort - Port number for firewall to serve PAC file. - PacFilePort *int32 `json:"pacFilePort,omitempty"` - // PacFile - SAS URL for PAC file. - PacFile *string `json:"pacFile,omitempty"` -} - -// ExpressRouteCircuit expressRouteCircuit resource. -type ExpressRouteCircuit struct { - autorest.Response `json:"-"` - // Sku - The SKU. - Sku *ExpressRouteCircuitSku `json:"sku,omitempty"` - // ExpressRouteCircuitPropertiesFormat - Properties of the express route circuit. - *ExpressRouteCircuitPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuit. -func (erc ExpressRouteCircuit) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erc.Sku != nil { - objectMap["sku"] = erc.Sku - } - if erc.ExpressRouteCircuitPropertiesFormat != nil { - objectMap["properties"] = erc.ExpressRouteCircuitPropertiesFormat - } - if erc.ID != nil { - objectMap["id"] = erc.ID - } - if erc.Location != nil { - objectMap["location"] = erc.Location - } - if erc.Tags != nil { - objectMap["tags"] = erc.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteCircuit struct. -func (erc *ExpressRouteCircuit) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "sku": - if v != nil { - var sku ExpressRouteCircuitSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - erc.Sku = &sku - } - case "properties": - if v != nil { - var expressRouteCircuitPropertiesFormat ExpressRouteCircuitPropertiesFormat - err = json.Unmarshal(*v, &expressRouteCircuitPropertiesFormat) - if err != nil { - return err - } - erc.ExpressRouteCircuitPropertiesFormat = &expressRouteCircuitPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - erc.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - erc.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - erc.Tags = tags - } - } - } - - return nil -} - -// ExpressRouteCircuitArpTable the ARP table associated with the ExpressRouteCircuit. -type ExpressRouteCircuitArpTable struct { - // Age - Entry age in minutes. - Age *int32 `json:"age,omitempty"` - // Interface - Interface address. - Interface *string `json:"interface,omitempty"` - // IPAddress - The IP address. - IPAddress *string `json:"ipAddress,omitempty"` - // MacAddress - The MAC address. - MacAddress *string `json:"macAddress,omitempty"` -} - -// ExpressRouteCircuitAuthorization authorization in an ExpressRouteCircuit resource. -type ExpressRouteCircuitAuthorization struct { - autorest.Response `json:"-"` - // AuthorizationPropertiesFormat - Properties of the express route circuit authorization. - *AuthorizationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuitAuthorization. -func (erca ExpressRouteCircuitAuthorization) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erca.AuthorizationPropertiesFormat != nil { - objectMap["properties"] = erca.AuthorizationPropertiesFormat - } - if erca.Name != nil { - objectMap["name"] = erca.Name - } - if erca.ID != nil { - objectMap["id"] = erca.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteCircuitAuthorization struct. -func (erca *ExpressRouteCircuitAuthorization) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var authorizationPropertiesFormat AuthorizationPropertiesFormat - err = json.Unmarshal(*v, &authorizationPropertiesFormat) - if err != nil { - return err - } - erca.AuthorizationPropertiesFormat = &authorizationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erca.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erca.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - erca.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erca.ID = &ID - } - } - } - - return nil -} - -// ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitAuthorizationsClient) (ExpressRouteCircuitAuthorization, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture.Result. -func (future *ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture) result(client ExpressRouteCircuitAuthorizationsClient) (erca ExpressRouteCircuitAuthorization, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erca.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erca.Response.Response, err = future.GetResult(sender); err == nil && erca.Response.Response.StatusCode != http.StatusNoContent { - erca, err = client.CreateOrUpdateResponder(erca.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsCreateOrUpdateFuture", "Result", erca.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitAuthorizationsDeleteFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type ExpressRouteCircuitAuthorizationsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitAuthorizationsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitAuthorizationsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitAuthorizationsDeleteFuture.Result. -func (future *ExpressRouteCircuitAuthorizationsDeleteFuture) result(client ExpressRouteCircuitAuthorizationsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitAuthorizationsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteCircuitConnection express Route Circuit Connection in an ExpressRouteCircuitPeering -// resource. -type ExpressRouteCircuitConnection struct { - autorest.Response `json:"-"` - // ExpressRouteCircuitConnectionPropertiesFormat - Properties of the express route circuit connection. - *ExpressRouteCircuitConnectionPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuitConnection. -func (ercc ExpressRouteCircuitConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercc.ExpressRouteCircuitConnectionPropertiesFormat != nil { - objectMap["properties"] = ercc.ExpressRouteCircuitConnectionPropertiesFormat - } - if ercc.Name != nil { - objectMap["name"] = ercc.Name - } - if ercc.ID != nil { - objectMap["id"] = ercc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteCircuitConnection struct. -func (ercc *ExpressRouteCircuitConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteCircuitConnectionPropertiesFormat ExpressRouteCircuitConnectionPropertiesFormat - err = json.Unmarshal(*v, &expressRouteCircuitConnectionPropertiesFormat) - if err != nil { - return err - } - ercc.ExpressRouteCircuitConnectionPropertiesFormat = &expressRouteCircuitConnectionPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ercc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ercc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ercc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ercc.ID = &ID - } - } - } - - return nil -} - -// ExpressRouteCircuitConnectionListResult response for ListConnections API service call retrieves all -// global reach connections that belongs to a Private Peering for an ExpressRouteCircuit. -type ExpressRouteCircuitConnectionListResult struct { - autorest.Response `json:"-"` - // Value - The global reach connection associated with Private Peering in an ExpressRoute Circuit. - Value *[]ExpressRouteCircuitConnection `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteCircuitConnectionListResultIterator provides access to a complete listing of -// ExpressRouteCircuitConnection values. -type ExpressRouteCircuitConnectionListResultIterator struct { - i int - page ExpressRouteCircuitConnectionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteCircuitConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteCircuitConnectionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteCircuitConnectionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteCircuitConnectionListResultIterator) Response() ExpressRouteCircuitConnectionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteCircuitConnectionListResultIterator) Value() ExpressRouteCircuitConnection { - if !iter.page.NotDone() { - return ExpressRouteCircuitConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteCircuitConnectionListResultIterator type. -func NewExpressRouteCircuitConnectionListResultIterator(page ExpressRouteCircuitConnectionListResultPage) ExpressRouteCircuitConnectionListResultIterator { - return ExpressRouteCircuitConnectionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ercclr ExpressRouteCircuitConnectionListResult) IsEmpty() bool { - return ercclr.Value == nil || len(*ercclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ercclr ExpressRouteCircuitConnectionListResult) hasNextLink() bool { - return ercclr.NextLink != nil && len(*ercclr.NextLink) != 0 -} - -// expressRouteCircuitConnectionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ercclr ExpressRouteCircuitConnectionListResult) expressRouteCircuitConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ercclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ercclr.NextLink))) -} - -// ExpressRouteCircuitConnectionListResultPage contains a page of ExpressRouteCircuitConnection values. -type ExpressRouteCircuitConnectionListResultPage struct { - fn func(context.Context, ExpressRouteCircuitConnectionListResult) (ExpressRouteCircuitConnectionListResult, error) - ercclr ExpressRouteCircuitConnectionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteCircuitConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitConnectionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ercclr) - if err != nil { - return err - } - page.ercclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteCircuitConnectionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteCircuitConnectionListResultPage) NotDone() bool { - return !page.ercclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteCircuitConnectionListResultPage) Response() ExpressRouteCircuitConnectionListResult { - return page.ercclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteCircuitConnectionListResultPage) Values() []ExpressRouteCircuitConnection { - if page.ercclr.IsEmpty() { - return nil - } - return *page.ercclr.Value -} - -// Creates a new instance of the ExpressRouteCircuitConnectionListResultPage type. -func NewExpressRouteCircuitConnectionListResultPage(cur ExpressRouteCircuitConnectionListResult, getNextPage func(context.Context, ExpressRouteCircuitConnectionListResult) (ExpressRouteCircuitConnectionListResult, error)) ExpressRouteCircuitConnectionListResultPage { - return ExpressRouteCircuitConnectionListResultPage{ - fn: getNextPage, - ercclr: cur, - } -} - -// ExpressRouteCircuitConnectionPropertiesFormat properties of the express route circuit connection. -type ExpressRouteCircuitConnectionPropertiesFormat struct { - // ExpressRouteCircuitPeering - Reference to Express Route Circuit Private Peering Resource of the circuit initiating connection. - ExpressRouteCircuitPeering *SubResource `json:"expressRouteCircuitPeering,omitempty"` - // PeerExpressRouteCircuitPeering - Reference to Express Route Circuit Private Peering Resource of the peered circuit. - PeerExpressRouteCircuitPeering *SubResource `json:"peerExpressRouteCircuitPeering,omitempty"` - // AddressPrefix - /29 IP address space to carve out Customer addresses for tunnels. - AddressPrefix *string `json:"addressPrefix,omitempty"` - // AuthorizationKey - The authorization key. - AuthorizationKey *string `json:"authorizationKey,omitempty"` - // Ipv6CircuitConnectionConfig - IPv6 Address PrefixProperties of the express route circuit connection. - Ipv6CircuitConnectionConfig *Ipv6CircuitConnectionConfig `json:"ipv6CircuitConnectionConfig,omitempty"` - // CircuitConnectionStatus - Express Route Circuit connection state. Possible values include: 'Connected', 'Connecting', 'Disconnected' - CircuitConnectionStatus CircuitConnectionStatus `json:"circuitConnectionStatus,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the express route circuit connection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuitConnectionPropertiesFormat. -func (erccpf ExpressRouteCircuitConnectionPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erccpf.ExpressRouteCircuitPeering != nil { - objectMap["expressRouteCircuitPeering"] = erccpf.ExpressRouteCircuitPeering - } - if erccpf.PeerExpressRouteCircuitPeering != nil { - objectMap["peerExpressRouteCircuitPeering"] = erccpf.PeerExpressRouteCircuitPeering - } - if erccpf.AddressPrefix != nil { - objectMap["addressPrefix"] = erccpf.AddressPrefix - } - if erccpf.AuthorizationKey != nil { - objectMap["authorizationKey"] = erccpf.AuthorizationKey - } - if erccpf.Ipv6CircuitConnectionConfig != nil { - objectMap["ipv6CircuitConnectionConfig"] = erccpf.Ipv6CircuitConnectionConfig - } - if erccpf.CircuitConnectionStatus != "" { - objectMap["circuitConnectionStatus"] = erccpf.CircuitConnectionStatus - } - return json.Marshal(objectMap) -} - -// ExpressRouteCircuitConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ExpressRouteCircuitConnectionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitConnectionsClient) (ExpressRouteCircuitConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitConnectionsCreateOrUpdateFuture.Result. -func (future *ExpressRouteCircuitConnectionsCreateOrUpdateFuture) result(client ExpressRouteCircuitConnectionsClient) (ercc ExpressRouteCircuitConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitConnectionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercc.Response.Response, err = future.GetResult(sender); err == nil && ercc.Response.Response.StatusCode != http.StatusNoContent { - ercc, err = client.CreateOrUpdateResponder(ercc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsCreateOrUpdateFuture", "Result", ercc.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteCircuitConnectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitConnectionsDeleteFuture.Result. -func (future *ExpressRouteCircuitConnectionsDeleteFuture) result(client ExpressRouteCircuitConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitConnectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteCircuitListResult response for ListExpressRouteCircuit API service call. -type ExpressRouteCircuitListResult struct { - autorest.Response `json:"-"` - // Value - A list of ExpressRouteCircuits in a resource group. - Value *[]ExpressRouteCircuit `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteCircuitListResultIterator provides access to a complete listing of ExpressRouteCircuit -// values. -type ExpressRouteCircuitListResultIterator struct { - i int - page ExpressRouteCircuitListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteCircuitListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteCircuitListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteCircuitListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteCircuitListResultIterator) Response() ExpressRouteCircuitListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteCircuitListResultIterator) Value() ExpressRouteCircuit { - if !iter.page.NotDone() { - return ExpressRouteCircuit{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteCircuitListResultIterator type. -func NewExpressRouteCircuitListResultIterator(page ExpressRouteCircuitListResultPage) ExpressRouteCircuitListResultIterator { - return ExpressRouteCircuitListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (erclr ExpressRouteCircuitListResult) IsEmpty() bool { - return erclr.Value == nil || len(*erclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (erclr ExpressRouteCircuitListResult) hasNextLink() bool { - return erclr.NextLink != nil && len(*erclr.NextLink) != 0 -} - -// expressRouteCircuitListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (erclr ExpressRouteCircuitListResult) expressRouteCircuitListResultPreparer(ctx context.Context) (*http.Request, error) { - if !erclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(erclr.NextLink))) -} - -// ExpressRouteCircuitListResultPage contains a page of ExpressRouteCircuit values. -type ExpressRouteCircuitListResultPage struct { - fn func(context.Context, ExpressRouteCircuitListResult) (ExpressRouteCircuitListResult, error) - erclr ExpressRouteCircuitListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteCircuitListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.erclr) - if err != nil { - return err - } - page.erclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteCircuitListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteCircuitListResultPage) NotDone() bool { - return !page.erclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteCircuitListResultPage) Response() ExpressRouteCircuitListResult { - return page.erclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteCircuitListResultPage) Values() []ExpressRouteCircuit { - if page.erclr.IsEmpty() { - return nil - } - return *page.erclr.Value -} - -// Creates a new instance of the ExpressRouteCircuitListResultPage type. -func NewExpressRouteCircuitListResultPage(cur ExpressRouteCircuitListResult, getNextPage func(context.Context, ExpressRouteCircuitListResult) (ExpressRouteCircuitListResult, error)) ExpressRouteCircuitListResultPage { - return ExpressRouteCircuitListResultPage{ - fn: getNextPage, - erclr: cur, - } -} - -// ExpressRouteCircuitPeering peering in an ExpressRouteCircuit resource. -type ExpressRouteCircuitPeering struct { - autorest.Response `json:"-"` - // ExpressRouteCircuitPeeringPropertiesFormat - Properties of the express route circuit peering. - *ExpressRouteCircuitPeeringPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuitPeering. -func (ercp ExpressRouteCircuitPeering) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercp.ExpressRouteCircuitPeeringPropertiesFormat != nil { - objectMap["properties"] = ercp.ExpressRouteCircuitPeeringPropertiesFormat - } - if ercp.Name != nil { - objectMap["name"] = ercp.Name - } - if ercp.ID != nil { - objectMap["id"] = ercp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteCircuitPeering struct. -func (ercp *ExpressRouteCircuitPeering) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteCircuitPeeringPropertiesFormat ExpressRouteCircuitPeeringPropertiesFormat - err = json.Unmarshal(*v, &expressRouteCircuitPeeringPropertiesFormat) - if err != nil { - return err - } - ercp.ExpressRouteCircuitPeeringPropertiesFormat = &expressRouteCircuitPeeringPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ercp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ercp.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ercp.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ercp.ID = &ID - } - } - } - - return nil -} - -// ExpressRouteCircuitPeeringConfig specifies the peering configuration. -type ExpressRouteCircuitPeeringConfig struct { - // AdvertisedPublicPrefixes - The reference to AdvertisedPublicPrefixes. - AdvertisedPublicPrefixes *[]string `json:"advertisedPublicPrefixes,omitempty"` - // AdvertisedCommunities - The communities of bgp peering. Specified for microsoft peering. - AdvertisedCommunities *[]string `json:"advertisedCommunities,omitempty"` - // AdvertisedPublicPrefixesState - READ-ONLY; The advertised public prefix state of the Peering resource. Possible values include: 'NotConfigured', 'Configuring', 'Configured', 'ValidationNeeded' - AdvertisedPublicPrefixesState ExpressRouteCircuitPeeringAdvertisedPublicPrefixState `json:"advertisedPublicPrefixesState,omitempty"` - // LegacyMode - The legacy mode of the peering. - LegacyMode *int32 `json:"legacyMode,omitempty"` - // CustomerASN - The CustomerASN of the peering. - CustomerASN *int32 `json:"customerASN,omitempty"` - // RoutingRegistryName - The RoutingRegistryName of the configuration. - RoutingRegistryName *string `json:"routingRegistryName,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuitPeeringConfig. -func (ercpc ExpressRouteCircuitPeeringConfig) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercpc.AdvertisedPublicPrefixes != nil { - objectMap["advertisedPublicPrefixes"] = ercpc.AdvertisedPublicPrefixes - } - if ercpc.AdvertisedCommunities != nil { - objectMap["advertisedCommunities"] = ercpc.AdvertisedCommunities - } - if ercpc.LegacyMode != nil { - objectMap["legacyMode"] = ercpc.LegacyMode - } - if ercpc.CustomerASN != nil { - objectMap["customerASN"] = ercpc.CustomerASN - } - if ercpc.RoutingRegistryName != nil { - objectMap["routingRegistryName"] = ercpc.RoutingRegistryName - } - return json.Marshal(objectMap) -} - -// ExpressRouteCircuitPeeringID expressRoute circuit peering identifier. -type ExpressRouteCircuitPeeringID struct { - // ID - The ID of the ExpressRoute circuit peering. - ID *string `json:"id,omitempty"` -} - -// ExpressRouteCircuitPeeringListResult response for ListPeering API service call retrieves all peerings -// that belong to an ExpressRouteCircuit. -type ExpressRouteCircuitPeeringListResult struct { - autorest.Response `json:"-"` - // Value - The peerings in an express route circuit. - Value *[]ExpressRouteCircuitPeering `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteCircuitPeeringListResultIterator provides access to a complete listing of -// ExpressRouteCircuitPeering values. -type ExpressRouteCircuitPeeringListResultIterator struct { - i int - page ExpressRouteCircuitPeeringListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteCircuitPeeringListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteCircuitPeeringListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteCircuitPeeringListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteCircuitPeeringListResultIterator) Response() ExpressRouteCircuitPeeringListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteCircuitPeeringListResultIterator) Value() ExpressRouteCircuitPeering { - if !iter.page.NotDone() { - return ExpressRouteCircuitPeering{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteCircuitPeeringListResultIterator type. -func NewExpressRouteCircuitPeeringListResultIterator(page ExpressRouteCircuitPeeringListResultPage) ExpressRouteCircuitPeeringListResultIterator { - return ExpressRouteCircuitPeeringListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ercplr ExpressRouteCircuitPeeringListResult) IsEmpty() bool { - return ercplr.Value == nil || len(*ercplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ercplr ExpressRouteCircuitPeeringListResult) hasNextLink() bool { - return ercplr.NextLink != nil && len(*ercplr.NextLink) != 0 -} - -// expressRouteCircuitPeeringListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ercplr ExpressRouteCircuitPeeringListResult) expressRouteCircuitPeeringListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ercplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ercplr.NextLink))) -} - -// ExpressRouteCircuitPeeringListResultPage contains a page of ExpressRouteCircuitPeering values. -type ExpressRouteCircuitPeeringListResultPage struct { - fn func(context.Context, ExpressRouteCircuitPeeringListResult) (ExpressRouteCircuitPeeringListResult, error) - ercplr ExpressRouteCircuitPeeringListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteCircuitPeeringListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCircuitPeeringListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ercplr) - if err != nil { - return err - } - page.ercplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteCircuitPeeringListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteCircuitPeeringListResultPage) NotDone() bool { - return !page.ercplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteCircuitPeeringListResultPage) Response() ExpressRouteCircuitPeeringListResult { - return page.ercplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteCircuitPeeringListResultPage) Values() []ExpressRouteCircuitPeering { - if page.ercplr.IsEmpty() { - return nil - } - return *page.ercplr.Value -} - -// Creates a new instance of the ExpressRouteCircuitPeeringListResultPage type. -func NewExpressRouteCircuitPeeringListResultPage(cur ExpressRouteCircuitPeeringListResult, getNextPage func(context.Context, ExpressRouteCircuitPeeringListResult) (ExpressRouteCircuitPeeringListResult, error)) ExpressRouteCircuitPeeringListResultPage { - return ExpressRouteCircuitPeeringListResultPage{ - fn: getNextPage, - ercplr: cur, - } -} - -// ExpressRouteCircuitPeeringPropertiesFormat properties of the express route circuit peering. -type ExpressRouteCircuitPeeringPropertiesFormat struct { - // PeeringType - The peering type. Possible values include: 'AzurePublicPeering', 'AzurePrivatePeering', 'MicrosoftPeering' - PeeringType ExpressRoutePeeringType `json:"peeringType,omitempty"` - // State - The peering state. Possible values include: 'ExpressRoutePeeringStateDisabled', 'ExpressRoutePeeringStateEnabled' - State ExpressRoutePeeringState `json:"state,omitempty"` - // AzureASN - The Azure ASN. - AzureASN *int32 `json:"azureASN,omitempty"` - // PeerASN - The peer ASN. - PeerASN *int64 `json:"peerASN,omitempty"` - // PrimaryPeerAddressPrefix - The primary address prefix. - PrimaryPeerAddressPrefix *string `json:"primaryPeerAddressPrefix,omitempty"` - // SecondaryPeerAddressPrefix - The secondary address prefix. - SecondaryPeerAddressPrefix *string `json:"secondaryPeerAddressPrefix,omitempty"` - // PrimaryAzurePort - The primary port. - PrimaryAzurePort *string `json:"primaryAzurePort,omitempty"` - // SecondaryAzurePort - The secondary port. - SecondaryAzurePort *string `json:"secondaryAzurePort,omitempty"` - // SharedKey - The shared key. - SharedKey *string `json:"sharedKey,omitempty"` - // VlanID - The VLAN ID. - VlanID *int32 `json:"vlanId,omitempty"` - // MicrosoftPeeringConfig - The Microsoft peering configuration. - MicrosoftPeeringConfig *ExpressRouteCircuitPeeringConfig `json:"microsoftPeeringConfig,omitempty"` - // Stats - The peering stats of express route circuit. - Stats *ExpressRouteCircuitStats `json:"stats,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the express route circuit peering resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // GatewayManagerEtag - The GatewayManager Etag. - GatewayManagerEtag *string `json:"gatewayManagerEtag,omitempty"` - // LastModifiedBy - READ-ONLY; Who was the last to modify the peering. - LastModifiedBy *string `json:"lastModifiedBy,omitempty"` - // RouteFilter - The reference to the RouteFilter resource. - RouteFilter *SubResource `json:"routeFilter,omitempty"` - // Ipv6PeeringConfig - The IPv6 peering configuration. - Ipv6PeeringConfig *Ipv6ExpressRouteCircuitPeeringConfig `json:"ipv6PeeringConfig,omitempty"` - // ExpressRouteConnection - The ExpressRoute connection. - ExpressRouteConnection *ExpressRouteConnectionID `json:"expressRouteConnection,omitempty"` - // Connections - The list of circuit connections associated with Azure Private Peering for this circuit. - Connections *[]ExpressRouteCircuitConnection `json:"connections,omitempty"` - // PeeredConnections - READ-ONLY; The list of peered circuit connections associated with Azure Private Peering for this circuit. - PeeredConnections *[]PeerExpressRouteCircuitConnection `json:"peeredConnections,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuitPeeringPropertiesFormat. -func (ercppf ExpressRouteCircuitPeeringPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercppf.PeeringType != "" { - objectMap["peeringType"] = ercppf.PeeringType - } - if ercppf.State != "" { - objectMap["state"] = ercppf.State - } - if ercppf.AzureASN != nil { - objectMap["azureASN"] = ercppf.AzureASN - } - if ercppf.PeerASN != nil { - objectMap["peerASN"] = ercppf.PeerASN - } - if ercppf.PrimaryPeerAddressPrefix != nil { - objectMap["primaryPeerAddressPrefix"] = ercppf.PrimaryPeerAddressPrefix - } - if ercppf.SecondaryPeerAddressPrefix != nil { - objectMap["secondaryPeerAddressPrefix"] = ercppf.SecondaryPeerAddressPrefix - } - if ercppf.PrimaryAzurePort != nil { - objectMap["primaryAzurePort"] = ercppf.PrimaryAzurePort - } - if ercppf.SecondaryAzurePort != nil { - objectMap["secondaryAzurePort"] = ercppf.SecondaryAzurePort - } - if ercppf.SharedKey != nil { - objectMap["sharedKey"] = ercppf.SharedKey - } - if ercppf.VlanID != nil { - objectMap["vlanId"] = ercppf.VlanID - } - if ercppf.MicrosoftPeeringConfig != nil { - objectMap["microsoftPeeringConfig"] = ercppf.MicrosoftPeeringConfig - } - if ercppf.Stats != nil { - objectMap["stats"] = ercppf.Stats - } - if ercppf.GatewayManagerEtag != nil { - objectMap["gatewayManagerEtag"] = ercppf.GatewayManagerEtag - } - if ercppf.RouteFilter != nil { - objectMap["routeFilter"] = ercppf.RouteFilter - } - if ercppf.Ipv6PeeringConfig != nil { - objectMap["ipv6PeeringConfig"] = ercppf.Ipv6PeeringConfig - } - if ercppf.ExpressRouteConnection != nil { - objectMap["expressRouteConnection"] = ercppf.ExpressRouteConnection - } - if ercppf.Connections != nil { - objectMap["connections"] = ercppf.Connections - } - return json.Marshal(objectMap) -} - -// ExpressRouteCircuitPeeringsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type ExpressRouteCircuitPeeringsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitPeeringsClient) (ExpressRouteCircuitPeering, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitPeeringsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitPeeringsCreateOrUpdateFuture.Result. -func (future *ExpressRouteCircuitPeeringsCreateOrUpdateFuture) result(client ExpressRouteCircuitPeeringsClient) (ercp ExpressRouteCircuitPeering, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitPeeringsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercp.Response.Response, err = future.GetResult(sender); err == nil && ercp.Response.Response.StatusCode != http.StatusNoContent { - ercp, err = client.CreateOrUpdateResponder(ercp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsCreateOrUpdateFuture", "Result", ercp.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitPeeringsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteCircuitPeeringsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitPeeringsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitPeeringsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitPeeringsDeleteFuture.Result. -func (future *ExpressRouteCircuitPeeringsDeleteFuture) result(client ExpressRouteCircuitPeeringsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitPeeringsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteCircuitPropertiesFormat properties of ExpressRouteCircuit. -type ExpressRouteCircuitPropertiesFormat struct { - // AllowClassicOperations - Allow classic operations. - AllowClassicOperations *bool `json:"allowClassicOperations,omitempty"` - // CircuitProvisioningState - The CircuitProvisioningState state of the resource. - CircuitProvisioningState *string `json:"circuitProvisioningState,omitempty"` - // ServiceProviderProvisioningState - The ServiceProviderProvisioningState state of the resource. Possible values include: 'ServiceProviderProvisioningStateNotProvisioned', 'ServiceProviderProvisioningStateProvisioning', 'ServiceProviderProvisioningStateProvisioned', 'ServiceProviderProvisioningStateDeprovisioning' - ServiceProviderProvisioningState ServiceProviderProvisioningState `json:"serviceProviderProvisioningState,omitempty"` - // Authorizations - The list of authorizations. - Authorizations *[]ExpressRouteCircuitAuthorization `json:"authorizations,omitempty"` - // Peerings - The list of peerings. - Peerings *[]ExpressRouteCircuitPeering `json:"peerings,omitempty"` - // ServiceKey - The ServiceKey. - ServiceKey *string `json:"serviceKey,omitempty"` - // ServiceProviderNotes - The ServiceProviderNotes. - ServiceProviderNotes *string `json:"serviceProviderNotes,omitempty"` - // ServiceProviderProperties - The ServiceProviderProperties. - ServiceProviderProperties *ExpressRouteCircuitServiceProviderProperties `json:"serviceProviderProperties,omitempty"` - // ExpressRoutePort - The reference to the ExpressRoutePort resource when the circuit is provisioned on an ExpressRoutePort resource. - ExpressRoutePort *SubResource `json:"expressRoutePort,omitempty"` - // BandwidthInGbps - The bandwidth of the circuit when the circuit is provisioned on an ExpressRoutePort resource. - BandwidthInGbps *float64 `json:"bandwidthInGbps,omitempty"` - // Stag - READ-ONLY; The identifier of the circuit traffic. Outer tag for QinQ encapsulation. - Stag *int32 `json:"stag,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the express route circuit resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // GatewayManagerEtag - The GatewayManager Etag. - GatewayManagerEtag *string `json:"gatewayManagerEtag,omitempty"` - // GlobalReachEnabled - Flag denoting global reach status. - GlobalReachEnabled *bool `json:"globalReachEnabled,omitempty"` - // AuthorizationKey - The authorizationKey. - AuthorizationKey *string `json:"authorizationKey,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCircuitPropertiesFormat. -func (ercpf ExpressRouteCircuitPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercpf.AllowClassicOperations != nil { - objectMap["allowClassicOperations"] = ercpf.AllowClassicOperations - } - if ercpf.CircuitProvisioningState != nil { - objectMap["circuitProvisioningState"] = ercpf.CircuitProvisioningState - } - if ercpf.ServiceProviderProvisioningState != "" { - objectMap["serviceProviderProvisioningState"] = ercpf.ServiceProviderProvisioningState - } - if ercpf.Authorizations != nil { - objectMap["authorizations"] = ercpf.Authorizations - } - if ercpf.Peerings != nil { - objectMap["peerings"] = ercpf.Peerings - } - if ercpf.ServiceKey != nil { - objectMap["serviceKey"] = ercpf.ServiceKey - } - if ercpf.ServiceProviderNotes != nil { - objectMap["serviceProviderNotes"] = ercpf.ServiceProviderNotes - } - if ercpf.ServiceProviderProperties != nil { - objectMap["serviceProviderProperties"] = ercpf.ServiceProviderProperties - } - if ercpf.ExpressRoutePort != nil { - objectMap["expressRoutePort"] = ercpf.ExpressRoutePort - } - if ercpf.BandwidthInGbps != nil { - objectMap["bandwidthInGbps"] = ercpf.BandwidthInGbps - } - if ercpf.GatewayManagerEtag != nil { - objectMap["gatewayManagerEtag"] = ercpf.GatewayManagerEtag - } - if ercpf.GlobalReachEnabled != nil { - objectMap["globalReachEnabled"] = ercpf.GlobalReachEnabled - } - if ercpf.AuthorizationKey != nil { - objectMap["authorizationKey"] = ercpf.AuthorizationKey - } - return json.Marshal(objectMap) -} - -// ExpressRouteCircuitReference reference to an express route circuit. -type ExpressRouteCircuitReference struct { - // ID - Corresponding Express Route Circuit Id. - ID *string `json:"id,omitempty"` -} - -// ExpressRouteCircuitRoutesTable the routes table associated with the ExpressRouteCircuit. -type ExpressRouteCircuitRoutesTable struct { - // NetworkProperty - IP address of a network entity. - NetworkProperty *string `json:"network,omitempty"` - // NextHop - NextHop address. - NextHop *string `json:"nextHop,omitempty"` - // LocPrf - Local preference value as set with the set local-preference route-map configuration command. - LocPrf *string `json:"locPrf,omitempty"` - // Weight - Route Weight. - Weight *int32 `json:"weight,omitempty"` - // Path - Autonomous system paths to the destination network. - Path *string `json:"path,omitempty"` -} - -// ExpressRouteCircuitRoutesTableSummary the routes table associated with the ExpressRouteCircuit. -type ExpressRouteCircuitRoutesTableSummary struct { - // Neighbor - IP address of the neighbor. - Neighbor *string `json:"neighbor,omitempty"` - // V - BGP version number spoken to the neighbor. - V *int32 `json:"v,omitempty"` - // As - Autonomous system number. - As *int32 `json:"as,omitempty"` - // UpDown - The length of time that the BGP session has been in the Established state, or the current status if not in the Established state. - UpDown *string `json:"upDown,omitempty"` - // StatePfxRcd - Current state of the BGP session, and the number of prefixes that have been received from a neighbor or peer group. - StatePfxRcd *string `json:"statePfxRcd,omitempty"` -} - -// ExpressRouteCircuitsArpTableListResult response for ListArpTable associated with the Express Route -// Circuits API. -type ExpressRouteCircuitsArpTableListResult struct { - autorest.Response `json:"-"` - // Value - A list of the ARP tables. - Value *[]ExpressRouteCircuitArpTable `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteCircuitsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteCircuitsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitsClient) (ExpressRouteCircuit, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitsCreateOrUpdateFuture.Result. -func (future *ExpressRouteCircuitsCreateOrUpdateFuture) result(client ExpressRouteCircuitsClient) (erc ExpressRouteCircuit, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erc.Response.Response, err = future.GetResult(sender); err == nil && erc.Response.Response.StatusCode != http.StatusNoContent { - erc, err = client.CreateOrUpdateResponder(erc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsCreateOrUpdateFuture", "Result", erc.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteCircuitsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitsDeleteFuture.Result. -func (future *ExpressRouteCircuitsDeleteFuture) result(client ExpressRouteCircuitsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteCircuitServiceProviderProperties contains ServiceProviderProperties in an -// ExpressRouteCircuit. -type ExpressRouteCircuitServiceProviderProperties struct { - // ServiceProviderName - The serviceProviderName. - ServiceProviderName *string `json:"serviceProviderName,omitempty"` - // PeeringLocation - The peering location. - PeeringLocation *string `json:"peeringLocation,omitempty"` - // BandwidthInMbps - The BandwidthInMbps. - BandwidthInMbps *int32 `json:"bandwidthInMbps,omitempty"` -} - -// ExpressRouteCircuitSku contains SKU in an ExpressRouteCircuit. -type ExpressRouteCircuitSku struct { - // Name - The name of the SKU. - Name *string `json:"name,omitempty"` - // Tier - The tier of the SKU. Possible values include: 'ExpressRouteCircuitSkuTierStandard', 'ExpressRouteCircuitSkuTierPremium', 'ExpressRouteCircuitSkuTierBasic', 'ExpressRouteCircuitSkuTierLocal' - Tier ExpressRouteCircuitSkuTier `json:"tier,omitempty"` - // Family - The family of the SKU. Possible values include: 'UnlimitedData', 'MeteredData' - Family ExpressRouteCircuitSkuFamily `json:"family,omitempty"` -} - -// ExpressRouteCircuitsListArpTableFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteCircuitsListArpTableFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitsClient) (ExpressRouteCircuitsArpTableListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitsListArpTableFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitsListArpTableFuture.Result. -func (future *ExpressRouteCircuitsListArpTableFuture) result(client ExpressRouteCircuitsClient) (ercatlr ExpressRouteCircuitsArpTableListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsListArpTableFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercatlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitsListArpTableFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercatlr.Response.Response, err = future.GetResult(sender); err == nil && ercatlr.Response.Response.StatusCode != http.StatusNoContent { - ercatlr, err = client.ListArpTableResponder(ercatlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsListArpTableFuture", "Result", ercatlr.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitsListRoutesTableFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteCircuitsListRoutesTableFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitsClient) (ExpressRouteCircuitsRoutesTableListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitsListRoutesTableFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitsListRoutesTableFuture.Result. -func (future *ExpressRouteCircuitsListRoutesTableFuture) result(client ExpressRouteCircuitsClient) (ercrtlr ExpressRouteCircuitsRoutesTableListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsListRoutesTableFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercrtlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitsListRoutesTableFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercrtlr.Response.Response, err = future.GetResult(sender); err == nil && ercrtlr.Response.Response.StatusCode != http.StatusNoContent { - ercrtlr, err = client.ListRoutesTableResponder(ercrtlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsListRoutesTableFuture", "Result", ercrtlr.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitsListRoutesTableSummaryFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ExpressRouteCircuitsListRoutesTableSummaryFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCircuitsClient) (ExpressRouteCircuitsRoutesTableSummaryListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCircuitsListRoutesTableSummaryFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCircuitsListRoutesTableSummaryFuture.Result. -func (future *ExpressRouteCircuitsListRoutesTableSummaryFuture) result(client ExpressRouteCircuitsClient) (ercrtslr ExpressRouteCircuitsRoutesTableSummaryListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsListRoutesTableSummaryFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercrtslr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCircuitsListRoutesTableSummaryFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercrtslr.Response.Response, err = future.GetResult(sender); err == nil && ercrtslr.Response.Response.StatusCode != http.StatusNoContent { - ercrtslr, err = client.ListRoutesTableSummaryResponder(ercrtslr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsListRoutesTableSummaryFuture", "Result", ercrtslr.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCircuitsRoutesTableListResult response for ListRoutesTable associated with the Express Route -// Circuits API. -type ExpressRouteCircuitsRoutesTableListResult struct { - autorest.Response `json:"-"` - // Value - The list of routes table. - Value *[]ExpressRouteCircuitRoutesTable `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteCircuitsRoutesTableSummaryListResult response for ListRoutesTable associated with the -// Express Route Circuits API. -type ExpressRouteCircuitsRoutesTableSummaryListResult struct { - autorest.Response `json:"-"` - // Value - A list of the routes table. - Value *[]ExpressRouteCircuitRoutesTableSummary `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteCircuitStats contains stats associated with the peering. -type ExpressRouteCircuitStats struct { - autorest.Response `json:"-"` - // PrimarybytesIn - The Primary BytesIn of the peering. - PrimarybytesIn *int64 `json:"primarybytesIn,omitempty"` - // PrimarybytesOut - The primary BytesOut of the peering. - PrimarybytesOut *int64 `json:"primarybytesOut,omitempty"` - // SecondarybytesIn - The secondary BytesIn of the peering. - SecondarybytesIn *int64 `json:"secondarybytesIn,omitempty"` - // SecondarybytesOut - The secondary BytesOut of the peering. - SecondarybytesOut *int64 `json:"secondarybytesOut,omitempty"` -} - -// ExpressRouteConnection expressRouteConnection resource. -type ExpressRouteConnection struct { - autorest.Response `json:"-"` - // ExpressRouteConnectionProperties - Properties of the express route connection. - *ExpressRouteConnectionProperties `json:"properties,omitempty"` - // Name - The name of the resource. - Name *string `json:"name,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteConnection. -func (erc ExpressRouteConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erc.ExpressRouteConnectionProperties != nil { - objectMap["properties"] = erc.ExpressRouteConnectionProperties - } - if erc.Name != nil { - objectMap["name"] = erc.Name - } - if erc.ID != nil { - objectMap["id"] = erc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteConnection struct. -func (erc *ExpressRouteConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteConnectionProperties ExpressRouteConnectionProperties - err = json.Unmarshal(*v, &expressRouteConnectionProperties) - if err != nil { - return err - } - erc.ExpressRouteConnectionProperties = &expressRouteConnectionProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erc.Name = &name - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erc.ID = &ID - } - } - } - - return nil -} - -// ExpressRouteConnectionID the ID of the ExpressRouteConnection. -type ExpressRouteConnectionID struct { - // ID - READ-ONLY; The ID of the ExpressRouteConnection. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteConnectionID. -func (erci ExpressRouteConnectionID) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ExpressRouteConnectionList expressRouteConnection list. -type ExpressRouteConnectionList struct { - autorest.Response `json:"-"` - // Value - The list of ExpressRoute connections. - Value *[]ExpressRouteConnection `json:"value,omitempty"` -} - -// ExpressRouteConnectionProperties properties of the ExpressRouteConnection subresource. -type ExpressRouteConnectionProperties struct { - // ProvisioningState - READ-ONLY; The provisioning state of the express route connection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ExpressRouteCircuitPeering - The ExpressRoute circuit peering. - ExpressRouteCircuitPeering *ExpressRouteCircuitPeeringID `json:"expressRouteCircuitPeering,omitempty"` - // AuthorizationKey - Authorization key to establish the connection. - AuthorizationKey *string `json:"authorizationKey,omitempty"` - // RoutingWeight - The routing weight associated to the connection. - RoutingWeight *int32 `json:"routingWeight,omitempty"` - // EnableInternetSecurity - Enable internet security. - EnableInternetSecurity *bool `json:"enableInternetSecurity,omitempty"` - // ExpressRouteGatewayBypass - Enable FastPath to vWan Firewall hub. - ExpressRouteGatewayBypass *bool `json:"expressRouteGatewayBypass,omitempty"` - // EnablePrivateLinkFastPath - Bypass the ExpressRoute gateway when accessing private-links. ExpressRoute FastPath (expressRouteGatewayBypass) must be enabled. - EnablePrivateLinkFastPath *bool `json:"enablePrivateLinkFastPath,omitempty"` - // RoutingConfiguration - The Routing Configuration indicating the associated and propagated route tables on this connection. - RoutingConfiguration *RoutingConfiguration `json:"routingConfiguration,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteConnectionProperties. -func (ercp ExpressRouteConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercp.ExpressRouteCircuitPeering != nil { - objectMap["expressRouteCircuitPeering"] = ercp.ExpressRouteCircuitPeering - } - if ercp.AuthorizationKey != nil { - objectMap["authorizationKey"] = ercp.AuthorizationKey - } - if ercp.RoutingWeight != nil { - objectMap["routingWeight"] = ercp.RoutingWeight - } - if ercp.EnableInternetSecurity != nil { - objectMap["enableInternetSecurity"] = ercp.EnableInternetSecurity - } - if ercp.ExpressRouteGatewayBypass != nil { - objectMap["expressRouteGatewayBypass"] = ercp.ExpressRouteGatewayBypass - } - if ercp.EnablePrivateLinkFastPath != nil { - objectMap["enablePrivateLinkFastPath"] = ercp.EnablePrivateLinkFastPath - } - if ercp.RoutingConfiguration != nil { - objectMap["routingConfiguration"] = ercp.RoutingConfiguration - } - return json.Marshal(objectMap) -} - -// ExpressRouteConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type ExpressRouteConnectionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteConnectionsClient) (ExpressRouteConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteConnectionsCreateOrUpdateFuture.Result. -func (future *ExpressRouteConnectionsCreateOrUpdateFuture) result(client ExpressRouteConnectionsClient) (erc ExpressRouteConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteConnectionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erc.Response.Response, err = future.GetResult(sender); err == nil && erc.Response.Response.StatusCode != http.StatusNoContent { - erc, err = client.CreateOrUpdateResponder(erc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsCreateOrUpdateFuture", "Result", erc.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteConnectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteConnectionsDeleteFuture.Result. -func (future *ExpressRouteConnectionsDeleteFuture) result(client ExpressRouteConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteConnectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteCrossConnection expressRouteCrossConnection resource. -type ExpressRouteCrossConnection struct { - autorest.Response `json:"-"` - // ExpressRouteCrossConnectionProperties - Properties of the express route cross connection. - *ExpressRouteCrossConnectionProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnection. -func (ercc ExpressRouteCrossConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercc.ExpressRouteCrossConnectionProperties != nil { - objectMap["properties"] = ercc.ExpressRouteCrossConnectionProperties - } - if ercc.ID != nil { - objectMap["id"] = ercc.ID - } - if ercc.Location != nil { - objectMap["location"] = ercc.Location - } - if ercc.Tags != nil { - objectMap["tags"] = ercc.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteCrossConnection struct. -func (ercc *ExpressRouteCrossConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteCrossConnectionProperties ExpressRouteCrossConnectionProperties - err = json.Unmarshal(*v, &expressRouteCrossConnectionProperties) - if err != nil { - return err - } - ercc.ExpressRouteCrossConnectionProperties = &expressRouteCrossConnectionProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ercc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ercc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ercc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ercc.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ercc.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - ercc.Tags = tags - } - } - } - - return nil -} - -// ExpressRouteCrossConnectionListResult response for ListExpressRouteCrossConnection API service call. -type ExpressRouteCrossConnectionListResult struct { - autorest.Response `json:"-"` - // Value - A list of ExpressRouteCrossConnection resources. - Value *[]ExpressRouteCrossConnection `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnectionListResult. -func (ercclr ExpressRouteCrossConnectionListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ercclr.Value != nil { - objectMap["value"] = ercclr.Value - } - return json.Marshal(objectMap) -} - -// ExpressRouteCrossConnectionListResultIterator provides access to a complete listing of -// ExpressRouteCrossConnection values. -type ExpressRouteCrossConnectionListResultIterator struct { - i int - page ExpressRouteCrossConnectionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteCrossConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteCrossConnectionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteCrossConnectionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteCrossConnectionListResultIterator) Response() ExpressRouteCrossConnectionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteCrossConnectionListResultIterator) Value() ExpressRouteCrossConnection { - if !iter.page.NotDone() { - return ExpressRouteCrossConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteCrossConnectionListResultIterator type. -func NewExpressRouteCrossConnectionListResultIterator(page ExpressRouteCrossConnectionListResultPage) ExpressRouteCrossConnectionListResultIterator { - return ExpressRouteCrossConnectionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ercclr ExpressRouteCrossConnectionListResult) IsEmpty() bool { - return ercclr.Value == nil || len(*ercclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ercclr ExpressRouteCrossConnectionListResult) hasNextLink() bool { - return ercclr.NextLink != nil && len(*ercclr.NextLink) != 0 -} - -// expressRouteCrossConnectionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ercclr ExpressRouteCrossConnectionListResult) expressRouteCrossConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ercclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ercclr.NextLink))) -} - -// ExpressRouteCrossConnectionListResultPage contains a page of ExpressRouteCrossConnection values. -type ExpressRouteCrossConnectionListResultPage struct { - fn func(context.Context, ExpressRouteCrossConnectionListResult) (ExpressRouteCrossConnectionListResult, error) - ercclr ExpressRouteCrossConnectionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteCrossConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ercclr) - if err != nil { - return err - } - page.ercclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteCrossConnectionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteCrossConnectionListResultPage) NotDone() bool { - return !page.ercclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteCrossConnectionListResultPage) Response() ExpressRouteCrossConnectionListResult { - return page.ercclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteCrossConnectionListResultPage) Values() []ExpressRouteCrossConnection { - if page.ercclr.IsEmpty() { - return nil - } - return *page.ercclr.Value -} - -// Creates a new instance of the ExpressRouteCrossConnectionListResultPage type. -func NewExpressRouteCrossConnectionListResultPage(cur ExpressRouteCrossConnectionListResult, getNextPage func(context.Context, ExpressRouteCrossConnectionListResult) (ExpressRouteCrossConnectionListResult, error)) ExpressRouteCrossConnectionListResultPage { - return ExpressRouteCrossConnectionListResultPage{ - fn: getNextPage, - ercclr: cur, - } -} - -// ExpressRouteCrossConnectionPeering peering in an ExpressRoute Cross Connection resource. -type ExpressRouteCrossConnectionPeering struct { - autorest.Response `json:"-"` - // ExpressRouteCrossConnectionPeeringProperties - Properties of the express route cross connection peering. - *ExpressRouteCrossConnectionPeeringProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnectionPeering. -func (erccp ExpressRouteCrossConnectionPeering) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erccp.ExpressRouteCrossConnectionPeeringProperties != nil { - objectMap["properties"] = erccp.ExpressRouteCrossConnectionPeeringProperties - } - if erccp.Name != nil { - objectMap["name"] = erccp.Name - } - if erccp.ID != nil { - objectMap["id"] = erccp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteCrossConnectionPeering struct. -func (erccp *ExpressRouteCrossConnectionPeering) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteCrossConnectionPeeringProperties ExpressRouteCrossConnectionPeeringProperties - err = json.Unmarshal(*v, &expressRouteCrossConnectionPeeringProperties) - if err != nil { - return err - } - erccp.ExpressRouteCrossConnectionPeeringProperties = &expressRouteCrossConnectionPeeringProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erccp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erccp.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erccp.ID = &ID - } - } - } - - return nil -} - -// ExpressRouteCrossConnectionPeeringList response for ListPeering API service call retrieves all peerings -// that belong to an ExpressRouteCrossConnection. -type ExpressRouteCrossConnectionPeeringList struct { - autorest.Response `json:"-"` - // Value - The peerings in an express route cross connection. - Value *[]ExpressRouteCrossConnectionPeering `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnectionPeeringList. -func (erccpl ExpressRouteCrossConnectionPeeringList) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erccpl.Value != nil { - objectMap["value"] = erccpl.Value - } - return json.Marshal(objectMap) -} - -// ExpressRouteCrossConnectionPeeringListIterator provides access to a complete listing of -// ExpressRouteCrossConnectionPeering values. -type ExpressRouteCrossConnectionPeeringListIterator struct { - i int - page ExpressRouteCrossConnectionPeeringListPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteCrossConnectionPeeringListIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringListIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteCrossConnectionPeeringListIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteCrossConnectionPeeringListIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteCrossConnectionPeeringListIterator) Response() ExpressRouteCrossConnectionPeeringList { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteCrossConnectionPeeringListIterator) Value() ExpressRouteCrossConnectionPeering { - if !iter.page.NotDone() { - return ExpressRouteCrossConnectionPeering{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteCrossConnectionPeeringListIterator type. -func NewExpressRouteCrossConnectionPeeringListIterator(page ExpressRouteCrossConnectionPeeringListPage) ExpressRouteCrossConnectionPeeringListIterator { - return ExpressRouteCrossConnectionPeeringListIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (erccpl ExpressRouteCrossConnectionPeeringList) IsEmpty() bool { - return erccpl.Value == nil || len(*erccpl.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (erccpl ExpressRouteCrossConnectionPeeringList) hasNextLink() bool { - return erccpl.NextLink != nil && len(*erccpl.NextLink) != 0 -} - -// expressRouteCrossConnectionPeeringListPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (erccpl ExpressRouteCrossConnectionPeeringList) expressRouteCrossConnectionPeeringListPreparer(ctx context.Context) (*http.Request, error) { - if !erccpl.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(erccpl.NextLink))) -} - -// ExpressRouteCrossConnectionPeeringListPage contains a page of ExpressRouteCrossConnectionPeering values. -type ExpressRouteCrossConnectionPeeringListPage struct { - fn func(context.Context, ExpressRouteCrossConnectionPeeringList) (ExpressRouteCrossConnectionPeeringList, error) - erccpl ExpressRouteCrossConnectionPeeringList -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteCrossConnectionPeeringListPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteCrossConnectionPeeringListPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.erccpl) - if err != nil { - return err - } - page.erccpl = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteCrossConnectionPeeringListPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteCrossConnectionPeeringListPage) NotDone() bool { - return !page.erccpl.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteCrossConnectionPeeringListPage) Response() ExpressRouteCrossConnectionPeeringList { - return page.erccpl -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteCrossConnectionPeeringListPage) Values() []ExpressRouteCrossConnectionPeering { - if page.erccpl.IsEmpty() { - return nil - } - return *page.erccpl.Value -} - -// Creates a new instance of the ExpressRouteCrossConnectionPeeringListPage type. -func NewExpressRouteCrossConnectionPeeringListPage(cur ExpressRouteCrossConnectionPeeringList, getNextPage func(context.Context, ExpressRouteCrossConnectionPeeringList) (ExpressRouteCrossConnectionPeeringList, error)) ExpressRouteCrossConnectionPeeringListPage { - return ExpressRouteCrossConnectionPeeringListPage{ - fn: getNextPage, - erccpl: cur, - } -} - -// ExpressRouteCrossConnectionPeeringProperties properties of express route cross connection peering. -type ExpressRouteCrossConnectionPeeringProperties struct { - // PeeringType - The peering type. Possible values include: 'AzurePublicPeering', 'AzurePrivatePeering', 'MicrosoftPeering' - PeeringType ExpressRoutePeeringType `json:"peeringType,omitempty"` - // State - The peering state. Possible values include: 'ExpressRoutePeeringStateDisabled', 'ExpressRoutePeeringStateEnabled' - State ExpressRoutePeeringState `json:"state,omitempty"` - // AzureASN - READ-ONLY; The Azure ASN. - AzureASN *int32 `json:"azureASN,omitempty"` - // PeerASN - The peer ASN. - PeerASN *int64 `json:"peerASN,omitempty"` - // PrimaryPeerAddressPrefix - The primary address prefix. - PrimaryPeerAddressPrefix *string `json:"primaryPeerAddressPrefix,omitempty"` - // SecondaryPeerAddressPrefix - The secondary address prefix. - SecondaryPeerAddressPrefix *string `json:"secondaryPeerAddressPrefix,omitempty"` - // PrimaryAzurePort - READ-ONLY; The primary port. - PrimaryAzurePort *string `json:"primaryAzurePort,omitempty"` - // SecondaryAzurePort - READ-ONLY; The secondary port. - SecondaryAzurePort *string `json:"secondaryAzurePort,omitempty"` - // SharedKey - The shared key. - SharedKey *string `json:"sharedKey,omitempty"` - // VlanID - The VLAN ID. - VlanID *int32 `json:"vlanId,omitempty"` - // MicrosoftPeeringConfig - The Microsoft peering configuration. - MicrosoftPeeringConfig *ExpressRouteCircuitPeeringConfig `json:"microsoftPeeringConfig,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the express route cross connection peering resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // GatewayManagerEtag - The GatewayManager Etag. - GatewayManagerEtag *string `json:"gatewayManagerEtag,omitempty"` - // LastModifiedBy - READ-ONLY; Who was the last to modify the peering. - LastModifiedBy *string `json:"lastModifiedBy,omitempty"` - // Ipv6PeeringConfig - The IPv6 peering configuration. - Ipv6PeeringConfig *Ipv6ExpressRouteCircuitPeeringConfig `json:"ipv6PeeringConfig,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnectionPeeringProperties. -func (erccpp ExpressRouteCrossConnectionPeeringProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erccpp.PeeringType != "" { - objectMap["peeringType"] = erccpp.PeeringType - } - if erccpp.State != "" { - objectMap["state"] = erccpp.State - } - if erccpp.PeerASN != nil { - objectMap["peerASN"] = erccpp.PeerASN - } - if erccpp.PrimaryPeerAddressPrefix != nil { - objectMap["primaryPeerAddressPrefix"] = erccpp.PrimaryPeerAddressPrefix - } - if erccpp.SecondaryPeerAddressPrefix != nil { - objectMap["secondaryPeerAddressPrefix"] = erccpp.SecondaryPeerAddressPrefix - } - if erccpp.SharedKey != nil { - objectMap["sharedKey"] = erccpp.SharedKey - } - if erccpp.VlanID != nil { - objectMap["vlanId"] = erccpp.VlanID - } - if erccpp.MicrosoftPeeringConfig != nil { - objectMap["microsoftPeeringConfig"] = erccpp.MicrosoftPeeringConfig - } - if erccpp.GatewayManagerEtag != nil { - objectMap["gatewayManagerEtag"] = erccpp.GatewayManagerEtag - } - if erccpp.Ipv6PeeringConfig != nil { - objectMap["ipv6PeeringConfig"] = erccpp.Ipv6PeeringConfig - } - return json.Marshal(objectMap) -} - -// ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCrossConnectionPeeringsClient) (ExpressRouteCrossConnectionPeering, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture.Result. -func (future *ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture) result(client ExpressRouteCrossConnectionPeeringsClient) (erccp ExpressRouteCrossConnectionPeering, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erccp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erccp.Response.Response, err = future.GetResult(sender); err == nil && erccp.Response.Response.StatusCode != http.StatusNoContent { - erccp, err = client.CreateOrUpdateResponder(erccp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsCreateOrUpdateFuture", "Result", erccp.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCrossConnectionPeeringsDeleteFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type ExpressRouteCrossConnectionPeeringsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCrossConnectionPeeringsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCrossConnectionPeeringsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCrossConnectionPeeringsDeleteFuture.Result. -func (future *ExpressRouteCrossConnectionPeeringsDeleteFuture) result(client ExpressRouteCrossConnectionPeeringsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionPeeringsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCrossConnectionPeeringsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteCrossConnectionProperties properties of ExpressRouteCrossConnection. -type ExpressRouteCrossConnectionProperties struct { - // PrimaryAzurePort - READ-ONLY; The name of the primary port. - PrimaryAzurePort *string `json:"primaryAzurePort,omitempty"` - // SecondaryAzurePort - READ-ONLY; The name of the secondary port. - SecondaryAzurePort *string `json:"secondaryAzurePort,omitempty"` - // STag - READ-ONLY; The identifier of the circuit traffic. - STag *int32 `json:"sTag,omitempty"` - // PeeringLocation - READ-ONLY; The peering location of the ExpressRoute circuit. - PeeringLocation *string `json:"peeringLocation,omitempty"` - // BandwidthInMbps - READ-ONLY; The circuit bandwidth In Mbps. - BandwidthInMbps *int32 `json:"bandwidthInMbps,omitempty"` - // ExpressRouteCircuit - The ExpressRouteCircuit. - ExpressRouteCircuit *ExpressRouteCircuitReference `json:"expressRouteCircuit,omitempty"` - // ServiceProviderProvisioningState - The provisioning state of the circuit in the connectivity provider system. Possible values include: 'ServiceProviderProvisioningStateNotProvisioned', 'ServiceProviderProvisioningStateProvisioning', 'ServiceProviderProvisioningStateProvisioned', 'ServiceProviderProvisioningStateDeprovisioning' - ServiceProviderProvisioningState ServiceProviderProvisioningState `json:"serviceProviderProvisioningState,omitempty"` - // ServiceProviderNotes - Additional read only notes set by the connectivity provider. - ServiceProviderNotes *string `json:"serviceProviderNotes,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the express route cross connection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // Peerings - The list of peerings. - Peerings *[]ExpressRouteCrossConnectionPeering `json:"peerings,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnectionProperties. -func (erccp ExpressRouteCrossConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erccp.ExpressRouteCircuit != nil { - objectMap["expressRouteCircuit"] = erccp.ExpressRouteCircuit - } - if erccp.ServiceProviderProvisioningState != "" { - objectMap["serviceProviderProvisioningState"] = erccp.ServiceProviderProvisioningState - } - if erccp.ServiceProviderNotes != nil { - objectMap["serviceProviderNotes"] = erccp.ServiceProviderNotes - } - if erccp.Peerings != nil { - objectMap["peerings"] = erccp.Peerings - } - return json.Marshal(objectMap) -} - -// ExpressRouteCrossConnectionRoutesTableSummary the routes table associated with the ExpressRouteCircuit. -type ExpressRouteCrossConnectionRoutesTableSummary struct { - // Neighbor - IP address of Neighbor router. - Neighbor *string `json:"neighbor,omitempty"` - // Asn - Autonomous system number. - Asn *int32 `json:"asn,omitempty"` - // UpDown - The length of time that the BGP session has been in the Established state, or the current status if not in the Established state. - UpDown *string `json:"upDown,omitempty"` - // StateOrPrefixesReceived - Current state of the BGP session, and the number of prefixes that have been received from a neighbor or peer group. - StateOrPrefixesReceived *string `json:"stateOrPrefixesReceived,omitempty"` -} - -// ExpressRouteCrossConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ExpressRouteCrossConnectionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCrossConnectionsClient) (ExpressRouteCrossConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCrossConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCrossConnectionsCreateOrUpdateFuture.Result. -func (future *ExpressRouteCrossConnectionsCreateOrUpdateFuture) result(client ExpressRouteCrossConnectionsClient) (ercc ExpressRouteCrossConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCrossConnectionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercc.Response.Response, err = future.GetResult(sender); err == nil && ercc.Response.Response.StatusCode != http.StatusNoContent { - ercc, err = client.CreateOrUpdateResponder(ercc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsCreateOrUpdateFuture", "Result", ercc.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCrossConnectionsListArpTableFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type ExpressRouteCrossConnectionsListArpTableFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCrossConnectionsClient) (ExpressRouteCircuitsArpTableListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCrossConnectionsListArpTableFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCrossConnectionsListArpTableFuture.Result. -func (future *ExpressRouteCrossConnectionsListArpTableFuture) result(client ExpressRouteCrossConnectionsClient) (ercatlr ExpressRouteCircuitsArpTableListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsListArpTableFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercatlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCrossConnectionsListArpTableFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercatlr.Response.Response, err = future.GetResult(sender); err == nil && ercatlr.Response.Response.StatusCode != http.StatusNoContent { - ercatlr, err = client.ListArpTableResponder(ercatlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsListArpTableFuture", "Result", ercatlr.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCrossConnectionsListRoutesTableFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ExpressRouteCrossConnectionsListRoutesTableFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCrossConnectionsClient) (ExpressRouteCircuitsRoutesTableListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCrossConnectionsListRoutesTableFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCrossConnectionsListRoutesTableFuture.Result. -func (future *ExpressRouteCrossConnectionsListRoutesTableFuture) result(client ExpressRouteCrossConnectionsClient) (ercrtlr ExpressRouteCircuitsRoutesTableListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsListRoutesTableFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ercrtlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCrossConnectionsListRoutesTableFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ercrtlr.Response.Response, err = future.GetResult(sender); err == nil && ercrtlr.Response.Response.StatusCode != http.StatusNoContent { - ercrtlr, err = client.ListRoutesTableResponder(ercrtlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsListRoutesTableFuture", "Result", ercrtlr.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCrossConnectionsListRoutesTableSummaryFuture an abstraction for monitoring and retrieving -// the results of a long-running operation. -type ExpressRouteCrossConnectionsListRoutesTableSummaryFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteCrossConnectionsClient) (ExpressRouteCrossConnectionsRoutesTableSummaryListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteCrossConnectionsListRoutesTableSummaryFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteCrossConnectionsListRoutesTableSummaryFuture.Result. -func (future *ExpressRouteCrossConnectionsListRoutesTableSummaryFuture) result(client ExpressRouteCrossConnectionsClient) (erccrtslr ExpressRouteCrossConnectionsRoutesTableSummaryListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsListRoutesTableSummaryFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erccrtslr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteCrossConnectionsListRoutesTableSummaryFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erccrtslr.Response.Response, err = future.GetResult(sender); err == nil && erccrtslr.Response.Response.StatusCode != http.StatusNoContent { - erccrtslr, err = client.ListRoutesTableSummaryResponder(erccrtslr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCrossConnectionsListRoutesTableSummaryFuture", "Result", erccrtslr.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteCrossConnectionsRoutesTableSummaryListResult response for ListRoutesTable associated with -// the Express Route Cross Connections. -type ExpressRouteCrossConnectionsRoutesTableSummaryListResult struct { - autorest.Response `json:"-"` - // Value - A list of the routes table. - Value *[]ExpressRouteCrossConnectionRoutesTableSummary `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteCrossConnectionsRoutesTableSummaryListResult. -func (erccrtslr ExpressRouteCrossConnectionsRoutesTableSummaryListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erccrtslr.Value != nil { - objectMap["value"] = erccrtslr.Value - } - return json.Marshal(objectMap) -} - -// ExpressRouteGateway expressRoute gateway resource. -type ExpressRouteGateway struct { - autorest.Response `json:"-"` - // ExpressRouteGatewayProperties - Properties of the express route gateway. - *ExpressRouteGatewayProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteGateway. -func (erg ExpressRouteGateway) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erg.ExpressRouteGatewayProperties != nil { - objectMap["properties"] = erg.ExpressRouteGatewayProperties - } - if erg.ID != nil { - objectMap["id"] = erg.ID - } - if erg.Location != nil { - objectMap["location"] = erg.Location - } - if erg.Tags != nil { - objectMap["tags"] = erg.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteGateway struct. -func (erg *ExpressRouteGateway) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteGatewayProperties ExpressRouteGatewayProperties - err = json.Unmarshal(*v, &expressRouteGatewayProperties) - if err != nil { - return err - } - erg.ExpressRouteGatewayProperties = &expressRouteGatewayProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erg.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erg.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - erg.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - erg.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - erg.Tags = tags - } - } - } - - return nil -} - -// ExpressRouteGatewayList list of ExpressRoute gateways. -type ExpressRouteGatewayList struct { - autorest.Response `json:"-"` - // Value - List of ExpressRoute gateways. - Value *[]ExpressRouteGateway `json:"value,omitempty"` -} - -// ExpressRouteGatewayProperties expressRoute gateway resource properties. -type ExpressRouteGatewayProperties struct { - // AutoScaleConfiguration - Configuration for auto scaling. - AutoScaleConfiguration *ExpressRouteGatewayPropertiesAutoScaleConfiguration `json:"autoScaleConfiguration,omitempty"` - // ExpressRouteConnections - List of ExpressRoute connections to the ExpressRoute gateway. - ExpressRouteConnections *[]ExpressRouteConnection `json:"expressRouteConnections,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the express route gateway resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // VirtualHub - The Virtual Hub where the ExpressRoute gateway is or will be deployed. - VirtualHub *VirtualHubID `json:"virtualHub,omitempty"` - // AllowNonVirtualWanTraffic - Configures this gateway to accept traffic from non Virtual WAN networks. - AllowNonVirtualWanTraffic *bool `json:"allowNonVirtualWanTraffic,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteGatewayProperties. -func (ergp ExpressRouteGatewayProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ergp.AutoScaleConfiguration != nil { - objectMap["autoScaleConfiguration"] = ergp.AutoScaleConfiguration - } - if ergp.ExpressRouteConnections != nil { - objectMap["expressRouteConnections"] = ergp.ExpressRouteConnections - } - if ergp.VirtualHub != nil { - objectMap["virtualHub"] = ergp.VirtualHub - } - if ergp.AllowNonVirtualWanTraffic != nil { - objectMap["allowNonVirtualWanTraffic"] = ergp.AllowNonVirtualWanTraffic - } - return json.Marshal(objectMap) -} - -// ExpressRouteGatewayPropertiesAutoScaleConfiguration configuration for auto scaling. -type ExpressRouteGatewayPropertiesAutoScaleConfiguration struct { - // Bounds - Minimum and maximum number of scale units to deploy. - Bounds *ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds `json:"bounds,omitempty"` -} - -// ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds minimum and maximum number of scale units to -// deploy. -type ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds struct { - // Min - Minimum number of scale units deployed for ExpressRoute gateway. - Min *int32 `json:"min,omitempty"` - // Max - Maximum number of scale units deployed for ExpressRoute gateway. - Max *int32 `json:"max,omitempty"` -} - -// ExpressRouteGatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteGatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteGatewaysClient) (ExpressRouteGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteGatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteGatewaysCreateOrUpdateFuture.Result. -func (future *ExpressRouteGatewaysCreateOrUpdateFuture) result(client ExpressRouteGatewaysClient) (erg ExpressRouteGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteGatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erg.Response.Response, err = future.GetResult(sender); err == nil && erg.Response.Response.StatusCode != http.StatusNoContent { - erg, err = client.CreateOrUpdateResponder(erg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysCreateOrUpdateFuture", "Result", erg.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteGatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteGatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteGatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteGatewaysDeleteFuture.Result. -func (future *ExpressRouteGatewaysDeleteFuture) result(client ExpressRouteGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteGatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRouteGatewaysUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRouteGatewaysUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRouteGatewaysClient) (ExpressRouteGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRouteGatewaysUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRouteGatewaysUpdateTagsFuture.Result. -func (future *ExpressRouteGatewaysUpdateTagsFuture) result(client ExpressRouteGatewaysClient) (erg ExpressRouteGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRouteGatewaysUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erg.Response.Response, err = future.GetResult(sender); err == nil && erg.Response.Response.StatusCode != http.StatusNoContent { - erg, err = client.UpdateTagsResponder(erg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteGatewaysUpdateTagsFuture", "Result", erg.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRouteLink expressRouteLink child resource definition. -type ExpressRouteLink struct { - autorest.Response `json:"-"` - // ExpressRouteLinkPropertiesFormat - ExpressRouteLink properties. - *ExpressRouteLinkPropertiesFormat `json:"properties,omitempty"` - // Name - Name of child port resource that is unique among child port resources of the parent. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteLink. -func (erl ExpressRouteLink) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erl.ExpressRouteLinkPropertiesFormat != nil { - objectMap["properties"] = erl.ExpressRouteLinkPropertiesFormat - } - if erl.Name != nil { - objectMap["name"] = erl.Name - } - if erl.ID != nil { - objectMap["id"] = erl.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteLink struct. -func (erl *ExpressRouteLink) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteLinkPropertiesFormat ExpressRouteLinkPropertiesFormat - err = json.Unmarshal(*v, &expressRouteLinkPropertiesFormat) - if err != nil { - return err - } - erl.ExpressRouteLinkPropertiesFormat = &expressRouteLinkPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erl.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erl.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erl.ID = &ID - } - } - } - - return nil -} - -// ExpressRouteLinkListResult response for ListExpressRouteLinks API service call. -type ExpressRouteLinkListResult struct { - autorest.Response `json:"-"` - // Value - The list of ExpressRouteLink sub-resources. - Value *[]ExpressRouteLink `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteLinkListResultIterator provides access to a complete listing of ExpressRouteLink values. -type ExpressRouteLinkListResultIterator struct { - i int - page ExpressRouteLinkListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteLinkListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteLinkListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteLinkListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteLinkListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteLinkListResultIterator) Response() ExpressRouteLinkListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteLinkListResultIterator) Value() ExpressRouteLink { - if !iter.page.NotDone() { - return ExpressRouteLink{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteLinkListResultIterator type. -func NewExpressRouteLinkListResultIterator(page ExpressRouteLinkListResultPage) ExpressRouteLinkListResultIterator { - return ExpressRouteLinkListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (erllr ExpressRouteLinkListResult) IsEmpty() bool { - return erllr.Value == nil || len(*erllr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (erllr ExpressRouteLinkListResult) hasNextLink() bool { - return erllr.NextLink != nil && len(*erllr.NextLink) != 0 -} - -// expressRouteLinkListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (erllr ExpressRouteLinkListResult) expressRouteLinkListResultPreparer(ctx context.Context) (*http.Request, error) { - if !erllr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(erllr.NextLink))) -} - -// ExpressRouteLinkListResultPage contains a page of ExpressRouteLink values. -type ExpressRouteLinkListResultPage struct { - fn func(context.Context, ExpressRouteLinkListResult) (ExpressRouteLinkListResult, error) - erllr ExpressRouteLinkListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteLinkListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteLinkListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.erllr) - if err != nil { - return err - } - page.erllr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteLinkListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteLinkListResultPage) NotDone() bool { - return !page.erllr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteLinkListResultPage) Response() ExpressRouteLinkListResult { - return page.erllr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteLinkListResultPage) Values() []ExpressRouteLink { - if page.erllr.IsEmpty() { - return nil - } - return *page.erllr.Value -} - -// Creates a new instance of the ExpressRouteLinkListResultPage type. -func NewExpressRouteLinkListResultPage(cur ExpressRouteLinkListResult, getNextPage func(context.Context, ExpressRouteLinkListResult) (ExpressRouteLinkListResult, error)) ExpressRouteLinkListResultPage { - return ExpressRouteLinkListResultPage{ - fn: getNextPage, - erllr: cur, - } -} - -// ExpressRouteLinkMacSecConfig expressRouteLink Mac Security Configuration. -type ExpressRouteLinkMacSecConfig struct { - // CknSecretIdentifier - Keyvault Secret Identifier URL containing Mac security CKN key. - CknSecretIdentifier *string `json:"cknSecretIdentifier,omitempty"` - // CakSecretIdentifier - Keyvault Secret Identifier URL containing Mac security CAK key. - CakSecretIdentifier *string `json:"cakSecretIdentifier,omitempty"` - // Cipher - Mac security cipher. Possible values include: 'GcmAes256', 'GcmAes128', 'GcmAesXpn128', 'GcmAesXpn256' - Cipher ExpressRouteLinkMacSecCipher `json:"cipher,omitempty"` - // SciState - Sci mode enabled/disabled. Possible values include: 'ExpressRouteLinkMacSecSciStateDisabled', 'ExpressRouteLinkMacSecSciStateEnabled' - SciState ExpressRouteLinkMacSecSciState `json:"sciState,omitempty"` -} - -// ExpressRouteLinkPropertiesFormat properties specific to ExpressRouteLink resources. -type ExpressRouteLinkPropertiesFormat struct { - // RouterName - READ-ONLY; Name of Azure router associated with physical port. - RouterName *string `json:"routerName,omitempty"` - // InterfaceName - READ-ONLY; Name of Azure router interface. - InterfaceName *string `json:"interfaceName,omitempty"` - // PatchPanelID - READ-ONLY; Mapping between physical port to patch panel port. - PatchPanelID *string `json:"patchPanelId,omitempty"` - // RackID - READ-ONLY; Mapping of physical patch panel to rack. - RackID *string `json:"rackId,omitempty"` - // ColoLocation - READ-ONLY; Cololocation for ExpressRoute Hybrid Direct. - ColoLocation *string `json:"coloLocation,omitempty"` - // ConnectorType - READ-ONLY; Physical fiber port type. Possible values include: 'LC', 'SC' - ConnectorType ExpressRouteLinkConnectorType `json:"connectorType,omitempty"` - // AdminState - Administrative state of the physical port. Possible values include: 'ExpressRouteLinkAdminStateEnabled', 'ExpressRouteLinkAdminStateDisabled' - AdminState ExpressRouteLinkAdminState `json:"adminState,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the express route link resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // MacSecConfig - MacSec configuration. - MacSecConfig *ExpressRouteLinkMacSecConfig `json:"macSecConfig,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteLinkPropertiesFormat. -func (erlpf ExpressRouteLinkPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erlpf.AdminState != "" { - objectMap["adminState"] = erlpf.AdminState - } - if erlpf.MacSecConfig != nil { - objectMap["macSecConfig"] = erlpf.MacSecConfig - } - return json.Marshal(objectMap) -} - -// ExpressRoutePort expressRoutePort resource definition. -type ExpressRoutePort struct { - autorest.Response `json:"-"` - // ExpressRoutePortPropertiesFormat - ExpressRoutePort properties. - *ExpressRoutePortPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Identity - The identity of ExpressRoutePort, if configured. - Identity *ManagedServiceIdentity `json:"identity,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ExpressRoutePort. -func (erp ExpressRoutePort) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erp.ExpressRoutePortPropertiesFormat != nil { - objectMap["properties"] = erp.ExpressRoutePortPropertiesFormat - } - if erp.Identity != nil { - objectMap["identity"] = erp.Identity - } - if erp.ID != nil { - objectMap["id"] = erp.ID - } - if erp.Location != nil { - objectMap["location"] = erp.Location - } - if erp.Tags != nil { - objectMap["tags"] = erp.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRoutePort struct. -func (erp *ExpressRoutePort) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRoutePortPropertiesFormat ExpressRoutePortPropertiesFormat - err = json.Unmarshal(*v, &expressRoutePortPropertiesFormat) - if err != nil { - return err - } - erp.ExpressRoutePortPropertiesFormat = &expressRoutePortPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erp.Etag = &etag - } - case "identity": - if v != nil { - var identity ManagedServiceIdentity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - erp.Identity = &identity - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - erp.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - erp.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - erp.Tags = tags - } - } - } - - return nil -} - -// ExpressRoutePortAuthorization expressRoutePort Authorization resource definition. -type ExpressRoutePortAuthorization struct { - autorest.Response `json:"-"` - // ExpressRoutePortAuthorizationPropertiesFormat - ExpressRoutePort properties. - *ExpressRoutePortAuthorizationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRoutePortAuthorization. -func (erpa ExpressRoutePortAuthorization) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erpa.ExpressRoutePortAuthorizationPropertiesFormat != nil { - objectMap["properties"] = erpa.ExpressRoutePortAuthorizationPropertiesFormat - } - if erpa.Name != nil { - objectMap["name"] = erpa.Name - } - if erpa.ID != nil { - objectMap["id"] = erpa.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRoutePortAuthorization struct. -func (erpa *ExpressRoutePortAuthorization) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRoutePortAuthorizationPropertiesFormat ExpressRoutePortAuthorizationPropertiesFormat - err = json.Unmarshal(*v, &expressRoutePortAuthorizationPropertiesFormat) - if err != nil { - return err - } - erpa.ExpressRoutePortAuthorizationPropertiesFormat = &expressRoutePortAuthorizationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erpa.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erpa.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - erpa.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erpa.ID = &ID - } - } - } - - return nil -} - -// ExpressRoutePortAuthorizationListResult response for ListExpressRoutePortAuthorizations API service -// call. -type ExpressRoutePortAuthorizationListResult struct { - autorest.Response `json:"-"` - // Value - The authorizations in an ExpressRoute Port. - Value *[]ExpressRoutePortAuthorization `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRoutePortAuthorizationListResultIterator provides access to a complete listing of -// ExpressRoutePortAuthorization values. -type ExpressRoutePortAuthorizationListResultIterator struct { - i int - page ExpressRoutePortAuthorizationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRoutePortAuthorizationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortAuthorizationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRoutePortAuthorizationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRoutePortAuthorizationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRoutePortAuthorizationListResultIterator) Response() ExpressRoutePortAuthorizationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRoutePortAuthorizationListResultIterator) Value() ExpressRoutePortAuthorization { - if !iter.page.NotDone() { - return ExpressRoutePortAuthorization{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRoutePortAuthorizationListResultIterator type. -func NewExpressRoutePortAuthorizationListResultIterator(page ExpressRoutePortAuthorizationListResultPage) ExpressRoutePortAuthorizationListResultIterator { - return ExpressRoutePortAuthorizationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (erpalr ExpressRoutePortAuthorizationListResult) IsEmpty() bool { - return erpalr.Value == nil || len(*erpalr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (erpalr ExpressRoutePortAuthorizationListResult) hasNextLink() bool { - return erpalr.NextLink != nil && len(*erpalr.NextLink) != 0 -} - -// expressRoutePortAuthorizationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (erpalr ExpressRoutePortAuthorizationListResult) expressRoutePortAuthorizationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !erpalr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(erpalr.NextLink))) -} - -// ExpressRoutePortAuthorizationListResultPage contains a page of ExpressRoutePortAuthorization values. -type ExpressRoutePortAuthorizationListResultPage struct { - fn func(context.Context, ExpressRoutePortAuthorizationListResult) (ExpressRoutePortAuthorizationListResult, error) - erpalr ExpressRoutePortAuthorizationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRoutePortAuthorizationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortAuthorizationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.erpalr) - if err != nil { - return err - } - page.erpalr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRoutePortAuthorizationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRoutePortAuthorizationListResultPage) NotDone() bool { - return !page.erpalr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRoutePortAuthorizationListResultPage) Response() ExpressRoutePortAuthorizationListResult { - return page.erpalr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRoutePortAuthorizationListResultPage) Values() []ExpressRoutePortAuthorization { - if page.erpalr.IsEmpty() { - return nil - } - return *page.erpalr.Value -} - -// Creates a new instance of the ExpressRoutePortAuthorizationListResultPage type. -func NewExpressRoutePortAuthorizationListResultPage(cur ExpressRoutePortAuthorizationListResult, getNextPage func(context.Context, ExpressRoutePortAuthorizationListResult) (ExpressRoutePortAuthorizationListResult, error)) ExpressRoutePortAuthorizationListResultPage { - return ExpressRoutePortAuthorizationListResultPage{ - fn: getNextPage, - erpalr: cur, - } -} - -// ExpressRoutePortAuthorizationPropertiesFormat properties of ExpressRoutePort Authorization. -type ExpressRoutePortAuthorizationPropertiesFormat struct { - // AuthorizationKey - READ-ONLY; The authorization key. - AuthorizationKey *string `json:"authorizationKey,omitempty"` - // AuthorizationUseStatus - READ-ONLY; The authorization use status. Possible values include: 'ExpressRoutePortAuthorizationUseStatusAvailable', 'ExpressRoutePortAuthorizationUseStatusInUse' - AuthorizationUseStatus ExpressRoutePortAuthorizationUseStatus `json:"authorizationUseStatus,omitempty"` - // CircuitResourceURI - READ-ONLY; The reference to the ExpressRoute circuit resource using the authorization. - CircuitResourceURI *string `json:"circuitResourceUri,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the authorization resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRoutePortAuthorizationPropertiesFormat. -func (erpapf ExpressRoutePortAuthorizationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ExpressRoutePortAuthorizationsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ExpressRoutePortAuthorizationsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRoutePortAuthorizationsClient) (ExpressRoutePortAuthorization, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRoutePortAuthorizationsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRoutePortAuthorizationsCreateOrUpdateFuture.Result. -func (future *ExpressRoutePortAuthorizationsCreateOrUpdateFuture) result(client ExpressRoutePortAuthorizationsClient) (erpa ExpressRoutePortAuthorization, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erpa.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRoutePortAuthorizationsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erpa.Response.Response, err = future.GetResult(sender); err == nil && erpa.Response.Response.StatusCode != http.StatusNoContent { - erpa, err = client.CreateOrUpdateResponder(erpa.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsCreateOrUpdateFuture", "Result", erpa.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRoutePortAuthorizationsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRoutePortAuthorizationsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRoutePortAuthorizationsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRoutePortAuthorizationsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRoutePortAuthorizationsDeleteFuture.Result. -func (future *ExpressRoutePortAuthorizationsDeleteFuture) result(client ExpressRoutePortAuthorizationsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortAuthorizationsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRoutePortAuthorizationsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRoutePortListResult response for ListExpressRoutePorts API service call. -type ExpressRoutePortListResult struct { - autorest.Response `json:"-"` - // Value - A list of ExpressRoutePort resources. - Value *[]ExpressRoutePort `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRoutePortListResultIterator provides access to a complete listing of ExpressRoutePort values. -type ExpressRoutePortListResultIterator struct { - i int - page ExpressRoutePortListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRoutePortListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRoutePortListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRoutePortListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRoutePortListResultIterator) Response() ExpressRoutePortListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRoutePortListResultIterator) Value() ExpressRoutePort { - if !iter.page.NotDone() { - return ExpressRoutePort{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRoutePortListResultIterator type. -func NewExpressRoutePortListResultIterator(page ExpressRoutePortListResultPage) ExpressRoutePortListResultIterator { - return ExpressRoutePortListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (erplr ExpressRoutePortListResult) IsEmpty() bool { - return erplr.Value == nil || len(*erplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (erplr ExpressRoutePortListResult) hasNextLink() bool { - return erplr.NextLink != nil && len(*erplr.NextLink) != 0 -} - -// expressRoutePortListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (erplr ExpressRoutePortListResult) expressRoutePortListResultPreparer(ctx context.Context) (*http.Request, error) { - if !erplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(erplr.NextLink))) -} - -// ExpressRoutePortListResultPage contains a page of ExpressRoutePort values. -type ExpressRoutePortListResultPage struct { - fn func(context.Context, ExpressRoutePortListResult) (ExpressRoutePortListResult, error) - erplr ExpressRoutePortListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRoutePortListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.erplr) - if err != nil { - return err - } - page.erplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRoutePortListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRoutePortListResultPage) NotDone() bool { - return !page.erplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRoutePortListResultPage) Response() ExpressRoutePortListResult { - return page.erplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRoutePortListResultPage) Values() []ExpressRoutePort { - if page.erplr.IsEmpty() { - return nil - } - return *page.erplr.Value -} - -// Creates a new instance of the ExpressRoutePortListResultPage type. -func NewExpressRoutePortListResultPage(cur ExpressRoutePortListResult, getNextPage func(context.Context, ExpressRoutePortListResult) (ExpressRoutePortListResult, error)) ExpressRoutePortListResultPage { - return ExpressRoutePortListResultPage{ - fn: getNextPage, - erplr: cur, - } -} - -// ExpressRoutePortPropertiesFormat properties specific to ExpressRoutePort resources. -type ExpressRoutePortPropertiesFormat struct { - // PeeringLocation - The name of the peering location that the ExpressRoutePort is mapped to physically. - PeeringLocation *string `json:"peeringLocation,omitempty"` - // BandwidthInGbps - Bandwidth of procured ports in Gbps. - BandwidthInGbps *int32 `json:"bandwidthInGbps,omitempty"` - // ProvisionedBandwidthInGbps - READ-ONLY; Aggregate Gbps of associated circuit bandwidths. - ProvisionedBandwidthInGbps *float64 `json:"provisionedBandwidthInGbps,omitempty"` - // Mtu - READ-ONLY; Maximum transmission unit of the physical port pair(s). - Mtu *string `json:"mtu,omitempty"` - // Encapsulation - Encapsulation method on physical ports. Possible values include: 'Dot1Q', 'QinQ' - Encapsulation ExpressRoutePortsEncapsulation `json:"encapsulation,omitempty"` - // EtherType - READ-ONLY; Ether type of the physical port. - EtherType *string `json:"etherType,omitempty"` - // AllocationDate - READ-ONLY; Date of the physical port allocation to be used in Letter of Authorization. - AllocationDate *string `json:"allocationDate,omitempty"` - // Links - The set of physical links of the ExpressRoutePort resource. - Links *[]ExpressRouteLink `json:"links,omitempty"` - // Circuits - READ-ONLY; Reference the ExpressRoute circuit(s) that are provisioned on this ExpressRoutePort resource. - Circuits *[]SubResource `json:"circuits,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the express route port resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the express route port resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // BillingType - The billing type of the ExpressRoutePort resource. Possible values include: 'ExpressRoutePortsBillingTypeMeteredData', 'ExpressRoutePortsBillingTypeUnlimitedData' - BillingType ExpressRoutePortsBillingType `json:"billingType,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRoutePortPropertiesFormat. -func (erppf ExpressRoutePortPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erppf.PeeringLocation != nil { - objectMap["peeringLocation"] = erppf.PeeringLocation - } - if erppf.BandwidthInGbps != nil { - objectMap["bandwidthInGbps"] = erppf.BandwidthInGbps - } - if erppf.Encapsulation != "" { - objectMap["encapsulation"] = erppf.Encapsulation - } - if erppf.Links != nil { - objectMap["links"] = erppf.Links - } - if erppf.BillingType != "" { - objectMap["billingType"] = erppf.BillingType - } - return json.Marshal(objectMap) -} - -// ExpressRoutePortsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ExpressRoutePortsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRoutePortsClient) (ExpressRoutePort, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRoutePortsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRoutePortsCreateOrUpdateFuture.Result. -func (future *ExpressRoutePortsCreateOrUpdateFuture) result(client ExpressRoutePortsClient) (erp ExpressRoutePort, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRoutePortsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erp.Response.Response, err = future.GetResult(sender); err == nil && erp.Response.Response.StatusCode != http.StatusNoContent { - erp, err = client.CreateOrUpdateResponder(erp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsCreateOrUpdateFuture", "Result", erp.Response.Response, "Failure responding to request") - } - } - return -} - -// ExpressRoutePortsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ExpressRoutePortsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ExpressRoutePortsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ExpressRoutePortsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ExpressRoutePortsDeleteFuture.Result. -func (future *ExpressRoutePortsDeleteFuture) result(client ExpressRoutePortsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ExpressRoutePortsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ExpressRoutePortsLocation definition of the ExpressRoutePorts peering location resource. -type ExpressRoutePortsLocation struct { - autorest.Response `json:"-"` - // ExpressRoutePortsLocationPropertiesFormat - ExpressRoutePort peering location properties. - *ExpressRoutePortsLocationPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ExpressRoutePortsLocation. -func (erpl ExpressRoutePortsLocation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erpl.ExpressRoutePortsLocationPropertiesFormat != nil { - objectMap["properties"] = erpl.ExpressRoutePortsLocationPropertiesFormat - } - if erpl.ID != nil { - objectMap["id"] = erpl.ID - } - if erpl.Location != nil { - objectMap["location"] = erpl.Location - } - if erpl.Tags != nil { - objectMap["tags"] = erpl.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRoutePortsLocation struct. -func (erpl *ExpressRoutePortsLocation) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRoutePortsLocationPropertiesFormat ExpressRoutePortsLocationPropertiesFormat - err = json.Unmarshal(*v, &expressRoutePortsLocationPropertiesFormat) - if err != nil { - return err - } - erpl.ExpressRoutePortsLocationPropertiesFormat = &expressRoutePortsLocationPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erpl.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erpl.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - erpl.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - erpl.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - erpl.Tags = tags - } - } - } - - return nil -} - -// ExpressRoutePortsLocationBandwidths real-time inventory of available ExpressRoute port bandwidths. -type ExpressRoutePortsLocationBandwidths struct { - // OfferName - READ-ONLY; Bandwidth descriptive name. - OfferName *string `json:"offerName,omitempty"` - // ValueInGbps - READ-ONLY; Bandwidth value in Gbps. - ValueInGbps *int32 `json:"valueInGbps,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRoutePortsLocationBandwidths. -func (erplb ExpressRoutePortsLocationBandwidths) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ExpressRoutePortsLocationListResult response for ListExpressRoutePortsLocations API service call. -type ExpressRoutePortsLocationListResult struct { - autorest.Response `json:"-"` - // Value - The list of all ExpressRoutePort peering locations. - Value *[]ExpressRoutePortsLocation `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRoutePortsLocationListResultIterator provides access to a complete listing of -// ExpressRoutePortsLocation values. -type ExpressRoutePortsLocationListResultIterator struct { - i int - page ExpressRoutePortsLocationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRoutePortsLocationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsLocationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRoutePortsLocationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRoutePortsLocationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRoutePortsLocationListResultIterator) Response() ExpressRoutePortsLocationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRoutePortsLocationListResultIterator) Value() ExpressRoutePortsLocation { - if !iter.page.NotDone() { - return ExpressRoutePortsLocation{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRoutePortsLocationListResultIterator type. -func NewExpressRoutePortsLocationListResultIterator(page ExpressRoutePortsLocationListResultPage) ExpressRoutePortsLocationListResultIterator { - return ExpressRoutePortsLocationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (erpllr ExpressRoutePortsLocationListResult) IsEmpty() bool { - return erpllr.Value == nil || len(*erpllr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (erpllr ExpressRoutePortsLocationListResult) hasNextLink() bool { - return erpllr.NextLink != nil && len(*erpllr.NextLink) != 0 -} - -// expressRoutePortsLocationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (erpllr ExpressRoutePortsLocationListResult) expressRoutePortsLocationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !erpllr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(erpllr.NextLink))) -} - -// ExpressRoutePortsLocationListResultPage contains a page of ExpressRoutePortsLocation values. -type ExpressRoutePortsLocationListResultPage struct { - fn func(context.Context, ExpressRoutePortsLocationListResult) (ExpressRoutePortsLocationListResult, error) - erpllr ExpressRoutePortsLocationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRoutePortsLocationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsLocationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.erpllr) - if err != nil { - return err - } - page.erpllr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRoutePortsLocationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRoutePortsLocationListResultPage) NotDone() bool { - return !page.erpllr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRoutePortsLocationListResultPage) Response() ExpressRoutePortsLocationListResult { - return page.erpllr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRoutePortsLocationListResultPage) Values() []ExpressRoutePortsLocation { - if page.erpllr.IsEmpty() { - return nil - } - return *page.erpllr.Value -} - -// Creates a new instance of the ExpressRoutePortsLocationListResultPage type. -func NewExpressRoutePortsLocationListResultPage(cur ExpressRoutePortsLocationListResult, getNextPage func(context.Context, ExpressRoutePortsLocationListResult) (ExpressRoutePortsLocationListResult, error)) ExpressRoutePortsLocationListResultPage { - return ExpressRoutePortsLocationListResultPage{ - fn: getNextPage, - erpllr: cur, - } -} - -// ExpressRoutePortsLocationPropertiesFormat properties specific to ExpressRoutePorts peering location -// resources. -type ExpressRoutePortsLocationPropertiesFormat struct { - // Address - READ-ONLY; Address of peering location. - Address *string `json:"address,omitempty"` - // Contact - READ-ONLY; Contact details of peering locations. - Contact *string `json:"contact,omitempty"` - // AvailableBandwidths - The inventory of available ExpressRoutePort bandwidths. - AvailableBandwidths *[]ExpressRoutePortsLocationBandwidths `json:"availableBandwidths,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the express route port location resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRoutePortsLocationPropertiesFormat. -func (erplpf ExpressRoutePortsLocationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erplpf.AvailableBandwidths != nil { - objectMap["availableBandwidths"] = erplpf.AvailableBandwidths - } - return json.Marshal(objectMap) -} - -// ExpressRouteProviderPort expressRouteProviderPort resource. -type ExpressRouteProviderPort struct { - autorest.Response `json:"-"` - // ExpressRouteProviderPortProperties - Properties of the express route Service Provider Port. - *ExpressRouteProviderPortProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteProviderPort. -func (erpp ExpressRouteProviderPort) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erpp.ExpressRouteProviderPortProperties != nil { - objectMap["properties"] = erpp.ExpressRouteProviderPortProperties - } - if erpp.ID != nil { - objectMap["id"] = erpp.ID - } - if erpp.Location != nil { - objectMap["location"] = erpp.Location - } - if erpp.Tags != nil { - objectMap["tags"] = erpp.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteProviderPort struct. -func (erpp *ExpressRouteProviderPort) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteProviderPortProperties ExpressRouteProviderPortProperties - err = json.Unmarshal(*v, &expressRouteProviderPortProperties) - if err != nil { - return err - } - erpp.ExpressRouteProviderPortProperties = &expressRouteProviderPortProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - erpp.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - erpp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - erpp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - erpp.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - erpp.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - erpp.Tags = tags - } - } - } - - return nil -} - -// ExpressRouteProviderPortListResult response for ListExpressRouteProviderPort API service call. -type ExpressRouteProviderPortListResult struct { - autorest.Response `json:"-"` - // Value - A list of ExpressRouteProviderPort resources. - Value *[]ExpressRouteProviderPort `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteProviderPortListResult. -func (erpplr ExpressRouteProviderPortListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erpplr.Value != nil { - objectMap["value"] = erpplr.Value - } - return json.Marshal(objectMap) -} - -// ExpressRouteProviderPortProperties properties of ExpressRouteProviderPort. -type ExpressRouteProviderPortProperties struct { - // PortPairDescriptor - READ-ONLY; The name of the port pair. - PortPairDescriptor *string `json:"portPairDescriptor,omitempty"` - // PrimaryAzurePort - READ-ONLY; The name of the primary port. - PrimaryAzurePort *string `json:"primaryAzurePort,omitempty"` - // SecondaryAzurePort - READ-ONLY; The name of the secondary port. - SecondaryAzurePort *string `json:"secondaryAzurePort,omitempty"` - // PeeringLocation - The peering location of the port pair. - PeeringLocation *string `json:"peeringLocation,omitempty"` - // OverprovisionFactor - Overprovisioning factor for the port pair. - OverprovisionFactor *int32 `json:"overprovisionFactor,omitempty"` - // PortBandwidthInMbps - Bandwidth of the port in Mbps - PortBandwidthInMbps *int32 `json:"portBandwidthInMbps,omitempty"` - // UsedBandwidthInMbps - Used Bandwidth of the port in Mbps - UsedBandwidthInMbps *int32 `json:"usedBandwidthInMbps,omitempty"` - // RemainingBandwidthInMbps - Remaining Bandwidth of the port in Mbps - RemainingBandwidthInMbps *int32 `json:"remainingBandwidthInMbps,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteProviderPortProperties. -func (erppp ExpressRouteProviderPortProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if erppp.PeeringLocation != nil { - objectMap["peeringLocation"] = erppp.PeeringLocation - } - if erppp.OverprovisionFactor != nil { - objectMap["overprovisionFactor"] = erppp.OverprovisionFactor - } - if erppp.PortBandwidthInMbps != nil { - objectMap["portBandwidthInMbps"] = erppp.PortBandwidthInMbps - } - if erppp.UsedBandwidthInMbps != nil { - objectMap["usedBandwidthInMbps"] = erppp.UsedBandwidthInMbps - } - if erppp.RemainingBandwidthInMbps != nil { - objectMap["remainingBandwidthInMbps"] = erppp.RemainingBandwidthInMbps - } - return json.Marshal(objectMap) -} - -// ExpressRouteServiceProvider a ExpressRouteResourceProvider object. -type ExpressRouteServiceProvider struct { - // ExpressRouteServiceProviderPropertiesFormat - Properties of the express route service provider. - *ExpressRouteServiceProviderPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteServiceProvider. -func (ersp ExpressRouteServiceProvider) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ersp.ExpressRouteServiceProviderPropertiesFormat != nil { - objectMap["properties"] = ersp.ExpressRouteServiceProviderPropertiesFormat - } - if ersp.ID != nil { - objectMap["id"] = ersp.ID - } - if ersp.Location != nil { - objectMap["location"] = ersp.Location - } - if ersp.Tags != nil { - objectMap["tags"] = ersp.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ExpressRouteServiceProvider struct. -func (ersp *ExpressRouteServiceProvider) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var expressRouteServiceProviderPropertiesFormat ExpressRouteServiceProviderPropertiesFormat - err = json.Unmarshal(*v, &expressRouteServiceProviderPropertiesFormat) - if err != nil { - return err - } - ersp.ExpressRouteServiceProviderPropertiesFormat = &expressRouteServiceProviderPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ersp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ersp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ersp.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ersp.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - ersp.Tags = tags - } - } - } - - return nil -} - -// ExpressRouteServiceProviderBandwidthsOffered contains bandwidths offered in ExpressRouteServiceProvider -// resources. -type ExpressRouteServiceProviderBandwidthsOffered struct { - // OfferName - The OfferName. - OfferName *string `json:"offerName,omitempty"` - // ValueInMbps - The ValueInMbps. - ValueInMbps *int32 `json:"valueInMbps,omitempty"` -} - -// ExpressRouteServiceProviderListResult response for the ListExpressRouteServiceProvider API service call. -type ExpressRouteServiceProviderListResult struct { - autorest.Response `json:"-"` - // Value - A list of ExpressRouteResourceProvider resources. - Value *[]ExpressRouteServiceProvider `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ExpressRouteServiceProviderListResultIterator provides access to a complete listing of -// ExpressRouteServiceProvider values. -type ExpressRouteServiceProviderListResultIterator struct { - i int - page ExpressRouteServiceProviderListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ExpressRouteServiceProviderListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteServiceProviderListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ExpressRouteServiceProviderListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ExpressRouteServiceProviderListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ExpressRouteServiceProviderListResultIterator) Response() ExpressRouteServiceProviderListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ExpressRouteServiceProviderListResultIterator) Value() ExpressRouteServiceProvider { - if !iter.page.NotDone() { - return ExpressRouteServiceProvider{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ExpressRouteServiceProviderListResultIterator type. -func NewExpressRouteServiceProviderListResultIterator(page ExpressRouteServiceProviderListResultPage) ExpressRouteServiceProviderListResultIterator { - return ExpressRouteServiceProviderListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ersplr ExpressRouteServiceProviderListResult) IsEmpty() bool { - return ersplr.Value == nil || len(*ersplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ersplr ExpressRouteServiceProviderListResult) hasNextLink() bool { - return ersplr.NextLink != nil && len(*ersplr.NextLink) != 0 -} - -// expressRouteServiceProviderListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ersplr ExpressRouteServiceProviderListResult) expressRouteServiceProviderListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ersplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ersplr.NextLink))) -} - -// ExpressRouteServiceProviderListResultPage contains a page of ExpressRouteServiceProvider values. -type ExpressRouteServiceProviderListResultPage struct { - fn func(context.Context, ExpressRouteServiceProviderListResult) (ExpressRouteServiceProviderListResult, error) - ersplr ExpressRouteServiceProviderListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ExpressRouteServiceProviderListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRouteServiceProviderListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ersplr) - if err != nil { - return err - } - page.ersplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ExpressRouteServiceProviderListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ExpressRouteServiceProviderListResultPage) NotDone() bool { - return !page.ersplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ExpressRouteServiceProviderListResultPage) Response() ExpressRouteServiceProviderListResult { - return page.ersplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ExpressRouteServiceProviderListResultPage) Values() []ExpressRouteServiceProvider { - if page.ersplr.IsEmpty() { - return nil - } - return *page.ersplr.Value -} - -// Creates a new instance of the ExpressRouteServiceProviderListResultPage type. -func NewExpressRouteServiceProviderListResultPage(cur ExpressRouteServiceProviderListResult, getNextPage func(context.Context, ExpressRouteServiceProviderListResult) (ExpressRouteServiceProviderListResult, error)) ExpressRouteServiceProviderListResultPage { - return ExpressRouteServiceProviderListResultPage{ - fn: getNextPage, - ersplr: cur, - } -} - -// ExpressRouteServiceProviderPropertiesFormat properties of ExpressRouteServiceProvider. -type ExpressRouteServiceProviderPropertiesFormat struct { - // PeeringLocations - A list of peering locations. - PeeringLocations *[]string `json:"peeringLocations,omitempty"` - // BandwidthsOffered - A list of bandwidths offered. - BandwidthsOffered *[]ExpressRouteServiceProviderBandwidthsOffered `json:"bandwidthsOffered,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the express route service provider resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ExpressRouteServiceProviderPropertiesFormat. -func (ersppf ExpressRouteServiceProviderPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ersppf.PeeringLocations != nil { - objectMap["peeringLocations"] = ersppf.PeeringLocations - } - if ersppf.BandwidthsOffered != nil { - objectMap["bandwidthsOffered"] = ersppf.BandwidthsOffered - } - return json.Marshal(objectMap) -} - -// ExtendedLocation extendedLocation complex type. -type ExtendedLocation struct { - // Name - The name of the extended location. - Name *string `json:"name,omitempty"` - // Type - The type of the extended location. Possible values include: 'EdgeZone' - Type ExtendedLocationTypes `json:"type,omitempty"` -} - -// FilterItems will contain the filter name and values to operate on -type FilterItems struct { - // Field - The name of the field we would like to filter - Field *string `json:"field,omitempty"` - // Values - List of values to filter the current field by - Values *[]string `json:"values,omitempty"` -} - -// FirewallPoliciesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type FirewallPoliciesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(FirewallPoliciesClient) (FirewallPolicy, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *FirewallPoliciesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for FirewallPoliciesCreateOrUpdateFuture.Result. -func (future *FirewallPoliciesCreateOrUpdateFuture) result(client FirewallPoliciesClient) (fp FirewallPolicy, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - fp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.FirewallPoliciesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if fp.Response.Response, err = future.GetResult(sender); err == nil && fp.Response.Response.StatusCode != http.StatusNoContent { - fp, err = client.CreateOrUpdateResponder(fp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesCreateOrUpdateFuture", "Result", fp.Response.Response, "Failure responding to request") - } - } - return -} - -// FirewallPoliciesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type FirewallPoliciesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(FirewallPoliciesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *FirewallPoliciesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for FirewallPoliciesDeleteFuture.Result. -func (future *FirewallPoliciesDeleteFuture) result(client FirewallPoliciesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPoliciesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.FirewallPoliciesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// FirewallPolicy firewallPolicy Resource. -type FirewallPolicy struct { - autorest.Response `json:"-"` - // FirewallPolicyPropertiesFormat - Properties of the firewall policy. - *FirewallPolicyPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Identity - The identity of the firewall policy. - Identity *ManagedServiceIdentity `json:"identity,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for FirewallPolicy. -func (fp FirewallPolicy) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if fp.FirewallPolicyPropertiesFormat != nil { - objectMap["properties"] = fp.FirewallPolicyPropertiesFormat - } - if fp.Identity != nil { - objectMap["identity"] = fp.Identity - } - if fp.ID != nil { - objectMap["id"] = fp.ID - } - if fp.Location != nil { - objectMap["location"] = fp.Location - } - if fp.Tags != nil { - objectMap["tags"] = fp.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for FirewallPolicy struct. -func (fp *FirewallPolicy) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var firewallPolicyPropertiesFormat FirewallPolicyPropertiesFormat - err = json.Unmarshal(*v, &firewallPolicyPropertiesFormat) - if err != nil { - return err - } - fp.FirewallPolicyPropertiesFormat = &firewallPolicyPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - fp.Etag = &etag - } - case "identity": - if v != nil { - var identity ManagedServiceIdentity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - fp.Identity = &identity - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - fp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - fp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - fp.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - fp.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - fp.Tags = tags - } - } - } - - return nil -} - -// FirewallPolicyCertificateAuthority trusted Root certificates properties for tls. -type FirewallPolicyCertificateAuthority struct { - // KeyVaultSecretID - Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or 'Certificate' object stored in KeyVault. - KeyVaultSecretID *string `json:"keyVaultSecretId,omitempty"` - // Name - Name of the CA certificate. - Name *string `json:"name,omitempty"` -} - -// FirewallPolicyFilterRuleCollection firewall Policy Filter Rule Collection. -type FirewallPolicyFilterRuleCollection struct { - // Action - The action type of a Filter rule collection. - Action *FirewallPolicyFilterRuleCollectionAction `json:"action,omitempty"` - // Rules - List of rules included in a rule collection. - Rules *[]BasicFirewallPolicyRule `json:"rules,omitempty"` - // Name - The name of the rule collection. - Name *string `json:"name,omitempty"` - // Priority - Priority of the Firewall Policy Rule Collection resource. - Priority *int32 `json:"priority,omitempty"` - // RuleCollectionType - Possible values include: 'RuleCollectionTypeFirewallPolicyRuleCollection', 'RuleCollectionTypeFirewallPolicyNatRuleCollection', 'RuleCollectionTypeFirewallPolicyFilterRuleCollection' - RuleCollectionType RuleCollectionType `json:"ruleCollectionType,omitempty"` -} - -// MarshalJSON is the custom marshaler for FirewallPolicyFilterRuleCollection. -func (fpfrc FirewallPolicyFilterRuleCollection) MarshalJSON() ([]byte, error) { - fpfrc.RuleCollectionType = RuleCollectionTypeFirewallPolicyFilterRuleCollection - objectMap := make(map[string]interface{}) - if fpfrc.Action != nil { - objectMap["action"] = fpfrc.Action - } - if fpfrc.Rules != nil { - objectMap["rules"] = fpfrc.Rules - } - if fpfrc.Name != nil { - objectMap["name"] = fpfrc.Name - } - if fpfrc.Priority != nil { - objectMap["priority"] = fpfrc.Priority - } - if fpfrc.RuleCollectionType != "" { - objectMap["ruleCollectionType"] = fpfrc.RuleCollectionType - } - return json.Marshal(objectMap) -} - -// AsFirewallPolicyNatRuleCollection is the BasicFirewallPolicyRuleCollection implementation for FirewallPolicyFilterRuleCollection. -func (fpfrc FirewallPolicyFilterRuleCollection) AsFirewallPolicyNatRuleCollection() (*FirewallPolicyNatRuleCollection, bool) { - return nil, false -} - -// AsFirewallPolicyFilterRuleCollection is the BasicFirewallPolicyRuleCollection implementation for FirewallPolicyFilterRuleCollection. -func (fpfrc FirewallPolicyFilterRuleCollection) AsFirewallPolicyFilterRuleCollection() (*FirewallPolicyFilterRuleCollection, bool) { - return &fpfrc, true -} - -// AsFirewallPolicyRuleCollection is the BasicFirewallPolicyRuleCollection implementation for FirewallPolicyFilterRuleCollection. -func (fpfrc FirewallPolicyFilterRuleCollection) AsFirewallPolicyRuleCollection() (*FirewallPolicyRuleCollection, bool) { - return nil, false -} - -// AsBasicFirewallPolicyRuleCollection is the BasicFirewallPolicyRuleCollection implementation for FirewallPolicyFilterRuleCollection. -func (fpfrc FirewallPolicyFilterRuleCollection) AsBasicFirewallPolicyRuleCollection() (BasicFirewallPolicyRuleCollection, bool) { - return &fpfrc, true -} - -// UnmarshalJSON is the custom unmarshaler for FirewallPolicyFilterRuleCollection struct. -func (fpfrc *FirewallPolicyFilterRuleCollection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "action": - if v != nil { - var action FirewallPolicyFilterRuleCollectionAction - err = json.Unmarshal(*v, &action) - if err != nil { - return err - } - fpfrc.Action = &action - } - case "rules": - if v != nil { - rules, err := unmarshalBasicFirewallPolicyRuleArray(*v) - if err != nil { - return err - } - fpfrc.Rules = &rules - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - fpfrc.Name = &name - } - case "priority": - if v != nil { - var priority int32 - err = json.Unmarshal(*v, &priority) - if err != nil { - return err - } - fpfrc.Priority = &priority - } - case "ruleCollectionType": - if v != nil { - var ruleCollectionType RuleCollectionType - err = json.Unmarshal(*v, &ruleCollectionType) - if err != nil { - return err - } - fpfrc.RuleCollectionType = ruleCollectionType - } - } - } - - return nil -} - -// FirewallPolicyFilterRuleCollectionAction properties of the FirewallPolicyFilterRuleCollectionAction. -type FirewallPolicyFilterRuleCollectionAction struct { - // Type - The type of action. Possible values include: 'FirewallPolicyFilterRuleCollectionActionTypeAllow', 'FirewallPolicyFilterRuleCollectionActionTypeDeny' - Type FirewallPolicyFilterRuleCollectionActionType `json:"type,omitempty"` -} - -// FirewallPolicyInsights firewall Policy Insights. -type FirewallPolicyInsights struct { - // IsEnabled - A flag to indicate if the insights are enabled on the policy. - IsEnabled *bool `json:"isEnabled,omitempty"` - // RetentionDays - Number of days the insights should be enabled on the policy. - RetentionDays *int32 `json:"retentionDays,omitempty"` - // LogAnalyticsResources - Workspaces needed to configure the Firewall Policy Insights. - LogAnalyticsResources *FirewallPolicyLogAnalyticsResources `json:"logAnalyticsResources,omitempty"` -} - -// FirewallPolicyIntrusionDetection configuration for intrusion detection mode and rules. -type FirewallPolicyIntrusionDetection struct { - // Mode - Intrusion detection general state. Possible values include: 'FirewallPolicyIntrusionDetectionStateTypeOff', 'FirewallPolicyIntrusionDetectionStateTypeAlert', 'FirewallPolicyIntrusionDetectionStateTypeDeny' - Mode FirewallPolicyIntrusionDetectionStateType `json:"mode,omitempty"` - // Configuration - Intrusion detection configuration properties. - Configuration *FirewallPolicyIntrusionDetectionConfiguration `json:"configuration,omitempty"` -} - -// FirewallPolicyIntrusionDetectionBypassTrafficSpecifications intrusion detection bypass traffic -// specification. -type FirewallPolicyIntrusionDetectionBypassTrafficSpecifications struct { - // Name - Name of the bypass traffic rule. - Name *string `json:"name,omitempty"` - // Description - Description of the bypass traffic rule. - Description *string `json:"description,omitempty"` - // Protocol - The rule bypass protocol. Possible values include: 'FirewallPolicyIntrusionDetectionProtocolTCP', 'FirewallPolicyIntrusionDetectionProtocolUDP', 'FirewallPolicyIntrusionDetectionProtocolICMP', 'FirewallPolicyIntrusionDetectionProtocolANY' - Protocol FirewallPolicyIntrusionDetectionProtocol `json:"protocol,omitempty"` - // SourceAddresses - List of source IP addresses or ranges for this rule. - SourceAddresses *[]string `json:"sourceAddresses,omitempty"` - // DestinationAddresses - List of destination IP addresses or ranges for this rule. - DestinationAddresses *[]string `json:"destinationAddresses,omitempty"` - // DestinationPorts - List of destination ports or ranges. - DestinationPorts *[]string `json:"destinationPorts,omitempty"` - // SourceIPGroups - List of source IpGroups for this rule. - SourceIPGroups *[]string `json:"sourceIpGroups,omitempty"` - // DestinationIPGroups - List of destination IpGroups for this rule. - DestinationIPGroups *[]string `json:"destinationIpGroups,omitempty"` -} - -// FirewallPolicyIntrusionDetectionConfiguration the operation for configuring intrusion detection. -type FirewallPolicyIntrusionDetectionConfiguration struct { - // SignatureOverrides - List of specific signatures states. - SignatureOverrides *[]FirewallPolicyIntrusionDetectionSignatureSpecification `json:"signatureOverrides,omitempty"` - // BypassTrafficSettings - List of rules for traffic to bypass. - BypassTrafficSettings *[]FirewallPolicyIntrusionDetectionBypassTrafficSpecifications `json:"bypassTrafficSettings,omitempty"` - // PrivateRanges - IDPS Private IP address ranges are used to identify traffic direction (i.e. inbound, outbound, etc.). By default, only ranges defined by IANA RFC 1918 are considered private IP addresses. To modify default ranges, specify your Private IP address ranges with this property - PrivateRanges *[]string `json:"privateRanges,omitempty"` -} - -// FirewallPolicyIntrusionDetectionSignatureSpecification intrusion detection signatures specification -// states. -type FirewallPolicyIntrusionDetectionSignatureSpecification struct { - // ID - Signature id. - ID *string `json:"id,omitempty"` - // Mode - The signature state. Possible values include: 'FirewallPolicyIntrusionDetectionStateTypeOff', 'FirewallPolicyIntrusionDetectionStateTypeAlert', 'FirewallPolicyIntrusionDetectionStateTypeDeny' - Mode FirewallPolicyIntrusionDetectionStateType `json:"mode,omitempty"` -} - -// FirewallPolicyListResult response for ListFirewallPolicies API service call. -type FirewallPolicyListResult struct { - autorest.Response `json:"-"` - // Value - List of Firewall Policies in a resource group. - Value *[]FirewallPolicy `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// FirewallPolicyListResultIterator provides access to a complete listing of FirewallPolicy values. -type FirewallPolicyListResultIterator struct { - i int - page FirewallPolicyListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *FirewallPolicyListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *FirewallPolicyListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter FirewallPolicyListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter FirewallPolicyListResultIterator) Response() FirewallPolicyListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter FirewallPolicyListResultIterator) Value() FirewallPolicy { - if !iter.page.NotDone() { - return FirewallPolicy{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the FirewallPolicyListResultIterator type. -func NewFirewallPolicyListResultIterator(page FirewallPolicyListResultPage) FirewallPolicyListResultIterator { - return FirewallPolicyListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (fplr FirewallPolicyListResult) IsEmpty() bool { - return fplr.Value == nil || len(*fplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (fplr FirewallPolicyListResult) hasNextLink() bool { - return fplr.NextLink != nil && len(*fplr.NextLink) != 0 -} - -// firewallPolicyListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (fplr FirewallPolicyListResult) firewallPolicyListResultPreparer(ctx context.Context) (*http.Request, error) { - if !fplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(fplr.NextLink))) -} - -// FirewallPolicyListResultPage contains a page of FirewallPolicy values. -type FirewallPolicyListResultPage struct { - fn func(context.Context, FirewallPolicyListResult) (FirewallPolicyListResult, error) - fplr FirewallPolicyListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *FirewallPolicyListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.fplr) - if err != nil { - return err - } - page.fplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *FirewallPolicyListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page FirewallPolicyListResultPage) NotDone() bool { - return !page.fplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page FirewallPolicyListResultPage) Response() FirewallPolicyListResult { - return page.fplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page FirewallPolicyListResultPage) Values() []FirewallPolicy { - if page.fplr.IsEmpty() { - return nil - } - return *page.fplr.Value -} - -// Creates a new instance of the FirewallPolicyListResultPage type. -func NewFirewallPolicyListResultPage(cur FirewallPolicyListResult, getNextPage func(context.Context, FirewallPolicyListResult) (FirewallPolicyListResult, error)) FirewallPolicyListResultPage { - return FirewallPolicyListResultPage{ - fn: getNextPage, - fplr: cur, - } -} - -// FirewallPolicyLogAnalyticsResources log Analytics Resources for Firewall Policy Insights. -type FirewallPolicyLogAnalyticsResources struct { - // Workspaces - List of workspaces for Firewall Policy Insights. - Workspaces *[]FirewallPolicyLogAnalyticsWorkspace `json:"workspaces,omitempty"` - // DefaultWorkspaceID - The default workspace Id for Firewall Policy Insights. - DefaultWorkspaceID *SubResource `json:"defaultWorkspaceId,omitempty"` -} - -// FirewallPolicyLogAnalyticsWorkspace log Analytics Workspace for Firewall Policy Insights. -type FirewallPolicyLogAnalyticsWorkspace struct { - // Region - Region to configure the Workspace. - Region *string `json:"region,omitempty"` - // WorkspaceID - The workspace Id for Firewall Policy Insights. - WorkspaceID *SubResource `json:"workspaceId,omitempty"` -} - -// FirewallPolicyNatRuleCollection firewall Policy NAT Rule Collection. -type FirewallPolicyNatRuleCollection struct { - // Action - The action type of a Nat rule collection. - Action *FirewallPolicyNatRuleCollectionAction `json:"action,omitempty"` - // Rules - List of rules included in a rule collection. - Rules *[]BasicFirewallPolicyRule `json:"rules,omitempty"` - // Name - The name of the rule collection. - Name *string `json:"name,omitempty"` - // Priority - Priority of the Firewall Policy Rule Collection resource. - Priority *int32 `json:"priority,omitempty"` - // RuleCollectionType - Possible values include: 'RuleCollectionTypeFirewallPolicyRuleCollection', 'RuleCollectionTypeFirewallPolicyNatRuleCollection', 'RuleCollectionTypeFirewallPolicyFilterRuleCollection' - RuleCollectionType RuleCollectionType `json:"ruleCollectionType,omitempty"` -} - -// MarshalJSON is the custom marshaler for FirewallPolicyNatRuleCollection. -func (fpnrc FirewallPolicyNatRuleCollection) MarshalJSON() ([]byte, error) { - fpnrc.RuleCollectionType = RuleCollectionTypeFirewallPolicyNatRuleCollection - objectMap := make(map[string]interface{}) - if fpnrc.Action != nil { - objectMap["action"] = fpnrc.Action - } - if fpnrc.Rules != nil { - objectMap["rules"] = fpnrc.Rules - } - if fpnrc.Name != nil { - objectMap["name"] = fpnrc.Name - } - if fpnrc.Priority != nil { - objectMap["priority"] = fpnrc.Priority - } - if fpnrc.RuleCollectionType != "" { - objectMap["ruleCollectionType"] = fpnrc.RuleCollectionType - } - return json.Marshal(objectMap) -} - -// AsFirewallPolicyNatRuleCollection is the BasicFirewallPolicyRuleCollection implementation for FirewallPolicyNatRuleCollection. -func (fpnrc FirewallPolicyNatRuleCollection) AsFirewallPolicyNatRuleCollection() (*FirewallPolicyNatRuleCollection, bool) { - return &fpnrc, true -} - -// AsFirewallPolicyFilterRuleCollection is the BasicFirewallPolicyRuleCollection implementation for FirewallPolicyNatRuleCollection. -func (fpnrc FirewallPolicyNatRuleCollection) AsFirewallPolicyFilterRuleCollection() (*FirewallPolicyFilterRuleCollection, bool) { - return nil, false -} - -// AsFirewallPolicyRuleCollection is the BasicFirewallPolicyRuleCollection implementation for FirewallPolicyNatRuleCollection. -func (fpnrc FirewallPolicyNatRuleCollection) AsFirewallPolicyRuleCollection() (*FirewallPolicyRuleCollection, bool) { - return nil, false -} - -// AsBasicFirewallPolicyRuleCollection is the BasicFirewallPolicyRuleCollection implementation for FirewallPolicyNatRuleCollection. -func (fpnrc FirewallPolicyNatRuleCollection) AsBasicFirewallPolicyRuleCollection() (BasicFirewallPolicyRuleCollection, bool) { - return &fpnrc, true -} - -// UnmarshalJSON is the custom unmarshaler for FirewallPolicyNatRuleCollection struct. -func (fpnrc *FirewallPolicyNatRuleCollection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "action": - if v != nil { - var action FirewallPolicyNatRuleCollectionAction - err = json.Unmarshal(*v, &action) - if err != nil { - return err - } - fpnrc.Action = &action - } - case "rules": - if v != nil { - rules, err := unmarshalBasicFirewallPolicyRuleArray(*v) - if err != nil { - return err - } - fpnrc.Rules = &rules - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - fpnrc.Name = &name - } - case "priority": - if v != nil { - var priority int32 - err = json.Unmarshal(*v, &priority) - if err != nil { - return err - } - fpnrc.Priority = &priority - } - case "ruleCollectionType": - if v != nil { - var ruleCollectionType RuleCollectionType - err = json.Unmarshal(*v, &ruleCollectionType) - if err != nil { - return err - } - fpnrc.RuleCollectionType = ruleCollectionType - } - } - } - - return nil -} - -// FirewallPolicyNatRuleCollectionAction properties of the FirewallPolicyNatRuleCollectionAction. -type FirewallPolicyNatRuleCollectionAction struct { - // Type - The type of action. Possible values include: 'DNAT' - Type FirewallPolicyNatRuleCollectionActionType `json:"type,omitempty"` -} - -// FirewallPolicyPropertiesFormat firewall Policy definition. -type FirewallPolicyPropertiesFormat struct { - // RuleCollectionGroups - READ-ONLY; List of references to FirewallPolicyRuleCollectionGroups. - RuleCollectionGroups *[]SubResource `json:"ruleCollectionGroups,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the firewall policy resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // BasePolicy - The parent firewall policy from which rules are inherited. - BasePolicy *SubResource `json:"basePolicy,omitempty"` - // Firewalls - READ-ONLY; List of references to Azure Firewalls that this Firewall Policy is associated with. - Firewalls *[]SubResource `json:"firewalls,omitempty"` - // ChildPolicies - READ-ONLY; List of references to Child Firewall Policies. - ChildPolicies *[]SubResource `json:"childPolicies,omitempty"` - // ThreatIntelMode - The operation mode for Threat Intelligence. Possible values include: 'AzureFirewallThreatIntelModeAlert', 'AzureFirewallThreatIntelModeDeny', 'AzureFirewallThreatIntelModeOff' - ThreatIntelMode AzureFirewallThreatIntelMode `json:"threatIntelMode,omitempty"` - // ThreatIntelWhitelist - ThreatIntel Whitelist for Firewall Policy. - ThreatIntelWhitelist *FirewallPolicyThreatIntelWhitelist `json:"threatIntelWhitelist,omitempty"` - // Insights - Insights on Firewall Policy. - Insights *FirewallPolicyInsights `json:"insights,omitempty"` - // Snat - The private IP addresses/IP ranges to which traffic will not be SNAT. - Snat *FirewallPolicySNAT `json:"snat,omitempty"` - // SQL - SQL Settings definition. - SQL *FirewallPolicySQL `json:"sql,omitempty"` - // DNSSettings - DNS Proxy Settings definition. - DNSSettings *DNSSettings `json:"dnsSettings,omitempty"` - // ExplicitProxy - Explicit Proxy Settings definition. - ExplicitProxy *ExplicitProxy `json:"explicitProxy,omitempty"` - // IntrusionDetection - The configuration for Intrusion detection. - IntrusionDetection *FirewallPolicyIntrusionDetection `json:"intrusionDetection,omitempty"` - // TransportSecurity - TLS Configuration definition. - TransportSecurity *FirewallPolicyTransportSecurity `json:"transportSecurity,omitempty"` - // Sku - The Firewall Policy SKU. - Sku *FirewallPolicySku `json:"sku,omitempty"` -} - -// MarshalJSON is the custom marshaler for FirewallPolicyPropertiesFormat. -func (fppf FirewallPolicyPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if fppf.BasePolicy != nil { - objectMap["basePolicy"] = fppf.BasePolicy - } - if fppf.ThreatIntelMode != "" { - objectMap["threatIntelMode"] = fppf.ThreatIntelMode - } - if fppf.ThreatIntelWhitelist != nil { - objectMap["threatIntelWhitelist"] = fppf.ThreatIntelWhitelist - } - if fppf.Insights != nil { - objectMap["insights"] = fppf.Insights - } - if fppf.Snat != nil { - objectMap["snat"] = fppf.Snat - } - if fppf.SQL != nil { - objectMap["sql"] = fppf.SQL - } - if fppf.DNSSettings != nil { - objectMap["dnsSettings"] = fppf.DNSSettings - } - if fppf.ExplicitProxy != nil { - objectMap["explicitProxy"] = fppf.ExplicitProxy - } - if fppf.IntrusionDetection != nil { - objectMap["intrusionDetection"] = fppf.IntrusionDetection - } - if fppf.TransportSecurity != nil { - objectMap["transportSecurity"] = fppf.TransportSecurity - } - if fppf.Sku != nil { - objectMap["sku"] = fppf.Sku - } - return json.Marshal(objectMap) -} - -// BasicFirewallPolicyRule properties of a rule. -type BasicFirewallPolicyRule interface { - AsApplicationRule() (*ApplicationRule, bool) - AsNatRule() (*NatRule, bool) - AsRule() (*Rule, bool) - AsFirewallPolicyRule() (*FirewallPolicyRule, bool) -} - -// FirewallPolicyRule properties of a rule. -type FirewallPolicyRule struct { - // Name - Name of the rule. - Name *string `json:"name,omitempty"` - // Description - Description of the rule. - Description *string `json:"description,omitempty"` - // RuleType - Possible values include: 'RuleTypeFirewallPolicyRule', 'RuleTypeApplicationRule', 'RuleTypeNatRule', 'RuleTypeNetworkRule' - RuleType RuleType `json:"ruleType,omitempty"` -} - -func unmarshalBasicFirewallPolicyRule(body []byte) (BasicFirewallPolicyRule, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["ruleType"] { - case string(RuleTypeApplicationRule): - var ar ApplicationRule - err := json.Unmarshal(body, &ar) - return ar, err - case string(RuleTypeNatRule): - var nr NatRule - err := json.Unmarshal(body, &nr) - return nr, err - case string(RuleTypeNetworkRule): - var r Rule - err := json.Unmarshal(body, &r) - return r, err - default: - var fpr FirewallPolicyRule - err := json.Unmarshal(body, &fpr) - return fpr, err - } -} -func unmarshalBasicFirewallPolicyRuleArray(body []byte) ([]BasicFirewallPolicyRule, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - fprArray := make([]BasicFirewallPolicyRule, len(rawMessages)) - - for index, rawMessage := range rawMessages { - fpr, err := unmarshalBasicFirewallPolicyRule(*rawMessage) - if err != nil { - return nil, err - } - fprArray[index] = fpr - } - return fprArray, nil -} - -// MarshalJSON is the custom marshaler for FirewallPolicyRule. -func (fpr FirewallPolicyRule) MarshalJSON() ([]byte, error) { - fpr.RuleType = RuleTypeFirewallPolicyRule - objectMap := make(map[string]interface{}) - if fpr.Name != nil { - objectMap["name"] = fpr.Name - } - if fpr.Description != nil { - objectMap["description"] = fpr.Description - } - if fpr.RuleType != "" { - objectMap["ruleType"] = fpr.RuleType - } - return json.Marshal(objectMap) -} - -// AsApplicationRule is the BasicFirewallPolicyRule implementation for FirewallPolicyRule. -func (fpr FirewallPolicyRule) AsApplicationRule() (*ApplicationRule, bool) { - return nil, false -} - -// AsNatRule is the BasicFirewallPolicyRule implementation for FirewallPolicyRule. -func (fpr FirewallPolicyRule) AsNatRule() (*NatRule, bool) { - return nil, false -} - -// AsRule is the BasicFirewallPolicyRule implementation for FirewallPolicyRule. -func (fpr FirewallPolicyRule) AsRule() (*Rule, bool) { - return nil, false -} - -// AsFirewallPolicyRule is the BasicFirewallPolicyRule implementation for FirewallPolicyRule. -func (fpr FirewallPolicyRule) AsFirewallPolicyRule() (*FirewallPolicyRule, bool) { - return &fpr, true -} - -// AsBasicFirewallPolicyRule is the BasicFirewallPolicyRule implementation for FirewallPolicyRule. -func (fpr FirewallPolicyRule) AsBasicFirewallPolicyRule() (BasicFirewallPolicyRule, bool) { - return &fpr, true -} - -// FirewallPolicyRuleApplicationProtocol properties of the application rule protocol. -type FirewallPolicyRuleApplicationProtocol struct { - // ProtocolType - Protocol type. Possible values include: 'FirewallPolicyRuleApplicationProtocolTypeHTTP', 'FirewallPolicyRuleApplicationProtocolTypeHTTPS' - ProtocolType FirewallPolicyRuleApplicationProtocolType `json:"protocolType,omitempty"` - // Port - Port number for the protocol, cannot be greater than 64000. - Port *int32 `json:"port,omitempty"` -} - -// BasicFirewallPolicyRuleCollection properties of the rule collection. -type BasicFirewallPolicyRuleCollection interface { - AsFirewallPolicyNatRuleCollection() (*FirewallPolicyNatRuleCollection, bool) - AsFirewallPolicyFilterRuleCollection() (*FirewallPolicyFilterRuleCollection, bool) - AsFirewallPolicyRuleCollection() (*FirewallPolicyRuleCollection, bool) -} - -// FirewallPolicyRuleCollection properties of the rule collection. -type FirewallPolicyRuleCollection struct { - // Name - The name of the rule collection. - Name *string `json:"name,omitempty"` - // Priority - Priority of the Firewall Policy Rule Collection resource. - Priority *int32 `json:"priority,omitempty"` - // RuleCollectionType - Possible values include: 'RuleCollectionTypeFirewallPolicyRuleCollection', 'RuleCollectionTypeFirewallPolicyNatRuleCollection', 'RuleCollectionTypeFirewallPolicyFilterRuleCollection' - RuleCollectionType RuleCollectionType `json:"ruleCollectionType,omitempty"` -} - -func unmarshalBasicFirewallPolicyRuleCollection(body []byte) (BasicFirewallPolicyRuleCollection, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["ruleCollectionType"] { - case string(RuleCollectionTypeFirewallPolicyNatRuleCollection): - var fpnrc FirewallPolicyNatRuleCollection - err := json.Unmarshal(body, &fpnrc) - return fpnrc, err - case string(RuleCollectionTypeFirewallPolicyFilterRuleCollection): - var fpfrc FirewallPolicyFilterRuleCollection - err := json.Unmarshal(body, &fpfrc) - return fpfrc, err - default: - var fprc FirewallPolicyRuleCollection - err := json.Unmarshal(body, &fprc) - return fprc, err - } -} -func unmarshalBasicFirewallPolicyRuleCollectionArray(body []byte) ([]BasicFirewallPolicyRuleCollection, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - fprcArray := make([]BasicFirewallPolicyRuleCollection, len(rawMessages)) - - for index, rawMessage := range rawMessages { - fprc, err := unmarshalBasicFirewallPolicyRuleCollection(*rawMessage) - if err != nil { - return nil, err - } - fprcArray[index] = fprc - } - return fprcArray, nil -} - -// MarshalJSON is the custom marshaler for FirewallPolicyRuleCollection. -func (fprc FirewallPolicyRuleCollection) MarshalJSON() ([]byte, error) { - fprc.RuleCollectionType = RuleCollectionTypeFirewallPolicyRuleCollection - objectMap := make(map[string]interface{}) - if fprc.Name != nil { - objectMap["name"] = fprc.Name - } - if fprc.Priority != nil { - objectMap["priority"] = fprc.Priority - } - if fprc.RuleCollectionType != "" { - objectMap["ruleCollectionType"] = fprc.RuleCollectionType - } - return json.Marshal(objectMap) -} - -// AsFirewallPolicyNatRuleCollection is the BasicFirewallPolicyRuleCollection implementation for FirewallPolicyRuleCollection. -func (fprc FirewallPolicyRuleCollection) AsFirewallPolicyNatRuleCollection() (*FirewallPolicyNatRuleCollection, bool) { - return nil, false -} - -// AsFirewallPolicyFilterRuleCollection is the BasicFirewallPolicyRuleCollection implementation for FirewallPolicyRuleCollection. -func (fprc FirewallPolicyRuleCollection) AsFirewallPolicyFilterRuleCollection() (*FirewallPolicyFilterRuleCollection, bool) { - return nil, false -} - -// AsFirewallPolicyRuleCollection is the BasicFirewallPolicyRuleCollection implementation for FirewallPolicyRuleCollection. -func (fprc FirewallPolicyRuleCollection) AsFirewallPolicyRuleCollection() (*FirewallPolicyRuleCollection, bool) { - return &fprc, true -} - -// AsBasicFirewallPolicyRuleCollection is the BasicFirewallPolicyRuleCollection implementation for FirewallPolicyRuleCollection. -func (fprc FirewallPolicyRuleCollection) AsBasicFirewallPolicyRuleCollection() (BasicFirewallPolicyRuleCollection, bool) { - return &fprc, true -} - -// FirewallPolicyRuleCollectionGroup rule Collection Group resource. -type FirewallPolicyRuleCollectionGroup struct { - autorest.Response `json:"-"` - // FirewallPolicyRuleCollectionGroupProperties - The properties of the firewall policy rule collection group. - *FirewallPolicyRuleCollectionGroupProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Rule Group type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for FirewallPolicyRuleCollectionGroup. -func (fprcg FirewallPolicyRuleCollectionGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if fprcg.FirewallPolicyRuleCollectionGroupProperties != nil { - objectMap["properties"] = fprcg.FirewallPolicyRuleCollectionGroupProperties - } - if fprcg.Name != nil { - objectMap["name"] = fprcg.Name - } - if fprcg.ID != nil { - objectMap["id"] = fprcg.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for FirewallPolicyRuleCollectionGroup struct. -func (fprcg *FirewallPolicyRuleCollectionGroup) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var firewallPolicyRuleCollectionGroupProperties FirewallPolicyRuleCollectionGroupProperties - err = json.Unmarshal(*v, &firewallPolicyRuleCollectionGroupProperties) - if err != nil { - return err - } - fprcg.FirewallPolicyRuleCollectionGroupProperties = &firewallPolicyRuleCollectionGroupProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - fprcg.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - fprcg.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - fprcg.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - fprcg.ID = &ID - } - } - } - - return nil -} - -// FirewallPolicyRuleCollectionGroupListResult response for ListFirewallPolicyRuleCollectionGroups API -// service call. -type FirewallPolicyRuleCollectionGroupListResult struct { - autorest.Response `json:"-"` - // Value - List of FirewallPolicyRuleCollectionGroups in a FirewallPolicy. - Value *[]FirewallPolicyRuleCollectionGroup `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// FirewallPolicyRuleCollectionGroupListResultIterator provides access to a complete listing of -// FirewallPolicyRuleCollectionGroup values. -type FirewallPolicyRuleCollectionGroupListResultIterator struct { - i int - page FirewallPolicyRuleCollectionGroupListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *FirewallPolicyRuleCollectionGroupListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyRuleCollectionGroupListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *FirewallPolicyRuleCollectionGroupListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter FirewallPolicyRuleCollectionGroupListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter FirewallPolicyRuleCollectionGroupListResultIterator) Response() FirewallPolicyRuleCollectionGroupListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter FirewallPolicyRuleCollectionGroupListResultIterator) Value() FirewallPolicyRuleCollectionGroup { - if !iter.page.NotDone() { - return FirewallPolicyRuleCollectionGroup{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the FirewallPolicyRuleCollectionGroupListResultIterator type. -func NewFirewallPolicyRuleCollectionGroupListResultIterator(page FirewallPolicyRuleCollectionGroupListResultPage) FirewallPolicyRuleCollectionGroupListResultIterator { - return FirewallPolicyRuleCollectionGroupListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (fprcglr FirewallPolicyRuleCollectionGroupListResult) IsEmpty() bool { - return fprcglr.Value == nil || len(*fprcglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (fprcglr FirewallPolicyRuleCollectionGroupListResult) hasNextLink() bool { - return fprcglr.NextLink != nil && len(*fprcglr.NextLink) != 0 -} - -// firewallPolicyRuleCollectionGroupListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (fprcglr FirewallPolicyRuleCollectionGroupListResult) firewallPolicyRuleCollectionGroupListResultPreparer(ctx context.Context) (*http.Request, error) { - if !fprcglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(fprcglr.NextLink))) -} - -// FirewallPolicyRuleCollectionGroupListResultPage contains a page of FirewallPolicyRuleCollectionGroup -// values. -type FirewallPolicyRuleCollectionGroupListResultPage struct { - fn func(context.Context, FirewallPolicyRuleCollectionGroupListResult) (FirewallPolicyRuleCollectionGroupListResult, error) - fprcglr FirewallPolicyRuleCollectionGroupListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *FirewallPolicyRuleCollectionGroupListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FirewallPolicyRuleCollectionGroupListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.fprcglr) - if err != nil { - return err - } - page.fprcglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *FirewallPolicyRuleCollectionGroupListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page FirewallPolicyRuleCollectionGroupListResultPage) NotDone() bool { - return !page.fprcglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page FirewallPolicyRuleCollectionGroupListResultPage) Response() FirewallPolicyRuleCollectionGroupListResult { - return page.fprcglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page FirewallPolicyRuleCollectionGroupListResultPage) Values() []FirewallPolicyRuleCollectionGroup { - if page.fprcglr.IsEmpty() { - return nil - } - return *page.fprcglr.Value -} - -// Creates a new instance of the FirewallPolicyRuleCollectionGroupListResultPage type. -func NewFirewallPolicyRuleCollectionGroupListResultPage(cur FirewallPolicyRuleCollectionGroupListResult, getNextPage func(context.Context, FirewallPolicyRuleCollectionGroupListResult) (FirewallPolicyRuleCollectionGroupListResult, error)) FirewallPolicyRuleCollectionGroupListResultPage { - return FirewallPolicyRuleCollectionGroupListResultPage{ - fn: getNextPage, - fprcglr: cur, - } -} - -// FirewallPolicyRuleCollectionGroupProperties properties of the rule collection group. -type FirewallPolicyRuleCollectionGroupProperties struct { - // Priority - Priority of the Firewall Policy Rule Collection Group resource. - Priority *int32 `json:"priority,omitempty"` - // RuleCollections - Group of Firewall Policy rule collections. - RuleCollections *[]BasicFirewallPolicyRuleCollection `json:"ruleCollections,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the firewall policy rule collection group resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for FirewallPolicyRuleCollectionGroupProperties. -func (fprcgp FirewallPolicyRuleCollectionGroupProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if fprcgp.Priority != nil { - objectMap["priority"] = fprcgp.Priority - } - if fprcgp.RuleCollections != nil { - objectMap["ruleCollections"] = fprcgp.RuleCollections - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for FirewallPolicyRuleCollectionGroupProperties struct. -func (fprcgp *FirewallPolicyRuleCollectionGroupProperties) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "priority": - if v != nil { - var priority int32 - err = json.Unmarshal(*v, &priority) - if err != nil { - return err - } - fprcgp.Priority = &priority - } - case "ruleCollections": - if v != nil { - ruleCollections, err := unmarshalBasicFirewallPolicyRuleCollectionArray(*v) - if err != nil { - return err - } - fprcgp.RuleCollections = &ruleCollections - } - case "provisioningState": - if v != nil { - var provisioningState ProvisioningState - err = json.Unmarshal(*v, &provisioningState) - if err != nil { - return err - } - fprcgp.ProvisioningState = provisioningState - } - } - } - - return nil -} - -// FirewallPolicyRuleCollectionGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type FirewallPolicyRuleCollectionGroupsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(FirewallPolicyRuleCollectionGroupsClient) (FirewallPolicyRuleCollectionGroup, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *FirewallPolicyRuleCollectionGroupsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for FirewallPolicyRuleCollectionGroupsCreateOrUpdateFuture.Result. -func (future *FirewallPolicyRuleCollectionGroupsCreateOrUpdateFuture) result(client FirewallPolicyRuleCollectionGroupsClient) (fprcg FirewallPolicyRuleCollectionGroup, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - fprcg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.FirewallPolicyRuleCollectionGroupsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if fprcg.Response.Response, err = future.GetResult(sender); err == nil && fprcg.Response.Response.StatusCode != http.StatusNoContent { - fprcg, err = client.CreateOrUpdateResponder(fprcg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsCreateOrUpdateFuture", "Result", fprcg.Response.Response, "Failure responding to request") - } - } - return -} - -// FirewallPolicyRuleCollectionGroupsDeleteFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type FirewallPolicyRuleCollectionGroupsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(FirewallPolicyRuleCollectionGroupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *FirewallPolicyRuleCollectionGroupsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for FirewallPolicyRuleCollectionGroupsDeleteFuture.Result. -func (future *FirewallPolicyRuleCollectionGroupsDeleteFuture) result(client FirewallPolicyRuleCollectionGroupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FirewallPolicyRuleCollectionGroupsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.FirewallPolicyRuleCollectionGroupsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// FirewallPolicySku SKU of Firewall policy. -type FirewallPolicySku struct { - // Tier - Tier of Firewall Policy. Possible values include: 'FirewallPolicySkuTierStandard', 'FirewallPolicySkuTierPremium', 'FirewallPolicySkuTierBasic' - Tier FirewallPolicySkuTier `json:"tier,omitempty"` -} - -// FirewallPolicySNAT the private IP addresses/IP ranges to which traffic will not be SNAT. -type FirewallPolicySNAT struct { - // PrivateRanges - List of private IP addresses/IP address ranges to not be SNAT. - PrivateRanges *[]string `json:"privateRanges,omitempty"` - // AutoLearnPrivateRanges - The operation mode for automatically learning private ranges to not be SNAT. Possible values include: 'AutoLearnPrivateRangesModeEnabled', 'AutoLearnPrivateRangesModeDisabled' - AutoLearnPrivateRanges AutoLearnPrivateRangesMode `json:"autoLearnPrivateRanges,omitempty"` -} - -// FirewallPolicySQL SQL Settings in Firewall Policy. -type FirewallPolicySQL struct { - // AllowSQLRedirect - A flag to indicate if SQL Redirect traffic filtering is enabled. Turning on the flag requires no rule using port 11000-11999. - AllowSQLRedirect *bool `json:"allowSqlRedirect,omitempty"` -} - -// FirewallPolicyThreatIntelWhitelist threatIntel Whitelist for Firewall Policy. -type FirewallPolicyThreatIntelWhitelist struct { - // IPAddresses - List of IP addresses for the ThreatIntel Whitelist. - IPAddresses *[]string `json:"ipAddresses,omitempty"` - // Fqdns - List of FQDNs for the ThreatIntel Whitelist. - Fqdns *[]string `json:"fqdns,omitempty"` -} - -// FirewallPolicyTransportSecurity configuration needed to perform TLS termination & initiation. -type FirewallPolicyTransportSecurity struct { - // CertificateAuthority - The CA used for intermediate CA generation. - CertificateAuthority *FirewallPolicyCertificateAuthority `json:"certificateAuthority,omitempty"` -} - -// FlowLog a flow log resource. -type FlowLog struct { - autorest.Response `json:"-"` - // FlowLogPropertiesFormat - Properties of the flow log. - *FlowLogPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for FlowLog. -func (fl FlowLog) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if fl.FlowLogPropertiesFormat != nil { - objectMap["properties"] = fl.FlowLogPropertiesFormat - } - if fl.ID != nil { - objectMap["id"] = fl.ID - } - if fl.Location != nil { - objectMap["location"] = fl.Location - } - if fl.Tags != nil { - objectMap["tags"] = fl.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for FlowLog struct. -func (fl *FlowLog) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var flowLogPropertiesFormat FlowLogPropertiesFormat - err = json.Unmarshal(*v, &flowLogPropertiesFormat) - if err != nil { - return err - } - fl.FlowLogPropertiesFormat = &flowLogPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - fl.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - fl.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - fl.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - fl.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - fl.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - fl.Tags = tags - } - } - } - - return nil -} - -// FlowLogFormatParameters parameters that define the flow log format. -type FlowLogFormatParameters struct { - // Type - The file type of flow log. Possible values include: 'JSON' - Type FlowLogFormatType `json:"type,omitempty"` - // Version - The version (revision) of the flow log. - Version *int32 `json:"version,omitempty"` -} - -// FlowLogInformation information on the configuration of flow log and traffic analytics (optional) . -type FlowLogInformation struct { - autorest.Response `json:"-"` - // TargetResourceID - The ID of the resource to configure for flow log and traffic analytics (optional) . - TargetResourceID *string `json:"targetResourceId,omitempty"` - // FlowLogProperties - Properties of the flow log. - *FlowLogProperties `json:"properties,omitempty"` - // FlowAnalyticsConfiguration - Parameters that define the configuration of traffic analytics. - FlowAnalyticsConfiguration *TrafficAnalyticsProperties `json:"flowAnalyticsConfiguration,omitempty"` -} - -// MarshalJSON is the custom marshaler for FlowLogInformation. -func (fli FlowLogInformation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if fli.TargetResourceID != nil { - objectMap["targetResourceId"] = fli.TargetResourceID - } - if fli.FlowLogProperties != nil { - objectMap["properties"] = fli.FlowLogProperties - } - if fli.FlowAnalyticsConfiguration != nil { - objectMap["flowAnalyticsConfiguration"] = fli.FlowAnalyticsConfiguration - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for FlowLogInformation struct. -func (fli *FlowLogInformation) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "targetResourceId": - if v != nil { - var targetResourceID string - err = json.Unmarshal(*v, &targetResourceID) - if err != nil { - return err - } - fli.TargetResourceID = &targetResourceID - } - case "properties": - if v != nil { - var flowLogProperties FlowLogProperties - err = json.Unmarshal(*v, &flowLogProperties) - if err != nil { - return err - } - fli.FlowLogProperties = &flowLogProperties - } - case "flowAnalyticsConfiguration": - if v != nil { - var flowAnalyticsConfiguration TrafficAnalyticsProperties - err = json.Unmarshal(*v, &flowAnalyticsConfiguration) - if err != nil { - return err - } - fli.FlowAnalyticsConfiguration = &flowAnalyticsConfiguration - } - } - } - - return nil -} - -// FlowLogListResult list of flow logs. -type FlowLogListResult struct { - autorest.Response `json:"-"` - // Value - Information about flow log resource. - Value *[]FlowLog `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for FlowLogListResult. -func (fllr FlowLogListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if fllr.Value != nil { - objectMap["value"] = fllr.Value - } - return json.Marshal(objectMap) -} - -// FlowLogListResultIterator provides access to a complete listing of FlowLog values. -type FlowLogListResultIterator struct { - i int - page FlowLogListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *FlowLogListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FlowLogListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *FlowLogListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter FlowLogListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter FlowLogListResultIterator) Response() FlowLogListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter FlowLogListResultIterator) Value() FlowLog { - if !iter.page.NotDone() { - return FlowLog{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the FlowLogListResultIterator type. -func NewFlowLogListResultIterator(page FlowLogListResultPage) FlowLogListResultIterator { - return FlowLogListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (fllr FlowLogListResult) IsEmpty() bool { - return fllr.Value == nil || len(*fllr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (fllr FlowLogListResult) hasNextLink() bool { - return fllr.NextLink != nil && len(*fllr.NextLink) != 0 -} - -// flowLogListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (fllr FlowLogListResult) flowLogListResultPreparer(ctx context.Context) (*http.Request, error) { - if !fllr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(fllr.NextLink))) -} - -// FlowLogListResultPage contains a page of FlowLog values. -type FlowLogListResultPage struct { - fn func(context.Context, FlowLogListResult) (FlowLogListResult, error) - fllr FlowLogListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *FlowLogListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/FlowLogListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.fllr) - if err != nil { - return err - } - page.fllr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *FlowLogListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page FlowLogListResultPage) NotDone() bool { - return !page.fllr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page FlowLogListResultPage) Response() FlowLogListResult { - return page.fllr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page FlowLogListResultPage) Values() []FlowLog { - if page.fllr.IsEmpty() { - return nil - } - return *page.fllr.Value -} - -// Creates a new instance of the FlowLogListResultPage type. -func NewFlowLogListResultPage(cur FlowLogListResult, getNextPage func(context.Context, FlowLogListResult) (FlowLogListResult, error)) FlowLogListResultPage { - return FlowLogListResultPage{ - fn: getNextPage, - fllr: cur, - } -} - -// FlowLogProperties parameters that define the configuration of flow log. -type FlowLogProperties struct { - // StorageID - ID of the storage account which is used to store the flow log. - StorageID *string `json:"storageId,omitempty"` - // Enabled - Flag to enable/disable flow logging. - Enabled *bool `json:"enabled,omitempty"` - // RetentionPolicy - Parameters that define the retention policy for flow log. - RetentionPolicy *RetentionPolicyParameters `json:"retentionPolicy,omitempty"` - // Format - Parameters that define the flow log format. - Format *FlowLogFormatParameters `json:"format,omitempty"` -} - -// FlowLogPropertiesFormat parameters that define the configuration of flow log. -type FlowLogPropertiesFormat struct { - // TargetResourceID - ID of network security group to which flow log will be applied. - TargetResourceID *string `json:"targetResourceId,omitempty"` - // TargetResourceGUID - READ-ONLY; Guid of network security group to which flow log will be applied. - TargetResourceGUID *string `json:"targetResourceGuid,omitempty"` - // StorageID - ID of the storage account which is used to store the flow log. - StorageID *string `json:"storageId,omitempty"` - // Enabled - Flag to enable/disable flow logging. - Enabled *bool `json:"enabled,omitempty"` - // RetentionPolicy - Parameters that define the retention policy for flow log. - RetentionPolicy *RetentionPolicyParameters `json:"retentionPolicy,omitempty"` - // Format - Parameters that define the flow log format. - Format *FlowLogFormatParameters `json:"format,omitempty"` - // FlowAnalyticsConfiguration - Parameters that define the configuration of traffic analytics. - FlowAnalyticsConfiguration *TrafficAnalyticsProperties `json:"flowAnalyticsConfiguration,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the flow log. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for FlowLogPropertiesFormat. -func (flpf FlowLogPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if flpf.TargetResourceID != nil { - objectMap["targetResourceId"] = flpf.TargetResourceID - } - if flpf.StorageID != nil { - objectMap["storageId"] = flpf.StorageID - } - if flpf.Enabled != nil { - objectMap["enabled"] = flpf.Enabled - } - if flpf.RetentionPolicy != nil { - objectMap["retentionPolicy"] = flpf.RetentionPolicy - } - if flpf.Format != nil { - objectMap["format"] = flpf.Format - } - if flpf.FlowAnalyticsConfiguration != nil { - objectMap["flowAnalyticsConfiguration"] = flpf.FlowAnalyticsConfiguration - } - return json.Marshal(objectMap) -} - -// FlowLogsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type FlowLogsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(FlowLogsClient) (FlowLog, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *FlowLogsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for FlowLogsCreateOrUpdateFuture.Result. -func (future *FlowLogsCreateOrUpdateFuture) result(client FlowLogsClient) (fl FlowLog, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - fl.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.FlowLogsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if fl.Response.Response, err = future.GetResult(sender); err == nil && fl.Response.Response.StatusCode != http.StatusNoContent { - fl, err = client.CreateOrUpdateResponder(fl.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsCreateOrUpdateFuture", "Result", fl.Response.Response, "Failure responding to request") - } - } - return -} - -// FlowLogsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type FlowLogsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(FlowLogsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *FlowLogsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for FlowLogsDeleteFuture.Result. -func (future *FlowLogsDeleteFuture) result(client FlowLogsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.FlowLogsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.FlowLogsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// FlowLogStatusParameters parameters that define a resource to query flow log and traffic analytics -// (optional) status. -type FlowLogStatusParameters struct { - // TargetResourceID - The target resource where getting the flow log and traffic analytics (optional) status. - TargetResourceID *string `json:"targetResourceId,omitempty"` -} - -// FrontendIPConfiguration frontend IP address of the load balancer. -type FrontendIPConfiguration struct { - autorest.Response `json:"-"` - // FrontendIPConfigurationPropertiesFormat - Properties of the load balancer probe. - *FrontendIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within the set of frontend IP configurations used by the load balancer. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // Zones - A list of availability zones denoting the IP allocated for the resource needs to come from. - Zones *[]string `json:"zones,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for FrontendIPConfiguration. -func (fic FrontendIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if fic.FrontendIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = fic.FrontendIPConfigurationPropertiesFormat - } - if fic.Name != nil { - objectMap["name"] = fic.Name - } - if fic.Zones != nil { - objectMap["zones"] = fic.Zones - } - if fic.ID != nil { - objectMap["id"] = fic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for FrontendIPConfiguration struct. -func (fic *FrontendIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var frontendIPConfigurationPropertiesFormat FrontendIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &frontendIPConfigurationPropertiesFormat) - if err != nil { - return err - } - fic.FrontendIPConfigurationPropertiesFormat = &frontendIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - fic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - fic.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - fic.Type = &typeVar - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - fic.Zones = &zones - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - fic.ID = &ID - } - } - } - - return nil -} - -// FrontendIPConfigurationPropertiesFormat properties of Frontend IP Configuration of the load balancer. -type FrontendIPConfigurationPropertiesFormat struct { - // InboundNatRules - READ-ONLY; An array of references to inbound rules that use this frontend IP. - InboundNatRules *[]SubResource `json:"inboundNatRules,omitempty"` - // InboundNatPools - READ-ONLY; An array of references to inbound pools that use this frontend IP. - InboundNatPools *[]SubResource `json:"inboundNatPools,omitempty"` - // OutboundRules - READ-ONLY; An array of references to outbound rules that use this frontend IP. - OutboundRules *[]SubResource `json:"outboundRules,omitempty"` - // LoadBalancingRules - READ-ONLY; An array of references to load balancing rules that use this frontend IP. - LoadBalancingRules *[]SubResource `json:"loadBalancingRules,omitempty"` - // PrivateIPAddress - The private IP address of the IP configuration. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // PrivateIPAllocationMethod - The Private IP allocation method. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` - // PrivateIPAddressVersion - Whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values include: 'IPv4', 'IPv6' - PrivateIPAddressVersion IPVersion `json:"privateIPAddressVersion,omitempty"` - // Subnet - The reference to the subnet resource. - Subnet *Subnet `json:"subnet,omitempty"` - // PublicIPAddress - The reference to the Public IP resource. - PublicIPAddress *PublicIPAddress `json:"publicIPAddress,omitempty"` - // PublicIPPrefix - The reference to the Public IP Prefix resource. - PublicIPPrefix *SubResource `json:"publicIPPrefix,omitempty"` - // GatewayLoadBalancer - The reference to gateway load balancer frontend IP. - GatewayLoadBalancer *SubResource `json:"gatewayLoadBalancer,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the frontend IP configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for FrontendIPConfigurationPropertiesFormat. -func (ficpf FrontendIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ficpf.PrivateIPAddress != nil { - objectMap["privateIPAddress"] = ficpf.PrivateIPAddress - } - if ficpf.PrivateIPAllocationMethod != "" { - objectMap["privateIPAllocationMethod"] = ficpf.PrivateIPAllocationMethod - } - if ficpf.PrivateIPAddressVersion != "" { - objectMap["privateIPAddressVersion"] = ficpf.PrivateIPAddressVersion - } - if ficpf.Subnet != nil { - objectMap["subnet"] = ficpf.Subnet - } - if ficpf.PublicIPAddress != nil { - objectMap["publicIPAddress"] = ficpf.PublicIPAddress - } - if ficpf.PublicIPPrefix != nil { - objectMap["publicIPPrefix"] = ficpf.PublicIPPrefix - } - if ficpf.GatewayLoadBalancer != nil { - objectMap["gatewayLoadBalancer"] = ficpf.GatewayLoadBalancer - } - return json.Marshal(objectMap) -} - -// GatewayCustomBgpIPAddressIPConfiguration gatewayCustomBgpIpAddressIpConfiguration for a virtual network -// gateway connection. -type GatewayCustomBgpIPAddressIPConfiguration struct { - // IPConfigurationID - The IpconfigurationId of ipconfiguration which belongs to gateway. - IPConfigurationID *string `json:"ipConfigurationId,omitempty"` - // CustomBgpIPAddress - The custom BgpPeeringAddress which belongs to IpconfigurationId. - CustomBgpIPAddress *string `json:"customBgpIpAddress,omitempty"` -} - -// GatewayLoadBalancerTunnelInterface gateway load balancer tunnel interface of a load balancer backend -// address pool. -type GatewayLoadBalancerTunnelInterface struct { - // Port - Port of gateway load balancer tunnel interface. - Port *int32 `json:"port,omitempty"` - // Identifier - Identifier of gateway load balancer tunnel interface. - Identifier *int32 `json:"identifier,omitempty"` - // Protocol - Protocol of gateway load balancer tunnel interface. Possible values include: 'GatewayLoadBalancerTunnelProtocolNone', 'GatewayLoadBalancerTunnelProtocolNative', 'GatewayLoadBalancerTunnelProtocolVXLAN' - Protocol GatewayLoadBalancerTunnelProtocol `json:"protocol,omitempty"` - // Type - Traffic type of gateway load balancer tunnel interface. Possible values include: 'GatewayLoadBalancerTunnelInterfaceTypeNone', 'GatewayLoadBalancerTunnelInterfaceTypeInternal', 'GatewayLoadBalancerTunnelInterfaceTypeExternal' - Type GatewayLoadBalancerTunnelInterfaceType `json:"type,omitempty"` -} - -// GatewayRoute gateway routing details. -type GatewayRoute struct { - // LocalAddress - READ-ONLY; The gateway's local address. - LocalAddress *string `json:"localAddress,omitempty"` - // NetworkProperty - READ-ONLY; The route's network prefix. - NetworkProperty *string `json:"network,omitempty"` - // NextHop - READ-ONLY; The route's next hop. - NextHop *string `json:"nextHop,omitempty"` - // SourcePeer - READ-ONLY; The peer this route was learned from. - SourcePeer *string `json:"sourcePeer,omitempty"` - // Origin - READ-ONLY; The source this route was learned from. - Origin *string `json:"origin,omitempty"` - // AsPath - READ-ONLY; The route's AS path sequence. - AsPath *string `json:"asPath,omitempty"` - // Weight - READ-ONLY; The route's weight. - Weight *int32 `json:"weight,omitempty"` -} - -// MarshalJSON is the custom marshaler for GatewayRoute. -func (gr GatewayRoute) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// GatewayRouteListResult list of virtual network gateway routes. -type GatewayRouteListResult struct { - autorest.Response `json:"-"` - // Value - List of gateway routes. - Value *[]GatewayRoute `json:"value,omitempty"` -} - -// GenerateExpressRoutePortsLOARequest the customer name to be printed on a letter of authorization. -type GenerateExpressRoutePortsLOARequest struct { - // CustomerName - The customer name. - CustomerName *string `json:"customerName,omitempty"` -} - -// GenerateExpressRoutePortsLOAResult response for GenerateExpressRoutePortsLOA API service call. -type GenerateExpressRoutePortsLOAResult struct { - autorest.Response `json:"-"` - // EncodedContent - The content as a base64 encoded string. - EncodedContent *string `json:"encodedContent,omitempty"` -} - -// GeneratevirtualwanvpnserverconfigurationvpnprofileFuture an abstraction for monitoring and retrieving -// the results of a long-running operation. -type GeneratevirtualwanvpnserverconfigurationvpnprofileFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BaseClient) (VpnProfileResponse, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GeneratevirtualwanvpnserverconfigurationvpnprofileFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GeneratevirtualwanvpnserverconfigurationvpnprofileFuture.Result. -func (future *GeneratevirtualwanvpnserverconfigurationvpnprofileFuture) result(client BaseClient) (vpr VpnProfileResponse, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GeneratevirtualwanvpnserverconfigurationvpnprofileFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vpr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.GeneratevirtualwanvpnserverconfigurationvpnprofileFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vpr.Response.Response, err = future.GetResult(sender); err == nil && vpr.Response.Response.StatusCode != http.StatusNoContent { - vpr, err = client.GeneratevirtualwanvpnserverconfigurationvpnprofileResponder(vpr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GeneratevirtualwanvpnserverconfigurationvpnprofileFuture", "Result", vpr.Response.Response, "Failure responding to request") - } - } - return -} - -// GetActiveSessionsAllFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type GetActiveSessionsAllFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BaseClient) (BastionActiveSessionListResultPage, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GetActiveSessionsAllFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GetActiveSessionsAllFuture.Result. -func (future *GetActiveSessionsAllFuture) result(client BaseClient) (baslrp BastionActiveSessionListResultPage, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GetActiveSessionsAllFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - baslrp.baslr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.GetActiveSessionsAllFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if baslrp.baslr.Response.Response, err = future.GetResult(sender); err == nil && baslrp.baslr.Response.Response.StatusCode != http.StatusNoContent { - baslrp, err = client.GetActiveSessionsResponder(baslrp.baslr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GetActiveSessionsAllFuture", "Result", baslrp.baslr.Response.Response, "Failure responding to request") - } - } - return -} - -// GetActiveSessionsFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type GetActiveSessionsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BaseClient) (BastionActiveSessionListResultPage, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GetActiveSessionsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GetActiveSessionsFuture.Result. -func (future *GetActiveSessionsFuture) result(client BaseClient) (baslrp BastionActiveSessionListResultPage, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GetActiveSessionsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - baslrp.baslr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.GetActiveSessionsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if baslrp.baslr.Response.Response, err = future.GetResult(sender); err == nil && baslrp.baslr.Response.Response.StatusCode != http.StatusNoContent { - baslrp, err = client.GetActiveSessionsResponder(baslrp.baslr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GetActiveSessionsFuture", "Result", baslrp.baslr.Response.Response, "Failure responding to request") - } - } - return -} - -// GetInboundRoutesParameters the parameters specifying the connection resource whose inbound routes are -// being requested. -type GetInboundRoutesParameters struct { - // ResourceURI - The connection resource whose inbound routes are being requested. - ResourceURI *string `json:"resourceUri,omitempty"` - // ConnectionType - The type of the specified connection resource like ExpressRouteConnection, HubVirtualNetworkConnection, VpnConnection and P2SConnection. - ConnectionType *string `json:"connectionType,omitempty"` -} - -// GetOutboundRoutesParameters the parameters specifying the connection resource whose outbound routes are -// being requested. -type GetOutboundRoutesParameters struct { - // ResourceURI - The connection resource whose outbound routes are being requested. - ResourceURI *string `json:"resourceUri,omitempty"` - // ConnectionType - The type of the specified connection resource like ExpressRouteConnection, HubVirtualNetworkConnection, VpnConnection and P2SConnection. - ConnectionType *string `json:"connectionType,omitempty"` -} - -// GetVpnSitesConfigurationRequest list of Vpn-Sites. -type GetVpnSitesConfigurationRequest struct { - // VpnSites - List of resource-ids of the vpn-sites for which config is to be downloaded. - VpnSites *[]string `json:"vpnSites,omitempty"` - // OutputBlobSasURL - The sas-url to download the configurations for vpn-sites. - OutputBlobSasURL *string `json:"outputBlobSasUrl,omitempty"` -} - -// Group the network group resource -type Group struct { - autorest.Response `json:"-"` - // GroupProperties - The Network Group properties - *GroupProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system metadata related to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for Group. -func (g Group) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if g.GroupProperties != nil { - objectMap["properties"] = g.GroupProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Group struct. -func (g *Group) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var groupProperties GroupProperties - err = json.Unmarshal(*v, &groupProperties) - if err != nil { - return err - } - g.GroupProperties = &groupProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - g.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - g.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - g.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - g.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - g.Etag = &etag - } - } - } - - return nil -} - -// GroupListResult result of the request to list NetworkGroup. It contains a list of groups and a URL link -// to get the next set of results. -type GroupListResult struct { - autorest.Response `json:"-"` - // Value - Gets a page of NetworkGroup - Value *[]Group `json:"value,omitempty"` - // NextLink - Gets the URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// GroupListResultIterator provides access to a complete listing of Group values. -type GroupListResultIterator struct { - i int - page GroupListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *GroupListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GroupListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *GroupListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter GroupListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter GroupListResultIterator) Response() GroupListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter GroupListResultIterator) Value() Group { - if !iter.page.NotDone() { - return Group{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the GroupListResultIterator type. -func NewGroupListResultIterator(page GroupListResultPage) GroupListResultIterator { - return GroupListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (glr GroupListResult) IsEmpty() bool { - return glr.Value == nil || len(*glr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (glr GroupListResult) hasNextLink() bool { - return glr.NextLink != nil && len(*glr.NextLink) != 0 -} - -// groupListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (glr GroupListResult) groupListResultPreparer(ctx context.Context) (*http.Request, error) { - if !glr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(glr.NextLink))) -} - -// GroupListResultPage contains a page of Group values. -type GroupListResultPage struct { - fn func(context.Context, GroupListResult) (GroupListResult, error) - glr GroupListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *GroupListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/GroupListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.glr) - if err != nil { - return err - } - page.glr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *GroupListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page GroupListResultPage) NotDone() bool { - return !page.glr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page GroupListResultPage) Response() GroupListResult { - return page.glr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page GroupListResultPage) Values() []Group { - if page.glr.IsEmpty() { - return nil - } - return *page.glr.Value -} - -// Creates a new instance of the GroupListResultPage type. -func NewGroupListResultPage(cur GroupListResult, getNextPage func(context.Context, GroupListResult) (GroupListResult, error)) GroupListResultPage { - return GroupListResultPage{ - fn: getNextPage, - glr: cur, - } -} - -// GroupProperties properties of network group -type GroupProperties struct { - // Description - A description of the network group. - Description *string `json:"description,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the scope assignment resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for GroupProperties. -func (gp GroupProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if gp.Description != nil { - objectMap["description"] = gp.Description - } - return json.Marshal(objectMap) -} - -// GroupsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type GroupsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(GroupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *GroupsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for GroupsDeleteFuture.Result. -func (future *GroupsDeleteFuture) result(client GroupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.GroupsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.GroupsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// HopLink hop link. -type HopLink struct { - // NextHopID - READ-ONLY; The ID of the next hop. - NextHopID *string `json:"nextHopId,omitempty"` - // LinkType - READ-ONLY; Link type. - LinkType *string `json:"linkType,omitempty"` - // HopLinkProperties - Hop link properties. - *HopLinkProperties `json:"properties,omitempty"` - // Issues - READ-ONLY; List of issues. - Issues *[]ConnectivityIssue `json:"issues,omitempty"` - // Context - READ-ONLY; Provides additional context on links. - Context map[string]*string `json:"context"` - // ResourceID - READ-ONLY; Resource ID. - ResourceID *string `json:"resourceId,omitempty"` -} - -// MarshalJSON is the custom marshaler for HopLink. -func (hl HopLink) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if hl.HopLinkProperties != nil { - objectMap["properties"] = hl.HopLinkProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for HopLink struct. -func (hl *HopLink) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "nextHopId": - if v != nil { - var nextHopID string - err = json.Unmarshal(*v, &nextHopID) - if err != nil { - return err - } - hl.NextHopID = &nextHopID - } - case "linkType": - if v != nil { - var linkType string - err = json.Unmarshal(*v, &linkType) - if err != nil { - return err - } - hl.LinkType = &linkType - } - case "properties": - if v != nil { - var hopLinkProperties HopLinkProperties - err = json.Unmarshal(*v, &hopLinkProperties) - if err != nil { - return err - } - hl.HopLinkProperties = &hopLinkProperties - } - case "issues": - if v != nil { - var issues []ConnectivityIssue - err = json.Unmarshal(*v, &issues) - if err != nil { - return err - } - hl.Issues = &issues - } - case "context": - if v != nil { - var context map[string]*string - err = json.Unmarshal(*v, &context) - if err != nil { - return err - } - hl.Context = context - } - case "resourceId": - if v != nil { - var resourceID string - err = json.Unmarshal(*v, &resourceID) - if err != nil { - return err - } - hl.ResourceID = &resourceID - } - } - } - - return nil -} - -// HopLinkProperties hop link properties. -type HopLinkProperties struct { - // RoundTripTimeMin - READ-ONLY; Minimum roundtrip time in milliseconds. - RoundTripTimeMin *int64 `json:"roundTripTimeMin,omitempty"` - // RoundTripTimeAvg - READ-ONLY; Average roundtrip time in milliseconds. - RoundTripTimeAvg *int64 `json:"roundTripTimeAvg,omitempty"` - // RoundTripTimeMax - READ-ONLY; Maximum roundtrip time in milliseconds. - RoundTripTimeMax *int64 `json:"roundTripTimeMax,omitempty"` -} - -// MarshalJSON is the custom marshaler for HopLinkProperties. -func (hlp HopLinkProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// HTTPConfiguration HTTP configuration of the connectivity check. -type HTTPConfiguration struct { - // Method - HTTP method. Possible values include: 'HTTPMethodGet' - Method HTTPMethod `json:"method,omitempty"` - // Headers - List of HTTP headers. - Headers *[]HTTPHeader `json:"headers,omitempty"` - // ValidStatusCodes - Valid status codes. - ValidStatusCodes *[]int32 `json:"validStatusCodes,omitempty"` -} - -// HTTPHeader the HTTP header. -type HTTPHeader struct { - // Name - The name in HTTP header. - Name *string `json:"name,omitempty"` - // Value - The value in HTTP header. - Value *string `json:"value,omitempty"` -} - -// Hub hub Item. -type Hub struct { - // ResourceID - Resource Id. - ResourceID *string `json:"resourceId,omitempty"` - // ResourceType - Resource Type. - ResourceType *string `json:"resourceType,omitempty"` -} - -// HubIPAddresses IP addresses associated with azure firewall. -type HubIPAddresses struct { - // PublicIPs - Public IP addresses associated with azure firewall. - PublicIPs *HubPublicIPAddresses `json:"publicIPs,omitempty"` - // PrivateIPAddress - Private IP Address associated with azure firewall. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` -} - -// HubIPConfiguration ipConfigurations. -type HubIPConfiguration struct { - autorest.Response `json:"-"` - // HubIPConfigurationPropertiesFormat - The properties of the Virtual Hub IPConfigurations. - *HubIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the Ip Configuration. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Ipconfiguration type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for HubIPConfiguration. -func (hic HubIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if hic.HubIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = hic.HubIPConfigurationPropertiesFormat - } - if hic.Name != nil { - objectMap["name"] = hic.Name - } - if hic.ID != nil { - objectMap["id"] = hic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for HubIPConfiguration struct. -func (hic *HubIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var hubIPConfigurationPropertiesFormat HubIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &hubIPConfigurationPropertiesFormat) - if err != nil { - return err - } - hic.HubIPConfigurationPropertiesFormat = &hubIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - hic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - hic.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - hic.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - hic.ID = &ID - } - } - } - - return nil -} - -// HubIPConfigurationPropertiesFormat properties of IP configuration. -type HubIPConfigurationPropertiesFormat struct { - // PrivateIPAddress - The private IP address of the IP configuration. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // PrivateIPAllocationMethod - The private IP address allocation method. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` - // Subnet - The reference to the subnet resource. - Subnet *Subnet `json:"subnet,omitempty"` - // PublicIPAddress - The reference to the public IP resource. - PublicIPAddress *PublicIPAddress `json:"publicIPAddress,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the IP configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for HubIPConfigurationPropertiesFormat. -func (hicpf HubIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if hicpf.PrivateIPAddress != nil { - objectMap["privateIPAddress"] = hicpf.PrivateIPAddress - } - if hicpf.PrivateIPAllocationMethod != "" { - objectMap["privateIPAllocationMethod"] = hicpf.PrivateIPAllocationMethod - } - if hicpf.Subnet != nil { - objectMap["subnet"] = hicpf.Subnet - } - if hicpf.PublicIPAddress != nil { - objectMap["publicIPAddress"] = hicpf.PublicIPAddress - } - return json.Marshal(objectMap) -} - -// HubPublicIPAddresses public IP addresses associated with azure firewall. -type HubPublicIPAddresses struct { - // Addresses - The list of Public IP addresses associated with azure firewall or IP addresses to be retained. - Addresses *[]AzureFirewallPublicIPAddress `json:"addresses,omitempty"` - // Count - The number of Public IP addresses associated with azure firewall. - Count *int32 `json:"count,omitempty"` -} - -// HubRoute routeTable route. -type HubRoute struct { - // Name - The name of the Route that is unique within a RouteTable. This name can be used to access this route. - Name *string `json:"name,omitempty"` - // DestinationType - The type of destinations (eg: CIDR, ResourceId, Service). - DestinationType *string `json:"destinationType,omitempty"` - // Destinations - List of all destinations. - Destinations *[]string `json:"destinations,omitempty"` - // NextHopType - The type of next hop (eg: ResourceId). - NextHopType *string `json:"nextHopType,omitempty"` - // NextHop - NextHop resource ID. - NextHop *string `json:"nextHop,omitempty"` -} - -// HubRouteTable routeTable resource in a virtual hub. -type HubRouteTable struct { - autorest.Response `json:"-"` - // HubRouteTableProperties - Properties of the RouteTable resource. - *HubRouteTableProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for HubRouteTable. -func (hrt HubRouteTable) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if hrt.HubRouteTableProperties != nil { - objectMap["properties"] = hrt.HubRouteTableProperties - } - if hrt.Name != nil { - objectMap["name"] = hrt.Name - } - if hrt.ID != nil { - objectMap["id"] = hrt.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for HubRouteTable struct. -func (hrt *HubRouteTable) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var hubRouteTableProperties HubRouteTableProperties - err = json.Unmarshal(*v, &hubRouteTableProperties) - if err != nil { - return err - } - hrt.HubRouteTableProperties = &hubRouteTableProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - hrt.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - hrt.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - hrt.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - hrt.ID = &ID - } - } - } - - return nil -} - -// HubRouteTableProperties parameters for RouteTable. -type HubRouteTableProperties struct { - // Routes - List of all routes. - Routes *[]HubRoute `json:"routes,omitempty"` - // Labels - List of labels associated with this route table. - Labels *[]string `json:"labels,omitempty"` - // AssociatedConnections - READ-ONLY; List of all connections associated with this route table. - AssociatedConnections *[]string `json:"associatedConnections,omitempty"` - // PropagatingConnections - READ-ONLY; List of all connections that advertise to this route table. - PropagatingConnections *[]string `json:"propagatingConnections,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the RouteTable resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for HubRouteTableProperties. -func (hrtp HubRouteTableProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if hrtp.Routes != nil { - objectMap["routes"] = hrtp.Routes - } - if hrtp.Labels != nil { - objectMap["labels"] = hrtp.Labels - } - return json.Marshal(objectMap) -} - -// HubRouteTablesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type HubRouteTablesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(HubRouteTablesClient) (HubRouteTable, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *HubRouteTablesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for HubRouteTablesCreateOrUpdateFuture.Result. -func (future *HubRouteTablesCreateOrUpdateFuture) result(client HubRouteTablesClient) (hrt HubRouteTable, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubRouteTablesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - hrt.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.HubRouteTablesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if hrt.Response.Response, err = future.GetResult(sender); err == nil && hrt.Response.Response.StatusCode != http.StatusNoContent { - hrt, err = client.CreateOrUpdateResponder(hrt.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubRouteTablesCreateOrUpdateFuture", "Result", hrt.Response.Response, "Failure responding to request") - } - } - return -} - -// HubRouteTablesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type HubRouteTablesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(HubRouteTablesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *HubRouteTablesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for HubRouteTablesDeleteFuture.Result. -func (future *HubRouteTablesDeleteFuture) result(client HubRouteTablesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubRouteTablesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.HubRouteTablesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// HubVirtualNetworkConnection hubVirtualNetworkConnection Resource. -type HubVirtualNetworkConnection struct { - autorest.Response `json:"-"` - // HubVirtualNetworkConnectionProperties - Properties of the hub virtual network connection. - *HubVirtualNetworkConnectionProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for HubVirtualNetworkConnection. -func (hvnc HubVirtualNetworkConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if hvnc.HubVirtualNetworkConnectionProperties != nil { - objectMap["properties"] = hvnc.HubVirtualNetworkConnectionProperties - } - if hvnc.Name != nil { - objectMap["name"] = hvnc.Name - } - if hvnc.ID != nil { - objectMap["id"] = hvnc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for HubVirtualNetworkConnection struct. -func (hvnc *HubVirtualNetworkConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var hubVirtualNetworkConnectionProperties HubVirtualNetworkConnectionProperties - err = json.Unmarshal(*v, &hubVirtualNetworkConnectionProperties) - if err != nil { - return err - } - hvnc.HubVirtualNetworkConnectionProperties = &hubVirtualNetworkConnectionProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - hvnc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - hvnc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - hvnc.ID = &ID - } - } - } - - return nil -} - -// HubVirtualNetworkConnectionProperties parameters for HubVirtualNetworkConnection. -type HubVirtualNetworkConnectionProperties struct { - // RemoteVirtualNetwork - Reference to the remote virtual network. - RemoteVirtualNetwork *SubResource `json:"remoteVirtualNetwork,omitempty"` - // AllowHubToRemoteVnetTransit - Deprecated: VirtualHub to RemoteVnet transit to enabled or not. - AllowHubToRemoteVnetTransit *bool `json:"allowHubToRemoteVnetTransit,omitempty"` - // AllowRemoteVnetToUseHubVnetGateways - Deprecated: Allow RemoteVnet to use Virtual Hub's gateways. - AllowRemoteVnetToUseHubVnetGateways *bool `json:"allowRemoteVnetToUseHubVnetGateways,omitempty"` - // EnableInternetSecurity - Enable internet security. - EnableInternetSecurity *bool `json:"enableInternetSecurity,omitempty"` - // RoutingConfiguration - The Routing Configuration indicating the associated and propagated route tables on this connection. - RoutingConfiguration *RoutingConfiguration `json:"routingConfiguration,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the hub virtual network connection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for HubVirtualNetworkConnectionProperties. -func (hvncp HubVirtualNetworkConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if hvncp.RemoteVirtualNetwork != nil { - objectMap["remoteVirtualNetwork"] = hvncp.RemoteVirtualNetwork - } - if hvncp.AllowHubToRemoteVnetTransit != nil { - objectMap["allowHubToRemoteVnetTransit"] = hvncp.AllowHubToRemoteVnetTransit - } - if hvncp.AllowRemoteVnetToUseHubVnetGateways != nil { - objectMap["allowRemoteVnetToUseHubVnetGateways"] = hvncp.AllowRemoteVnetToUseHubVnetGateways - } - if hvncp.EnableInternetSecurity != nil { - objectMap["enableInternetSecurity"] = hvncp.EnableInternetSecurity - } - if hvncp.RoutingConfiguration != nil { - objectMap["routingConfiguration"] = hvncp.RoutingConfiguration - } - return json.Marshal(objectMap) -} - -// HubVirtualNetworkConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type HubVirtualNetworkConnectionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(HubVirtualNetworkConnectionsClient) (HubVirtualNetworkConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *HubVirtualNetworkConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for HubVirtualNetworkConnectionsCreateOrUpdateFuture.Result. -func (future *HubVirtualNetworkConnectionsCreateOrUpdateFuture) result(client HubVirtualNetworkConnectionsClient) (hvnc HubVirtualNetworkConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - hvnc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.HubVirtualNetworkConnectionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if hvnc.Response.Response, err = future.GetResult(sender); err == nil && hvnc.Response.Response.StatusCode != http.StatusNoContent { - hvnc, err = client.CreateOrUpdateResponder(hvnc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsCreateOrUpdateFuture", "Result", hvnc.Response.Response, "Failure responding to request") - } - } - return -} - -// HubVirtualNetworkConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type HubVirtualNetworkConnectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(HubVirtualNetworkConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *HubVirtualNetworkConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for HubVirtualNetworkConnectionsDeleteFuture.Result. -func (future *HubVirtualNetworkConnectionsDeleteFuture) result(client HubVirtualNetworkConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.HubVirtualNetworkConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.HubVirtualNetworkConnectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// IDPSQueryObject will describe the query to run against the IDPS signatures DB -type IDPSQueryObject struct { - // Filters - Contain all filters names and values - Filters *[]FilterItems `json:"filters,omitempty"` - // Search - Search term in all columns - Search *string `json:"search,omitempty"` - // OrderBy - Column to sort response by - OrderBy *OrderBy `json:"orderBy,omitempty"` - // ResultsPerPage - The number of the results to return in each page - ResultsPerPage *int32 `json:"resultsPerPage,omitempty"` - // Skip - The number of records matching the filter to skip - Skip *int32 `json:"skip,omitempty"` -} - -// InboundNatPool inbound NAT pool of the load balancer. -type InboundNatPool struct { - // InboundNatPoolPropertiesFormat - Properties of load balancer inbound nat pool. - *InboundNatPoolPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within the set of inbound NAT pools used by the load balancer. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for InboundNatPool. -func (inp InboundNatPool) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if inp.InboundNatPoolPropertiesFormat != nil { - objectMap["properties"] = inp.InboundNatPoolPropertiesFormat - } - if inp.Name != nil { - objectMap["name"] = inp.Name - } - if inp.ID != nil { - objectMap["id"] = inp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for InboundNatPool struct. -func (inp *InboundNatPool) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var inboundNatPoolPropertiesFormat InboundNatPoolPropertiesFormat - err = json.Unmarshal(*v, &inboundNatPoolPropertiesFormat) - if err != nil { - return err - } - inp.InboundNatPoolPropertiesFormat = &inboundNatPoolPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - inp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - inp.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - inp.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - inp.ID = &ID - } - } - } - - return nil -} - -// InboundNatPoolPropertiesFormat properties of Inbound NAT pool. -type InboundNatPoolPropertiesFormat struct { - // FrontendIPConfiguration - A reference to frontend IP addresses. - FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` - // Protocol - The reference to the transport protocol used by the inbound NAT pool. Possible values include: 'TransportProtocolUDP', 'TransportProtocolTCP', 'TransportProtocolAll' - Protocol TransportProtocol `json:"protocol,omitempty"` - // FrontendPortRangeStart - The first port number in the range of external ports that will be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - FrontendPortRangeStart *int32 `json:"frontendPortRangeStart,omitempty"` - // FrontendPortRangeEnd - The last port number in the range of external ports that will be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - FrontendPortRangeEnd *int32 `json:"frontendPortRangeEnd,omitempty"` - // BackendPort - The port used for internal connections on the endpoint. Acceptable values are between 1 and 65535. - BackendPort *int32 `json:"backendPort,omitempty"` - // IdleTimeoutInMinutes - The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` - // EnableFloatingIP - Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - EnableFloatingIP *bool `json:"enableFloatingIP,omitempty"` - // EnableTCPReset - Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP. - EnableTCPReset *bool `json:"enableTcpReset,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the inbound NAT pool resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for InboundNatPoolPropertiesFormat. -func (inppf InboundNatPoolPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if inppf.FrontendIPConfiguration != nil { - objectMap["frontendIPConfiguration"] = inppf.FrontendIPConfiguration - } - if inppf.Protocol != "" { - objectMap["protocol"] = inppf.Protocol - } - if inppf.FrontendPortRangeStart != nil { - objectMap["frontendPortRangeStart"] = inppf.FrontendPortRangeStart - } - if inppf.FrontendPortRangeEnd != nil { - objectMap["frontendPortRangeEnd"] = inppf.FrontendPortRangeEnd - } - if inppf.BackendPort != nil { - objectMap["backendPort"] = inppf.BackendPort - } - if inppf.IdleTimeoutInMinutes != nil { - objectMap["idleTimeoutInMinutes"] = inppf.IdleTimeoutInMinutes - } - if inppf.EnableFloatingIP != nil { - objectMap["enableFloatingIP"] = inppf.EnableFloatingIP - } - if inppf.EnableTCPReset != nil { - objectMap["enableTcpReset"] = inppf.EnableTCPReset - } - return json.Marshal(objectMap) -} - -// InboundNatRule inbound NAT rule of the load balancer. -type InboundNatRule struct { - autorest.Response `json:"-"` - // InboundNatRulePropertiesFormat - Properties of load balancer inbound NAT rule. - *InboundNatRulePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within the set of inbound NAT rules used by the load balancer. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for InboundNatRule. -func (inr InboundNatRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if inr.InboundNatRulePropertiesFormat != nil { - objectMap["properties"] = inr.InboundNatRulePropertiesFormat - } - if inr.Name != nil { - objectMap["name"] = inr.Name - } - if inr.ID != nil { - objectMap["id"] = inr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for InboundNatRule struct. -func (inr *InboundNatRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var inboundNatRulePropertiesFormat InboundNatRulePropertiesFormat - err = json.Unmarshal(*v, &inboundNatRulePropertiesFormat) - if err != nil { - return err - } - inr.InboundNatRulePropertiesFormat = &inboundNatRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - inr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - inr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - inr.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - inr.ID = &ID - } - } - } - - return nil -} - -// InboundNatRuleListResult response for ListInboundNatRule API service call. -type InboundNatRuleListResult struct { - autorest.Response `json:"-"` - // Value - A list of inbound NAT rules in a load balancer. - Value *[]InboundNatRule `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for InboundNatRuleListResult. -func (inrlr InboundNatRuleListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if inrlr.Value != nil { - objectMap["value"] = inrlr.Value - } - return json.Marshal(objectMap) -} - -// InboundNatRuleListResultIterator provides access to a complete listing of InboundNatRule values. -type InboundNatRuleListResultIterator struct { - i int - page InboundNatRuleListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *InboundNatRuleListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRuleListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *InboundNatRuleListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter InboundNatRuleListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter InboundNatRuleListResultIterator) Response() InboundNatRuleListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter InboundNatRuleListResultIterator) Value() InboundNatRule { - if !iter.page.NotDone() { - return InboundNatRule{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the InboundNatRuleListResultIterator type. -func NewInboundNatRuleListResultIterator(page InboundNatRuleListResultPage) InboundNatRuleListResultIterator { - return InboundNatRuleListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (inrlr InboundNatRuleListResult) IsEmpty() bool { - return inrlr.Value == nil || len(*inrlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (inrlr InboundNatRuleListResult) hasNextLink() bool { - return inrlr.NextLink != nil && len(*inrlr.NextLink) != 0 -} - -// inboundNatRuleListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (inrlr InboundNatRuleListResult) inboundNatRuleListResultPreparer(ctx context.Context) (*http.Request, error) { - if !inrlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(inrlr.NextLink))) -} - -// InboundNatRuleListResultPage contains a page of InboundNatRule values. -type InboundNatRuleListResultPage struct { - fn func(context.Context, InboundNatRuleListResult) (InboundNatRuleListResult, error) - inrlr InboundNatRuleListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *InboundNatRuleListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InboundNatRuleListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.inrlr) - if err != nil { - return err - } - page.inrlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *InboundNatRuleListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page InboundNatRuleListResultPage) NotDone() bool { - return !page.inrlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page InboundNatRuleListResultPage) Response() InboundNatRuleListResult { - return page.inrlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page InboundNatRuleListResultPage) Values() []InboundNatRule { - if page.inrlr.IsEmpty() { - return nil - } - return *page.inrlr.Value -} - -// Creates a new instance of the InboundNatRuleListResultPage type. -func NewInboundNatRuleListResultPage(cur InboundNatRuleListResult, getNextPage func(context.Context, InboundNatRuleListResult) (InboundNatRuleListResult, error)) InboundNatRuleListResultPage { - return InboundNatRuleListResultPage{ - fn: getNextPage, - inrlr: cur, - } -} - -// InboundNatRulePortMapping individual port mappings for inbound NAT rule created for backend pool. -type InboundNatRulePortMapping struct { - // InboundNatRuleName - READ-ONLY; Name of inbound NAT rule. - InboundNatRuleName *string `json:"inboundNatRuleName,omitempty"` - // Protocol - READ-ONLY; The reference to the transport protocol used by the inbound NAT rule. Possible values include: 'TransportProtocolUDP', 'TransportProtocolTCP', 'TransportProtocolAll' - Protocol TransportProtocol `json:"protocol,omitempty"` - // FrontendPort - READ-ONLY; Frontend port. - FrontendPort *int32 `json:"frontendPort,omitempty"` - // BackendPort - READ-ONLY; Backend port. - BackendPort *int32 `json:"backendPort,omitempty"` -} - -// MarshalJSON is the custom marshaler for InboundNatRulePortMapping. -func (inrpm InboundNatRulePortMapping) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// InboundNatRulePropertiesFormat properties of the inbound NAT rule. -type InboundNatRulePropertiesFormat struct { - // FrontendIPConfiguration - A reference to frontend IP addresses. - FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` - // BackendIPConfiguration - READ-ONLY; A reference to a private IP address defined on a network interface of a VM. Traffic sent to the frontend port of each of the frontend IP configurations is forwarded to the backend IP. - BackendIPConfiguration *InterfaceIPConfiguration `json:"backendIPConfiguration,omitempty"` - // Protocol - The reference to the transport protocol used by the load balancing rule. Possible values include: 'TransportProtocolUDP', 'TransportProtocolTCP', 'TransportProtocolAll' - Protocol TransportProtocol `json:"protocol,omitempty"` - // FrontendPort - The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - FrontendPort *int32 `json:"frontendPort,omitempty"` - // BackendPort - The port used for the internal endpoint. Acceptable values range from 1 to 65535. - BackendPort *int32 `json:"backendPort,omitempty"` - // IdleTimeoutInMinutes - The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` - // EnableFloatingIP - Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - EnableFloatingIP *bool `json:"enableFloatingIP,omitempty"` - // EnableTCPReset - Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP. - EnableTCPReset *bool `json:"enableTcpReset,omitempty"` - // FrontendPortRangeStart - The port range start for the external endpoint. This property is used together with BackendAddressPool and FrontendPortRangeEnd. Individual inbound NAT rule port mappings will be created for each backend address from BackendAddressPool. Acceptable values range from 1 to 65534. - FrontendPortRangeStart *int32 `json:"frontendPortRangeStart,omitempty"` - // FrontendPortRangeEnd - The port range end for the external endpoint. This property is used together with BackendAddressPool and FrontendPortRangeStart. Individual inbound NAT rule port mappings will be created for each backend address from BackendAddressPool. Acceptable values range from 1 to 65534. - FrontendPortRangeEnd *int32 `json:"frontendPortRangeEnd,omitempty"` - // BackendAddressPool - A reference to backendAddressPool resource. - BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the inbound NAT rule resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for InboundNatRulePropertiesFormat. -func (inrpf InboundNatRulePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if inrpf.FrontendIPConfiguration != nil { - objectMap["frontendIPConfiguration"] = inrpf.FrontendIPConfiguration - } - if inrpf.Protocol != "" { - objectMap["protocol"] = inrpf.Protocol - } - if inrpf.FrontendPort != nil { - objectMap["frontendPort"] = inrpf.FrontendPort - } - if inrpf.BackendPort != nil { - objectMap["backendPort"] = inrpf.BackendPort - } - if inrpf.IdleTimeoutInMinutes != nil { - objectMap["idleTimeoutInMinutes"] = inrpf.IdleTimeoutInMinutes - } - if inrpf.EnableFloatingIP != nil { - objectMap["enableFloatingIP"] = inrpf.EnableFloatingIP - } - if inrpf.EnableTCPReset != nil { - objectMap["enableTcpReset"] = inrpf.EnableTCPReset - } - if inrpf.FrontendPortRangeStart != nil { - objectMap["frontendPortRangeStart"] = inrpf.FrontendPortRangeStart - } - if inrpf.FrontendPortRangeEnd != nil { - objectMap["frontendPortRangeEnd"] = inrpf.FrontendPortRangeEnd - } - if inrpf.BackendAddressPool != nil { - objectMap["backendAddressPool"] = inrpf.BackendAddressPool - } - return json.Marshal(objectMap) -} - -// InboundNatRulesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type InboundNatRulesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InboundNatRulesClient) (InboundNatRule, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InboundNatRulesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InboundNatRulesCreateOrUpdateFuture.Result. -func (future *InboundNatRulesCreateOrUpdateFuture) result(client InboundNatRulesClient) (inr InboundNatRule, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - inr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InboundNatRulesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if inr.Response.Response, err = future.GetResult(sender); err == nil && inr.Response.Response.StatusCode != http.StatusNoContent { - inr, err = client.CreateOrUpdateResponder(inr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesCreateOrUpdateFuture", "Result", inr.Response.Response, "Failure responding to request") - } - } - return -} - -// InboundNatRulesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type InboundNatRulesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InboundNatRulesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InboundNatRulesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InboundNatRulesDeleteFuture.Result. -func (future *InboundNatRulesDeleteFuture) result(client InboundNatRulesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundNatRulesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InboundNatRulesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// InboundSecurityRule NVA Inbound Security Rule resource. -type InboundSecurityRule struct { - autorest.Response `json:"-"` - // InboundSecurityRuleProperties - The properties of the Inbound Security Rules. - *InboundSecurityRuleProperties `json:"properties,omitempty"` - // Name - Name of security rule collection. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; NVA inbound security rule type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for InboundSecurityRule. -func (isr InboundSecurityRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if isr.InboundSecurityRuleProperties != nil { - objectMap["properties"] = isr.InboundSecurityRuleProperties - } - if isr.Name != nil { - objectMap["name"] = isr.Name - } - if isr.ID != nil { - objectMap["id"] = isr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for InboundSecurityRule struct. -func (isr *InboundSecurityRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var inboundSecurityRuleProperties InboundSecurityRuleProperties - err = json.Unmarshal(*v, &inboundSecurityRuleProperties) - if err != nil { - return err - } - isr.InboundSecurityRuleProperties = &inboundSecurityRuleProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - isr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - isr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - isr.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - isr.ID = &ID - } - } - } - - return nil -} - -// InboundSecurityRuleCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type InboundSecurityRuleCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InboundSecurityRuleClient) (InboundSecurityRule, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InboundSecurityRuleCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InboundSecurityRuleCreateOrUpdateFuture.Result. -func (future *InboundSecurityRuleCreateOrUpdateFuture) result(client InboundSecurityRuleClient) (isr InboundSecurityRule, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundSecurityRuleCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - isr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InboundSecurityRuleCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if isr.Response.Response, err = future.GetResult(sender); err == nil && isr.Response.Response.StatusCode != http.StatusNoContent { - isr, err = client.CreateOrUpdateResponder(isr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InboundSecurityRuleCreateOrUpdateFuture", "Result", isr.Response.Response, "Failure responding to request") - } - } - return -} - -// InboundSecurityRuleProperties properties of the Inbound Security Rules resource. -type InboundSecurityRuleProperties struct { - // Rules - List of allowed rules. - Rules *[]InboundSecurityRules `json:"rules,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for InboundSecurityRuleProperties. -func (isrp InboundSecurityRuleProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if isrp.Rules != nil { - objectMap["rules"] = isrp.Rules - } - return json.Marshal(objectMap) -} - -// InboundSecurityRules properties of the Inbound Security Rules resource. -type InboundSecurityRules struct { - // Protocol - Protocol. This should be either TCP or UDP. Possible values include: 'InboundSecurityRulesProtocolTCP', 'InboundSecurityRulesProtocolUDP' - Protocol InboundSecurityRulesProtocol `json:"protocol,omitempty"` - // SourceAddressPrefix - The CIDR or source IP range. Only /30, /31 and /32 Ip ranges are allowed. - SourceAddressPrefix *string `json:"sourceAddressPrefix,omitempty"` - // DestinationPortRange - NVA port ranges to be opened up. One needs to provide specific ports. - DestinationPortRange *int32 `json:"destinationPortRange,omitempty"` -} - -// IntentPolicy network Intent Policy resource. -type IntentPolicy struct { - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for IntentPolicy. -func (IP IntentPolicy) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if IP.ID != nil { - objectMap["id"] = IP.ID - } - if IP.Location != nil { - objectMap["location"] = IP.Location - } - if IP.Tags != nil { - objectMap["tags"] = IP.Tags - } - return json.Marshal(objectMap) -} - -// IntentPolicyConfiguration details of NetworkIntentPolicyConfiguration for PrepareNetworkPoliciesRequest. -type IntentPolicyConfiguration struct { - // NetworkIntentPolicyName - The name of the Network Intent Policy for storing in target subscription. - NetworkIntentPolicyName *string `json:"networkIntentPolicyName,omitempty"` - // SourceNetworkIntentPolicy - Source network intent policy. - SourceNetworkIntentPolicy *IntentPolicy `json:"sourceNetworkIntentPolicy,omitempty"` -} - -// Interface a network interface in a resource group. -type Interface struct { - autorest.Response `json:"-"` - // ExtendedLocation - The extended location of the network interface. - ExtendedLocation *ExtendedLocation `json:"extendedLocation,omitempty"` - // InterfacePropertiesFormat - Properties of the network interface. - *InterfacePropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Interface. -func (i Interface) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if i.ExtendedLocation != nil { - objectMap["extendedLocation"] = i.ExtendedLocation - } - if i.InterfacePropertiesFormat != nil { - objectMap["properties"] = i.InterfacePropertiesFormat - } - if i.ID != nil { - objectMap["id"] = i.ID - } - if i.Location != nil { - objectMap["location"] = i.Location - } - if i.Tags != nil { - objectMap["tags"] = i.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Interface struct. -func (i *Interface) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "extendedLocation": - if v != nil { - var extendedLocation ExtendedLocation - err = json.Unmarshal(*v, &extendedLocation) - if err != nil { - return err - } - i.ExtendedLocation = &extendedLocation - } - case "properties": - if v != nil { - var interfacePropertiesFormat InterfacePropertiesFormat - err = json.Unmarshal(*v, &interfacePropertiesFormat) - if err != nil { - return err - } - i.InterfacePropertiesFormat = &interfacePropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - i.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - i.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - i.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - i.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - i.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - i.Tags = tags - } - } - } - - return nil -} - -// InterfaceAssociation network interface and its custom security rules. -type InterfaceAssociation struct { - // ID - READ-ONLY; Network interface ID. - ID *string `json:"id,omitempty"` - // SecurityRules - Collection of custom security rules. - SecurityRules *[]SecurityRule `json:"securityRules,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceAssociation. -func (ia InterfaceAssociation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ia.SecurityRules != nil { - objectMap["securityRules"] = ia.SecurityRules - } - return json.Marshal(objectMap) -} - -// InterfaceDNSSettings DNS settings of a network interface. -type InterfaceDNSSettings struct { - // DNSServers - List of DNS servers IP addresses. Use 'AzureProvidedDNS' to switch to azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dnsServers collection. - DNSServers *[]string `json:"dnsServers,omitempty"` - // AppliedDNSServers - READ-ONLY; If the VM that uses this NIC is part of an Availability Set, then this list will have the union of all DNS servers from all NICs that are part of the Availability Set. This property is what is configured on each of those VMs. - AppliedDNSServers *[]string `json:"appliedDnsServers,omitempty"` - // InternalDNSNameLabel - Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - InternalDNSNameLabel *string `json:"internalDnsNameLabel,omitempty"` - // InternalFqdn - READ-ONLY; Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - InternalFqdn *string `json:"internalFqdn,omitempty"` - // InternalDomainNameSuffix - READ-ONLY; Even if internalDnsNameLabel is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internalDomainNameSuffix. - InternalDomainNameSuffix *string `json:"internalDomainNameSuffix,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceDNSSettings. -func (ids InterfaceDNSSettings) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ids.DNSServers != nil { - objectMap["dnsServers"] = ids.DNSServers - } - if ids.InternalDNSNameLabel != nil { - objectMap["internalDnsNameLabel"] = ids.InternalDNSNameLabel - } - return json.Marshal(objectMap) -} - -// InterfaceIPConfiguration iPConfiguration in a network interface. -type InterfaceIPConfiguration struct { - autorest.Response `json:"-"` - // InterfaceIPConfigurationPropertiesFormat - Network interface IP configuration properties. - *InterfaceIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceIPConfiguration. -func (iic InterfaceIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if iic.InterfaceIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = iic.InterfaceIPConfigurationPropertiesFormat - } - if iic.Name != nil { - objectMap["name"] = iic.Name - } - if iic.Type != nil { - objectMap["type"] = iic.Type - } - if iic.ID != nil { - objectMap["id"] = iic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for InterfaceIPConfiguration struct. -func (iic *InterfaceIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var interfaceIPConfigurationPropertiesFormat InterfaceIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &interfaceIPConfigurationPropertiesFormat) - if err != nil { - return err - } - iic.InterfaceIPConfigurationPropertiesFormat = &interfaceIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - iic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - iic.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - iic.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - iic.ID = &ID - } - } - } - - return nil -} - -// InterfaceIPConfigurationListResult response for list ip configurations API service call. -type InterfaceIPConfigurationListResult struct { - autorest.Response `json:"-"` - // Value - A list of ip configurations. - Value *[]InterfaceIPConfiguration `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceIPConfigurationListResult. -func (iiclr InterfaceIPConfigurationListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if iiclr.Value != nil { - objectMap["value"] = iiclr.Value - } - return json.Marshal(objectMap) -} - -// InterfaceIPConfigurationListResultIterator provides access to a complete listing of -// InterfaceIPConfiguration values. -type InterfaceIPConfigurationListResultIterator struct { - i int - page InterfaceIPConfigurationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *InterfaceIPConfigurationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceIPConfigurationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *InterfaceIPConfigurationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter InterfaceIPConfigurationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter InterfaceIPConfigurationListResultIterator) Response() InterfaceIPConfigurationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter InterfaceIPConfigurationListResultIterator) Value() InterfaceIPConfiguration { - if !iter.page.NotDone() { - return InterfaceIPConfiguration{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the InterfaceIPConfigurationListResultIterator type. -func NewInterfaceIPConfigurationListResultIterator(page InterfaceIPConfigurationListResultPage) InterfaceIPConfigurationListResultIterator { - return InterfaceIPConfigurationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (iiclr InterfaceIPConfigurationListResult) IsEmpty() bool { - return iiclr.Value == nil || len(*iiclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (iiclr InterfaceIPConfigurationListResult) hasNextLink() bool { - return iiclr.NextLink != nil && len(*iiclr.NextLink) != 0 -} - -// interfaceIPConfigurationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (iiclr InterfaceIPConfigurationListResult) interfaceIPConfigurationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !iiclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(iiclr.NextLink))) -} - -// InterfaceIPConfigurationListResultPage contains a page of InterfaceIPConfiguration values. -type InterfaceIPConfigurationListResultPage struct { - fn func(context.Context, InterfaceIPConfigurationListResult) (InterfaceIPConfigurationListResult, error) - iiclr InterfaceIPConfigurationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *InterfaceIPConfigurationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceIPConfigurationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.iiclr) - if err != nil { - return err - } - page.iiclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *InterfaceIPConfigurationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page InterfaceIPConfigurationListResultPage) NotDone() bool { - return !page.iiclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page InterfaceIPConfigurationListResultPage) Response() InterfaceIPConfigurationListResult { - return page.iiclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page InterfaceIPConfigurationListResultPage) Values() []InterfaceIPConfiguration { - if page.iiclr.IsEmpty() { - return nil - } - return *page.iiclr.Value -} - -// Creates a new instance of the InterfaceIPConfigurationListResultPage type. -func NewInterfaceIPConfigurationListResultPage(cur InterfaceIPConfigurationListResult, getNextPage func(context.Context, InterfaceIPConfigurationListResult) (InterfaceIPConfigurationListResult, error)) InterfaceIPConfigurationListResultPage { - return InterfaceIPConfigurationListResultPage{ - fn: getNextPage, - iiclr: cur, - } -} - -// InterfaceIPConfigurationPrivateLinkConnectionProperties privateLinkConnection properties for the network -// interface. -type InterfaceIPConfigurationPrivateLinkConnectionProperties struct { - // GroupID - READ-ONLY; The group ID for current private link connection. - GroupID *string `json:"groupId,omitempty"` - // RequiredMemberName - READ-ONLY; The required member name for current private link connection. - RequiredMemberName *string `json:"requiredMemberName,omitempty"` - // Fqdns - READ-ONLY; List of FQDNs for current private link connection. - Fqdns *[]string `json:"fqdns,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceIPConfigurationPrivateLinkConnectionProperties. -func (iicplcp InterfaceIPConfigurationPrivateLinkConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// InterfaceIPConfigurationPropertiesFormat properties of IP configuration. -type InterfaceIPConfigurationPropertiesFormat struct { - // GatewayLoadBalancer - The reference to gateway load balancer frontend IP. - GatewayLoadBalancer *SubResource `json:"gatewayLoadBalancer,omitempty"` - // VirtualNetworkTaps - The reference to Virtual Network Taps. - VirtualNetworkTaps *[]VirtualNetworkTap `json:"virtualNetworkTaps,omitempty"` - // ApplicationGatewayBackendAddressPools - The reference to ApplicationGatewayBackendAddressPool resource. - ApplicationGatewayBackendAddressPools *[]ApplicationGatewayBackendAddressPool `json:"applicationGatewayBackendAddressPools,omitempty"` - // LoadBalancerBackendAddressPools - The reference to LoadBalancerBackendAddressPool resource. - LoadBalancerBackendAddressPools *[]BackendAddressPool `json:"loadBalancerBackendAddressPools,omitempty"` - // LoadBalancerInboundNatRules - A list of references of LoadBalancerInboundNatRules. - LoadBalancerInboundNatRules *[]InboundNatRule `json:"loadBalancerInboundNatRules,omitempty"` - // PrivateIPAddress - Private IP address of the IP configuration. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // PrivateIPAllocationMethod - The private IP address allocation method. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` - // PrivateIPAddressVersion - Whether the specific IP configuration is IPv4 or IPv6. Default is IPv4. Possible values include: 'IPv4', 'IPv6' - PrivateIPAddressVersion IPVersion `json:"privateIPAddressVersion,omitempty"` - // Subnet - Subnet bound to the IP configuration. - Subnet *Subnet `json:"subnet,omitempty"` - // Primary - Whether this is a primary customer address on the network interface. - Primary *bool `json:"primary,omitempty"` - // PublicIPAddress - Public IP address bound to the IP configuration. - PublicIPAddress *PublicIPAddress `json:"publicIPAddress,omitempty"` - // ApplicationSecurityGroups - Application security groups in which the IP configuration is included. - ApplicationSecurityGroups *[]ApplicationSecurityGroup `json:"applicationSecurityGroups,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the network interface IP configuration. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // PrivateLinkConnectionProperties - READ-ONLY; PrivateLinkConnection properties for the network interface. - PrivateLinkConnectionProperties *InterfaceIPConfigurationPrivateLinkConnectionProperties `json:"privateLinkConnectionProperties,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceIPConfigurationPropertiesFormat. -func (iicpf InterfaceIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if iicpf.GatewayLoadBalancer != nil { - objectMap["gatewayLoadBalancer"] = iicpf.GatewayLoadBalancer - } - if iicpf.VirtualNetworkTaps != nil { - objectMap["virtualNetworkTaps"] = iicpf.VirtualNetworkTaps - } - if iicpf.ApplicationGatewayBackendAddressPools != nil { - objectMap["applicationGatewayBackendAddressPools"] = iicpf.ApplicationGatewayBackendAddressPools - } - if iicpf.LoadBalancerBackendAddressPools != nil { - objectMap["loadBalancerBackendAddressPools"] = iicpf.LoadBalancerBackendAddressPools - } - if iicpf.LoadBalancerInboundNatRules != nil { - objectMap["loadBalancerInboundNatRules"] = iicpf.LoadBalancerInboundNatRules - } - if iicpf.PrivateIPAddress != nil { - objectMap["privateIPAddress"] = iicpf.PrivateIPAddress - } - if iicpf.PrivateIPAllocationMethod != "" { - objectMap["privateIPAllocationMethod"] = iicpf.PrivateIPAllocationMethod - } - if iicpf.PrivateIPAddressVersion != "" { - objectMap["privateIPAddressVersion"] = iicpf.PrivateIPAddressVersion - } - if iicpf.Subnet != nil { - objectMap["subnet"] = iicpf.Subnet - } - if iicpf.Primary != nil { - objectMap["primary"] = iicpf.Primary - } - if iicpf.PublicIPAddress != nil { - objectMap["publicIPAddress"] = iicpf.PublicIPAddress - } - if iicpf.ApplicationSecurityGroups != nil { - objectMap["applicationSecurityGroups"] = iicpf.ApplicationSecurityGroups - } - return json.Marshal(objectMap) -} - -// InterfaceListResult response for the ListNetworkInterface API service call. -type InterfaceListResult struct { - autorest.Response `json:"-"` - // Value - A list of network interfaces in a resource group. - Value *[]Interface `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceListResult. -func (ilr InterfaceListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ilr.Value != nil { - objectMap["value"] = ilr.Value - } - return json.Marshal(objectMap) -} - -// InterfaceListResultIterator provides access to a complete listing of Interface values. -type InterfaceListResultIterator struct { - i int - page InterfaceListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *InterfaceListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *InterfaceListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter InterfaceListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter InterfaceListResultIterator) Response() InterfaceListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter InterfaceListResultIterator) Value() Interface { - if !iter.page.NotDone() { - return Interface{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the InterfaceListResultIterator type. -func NewInterfaceListResultIterator(page InterfaceListResultPage) InterfaceListResultIterator { - return InterfaceListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ilr InterfaceListResult) IsEmpty() bool { - return ilr.Value == nil || len(*ilr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ilr InterfaceListResult) hasNextLink() bool { - return ilr.NextLink != nil && len(*ilr.NextLink) != 0 -} - -// interfaceListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ilr InterfaceListResult) interfaceListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ilr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ilr.NextLink))) -} - -// InterfaceListResultPage contains a page of Interface values. -type InterfaceListResultPage struct { - fn func(context.Context, InterfaceListResult) (InterfaceListResult, error) - ilr InterfaceListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *InterfaceListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ilr) - if err != nil { - return err - } - page.ilr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *InterfaceListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page InterfaceListResultPage) NotDone() bool { - return !page.ilr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page InterfaceListResultPage) Response() InterfaceListResult { - return page.ilr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page InterfaceListResultPage) Values() []Interface { - if page.ilr.IsEmpty() { - return nil - } - return *page.ilr.Value -} - -// Creates a new instance of the InterfaceListResultPage type. -func NewInterfaceListResultPage(cur InterfaceListResult, getNextPage func(context.Context, InterfaceListResult) (InterfaceListResult, error)) InterfaceListResultPage { - return InterfaceListResultPage{ - fn: getNextPage, - ilr: cur, - } -} - -// InterfaceLoadBalancerListResult response for list ip configurations API service call. -type InterfaceLoadBalancerListResult struct { - autorest.Response `json:"-"` - // Value - A list of load balancers. - Value *[]LoadBalancer `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceLoadBalancerListResult. -func (ilblr InterfaceLoadBalancerListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ilblr.Value != nil { - objectMap["value"] = ilblr.Value - } - return json.Marshal(objectMap) -} - -// InterfaceLoadBalancerListResultIterator provides access to a complete listing of LoadBalancer values. -type InterfaceLoadBalancerListResultIterator struct { - i int - page InterfaceLoadBalancerListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *InterfaceLoadBalancerListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceLoadBalancerListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *InterfaceLoadBalancerListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter InterfaceLoadBalancerListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter InterfaceLoadBalancerListResultIterator) Response() InterfaceLoadBalancerListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter InterfaceLoadBalancerListResultIterator) Value() LoadBalancer { - if !iter.page.NotDone() { - return LoadBalancer{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the InterfaceLoadBalancerListResultIterator type. -func NewInterfaceLoadBalancerListResultIterator(page InterfaceLoadBalancerListResultPage) InterfaceLoadBalancerListResultIterator { - return InterfaceLoadBalancerListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ilblr InterfaceLoadBalancerListResult) IsEmpty() bool { - return ilblr.Value == nil || len(*ilblr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ilblr InterfaceLoadBalancerListResult) hasNextLink() bool { - return ilblr.NextLink != nil && len(*ilblr.NextLink) != 0 -} - -// interfaceLoadBalancerListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ilblr InterfaceLoadBalancerListResult) interfaceLoadBalancerListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ilblr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ilblr.NextLink))) -} - -// InterfaceLoadBalancerListResultPage contains a page of LoadBalancer values. -type InterfaceLoadBalancerListResultPage struct { - fn func(context.Context, InterfaceLoadBalancerListResult) (InterfaceLoadBalancerListResult, error) - ilblr InterfaceLoadBalancerListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *InterfaceLoadBalancerListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceLoadBalancerListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ilblr) - if err != nil { - return err - } - page.ilblr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *InterfaceLoadBalancerListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page InterfaceLoadBalancerListResultPage) NotDone() bool { - return !page.ilblr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page InterfaceLoadBalancerListResultPage) Response() InterfaceLoadBalancerListResult { - return page.ilblr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page InterfaceLoadBalancerListResultPage) Values() []LoadBalancer { - if page.ilblr.IsEmpty() { - return nil - } - return *page.ilblr.Value -} - -// Creates a new instance of the InterfaceLoadBalancerListResultPage type. -func NewInterfaceLoadBalancerListResultPage(cur InterfaceLoadBalancerListResult, getNextPage func(context.Context, InterfaceLoadBalancerListResult) (InterfaceLoadBalancerListResult, error)) InterfaceLoadBalancerListResultPage { - return InterfaceLoadBalancerListResultPage{ - fn: getNextPage, - ilblr: cur, - } -} - -// InterfacePropertiesFormat networkInterface properties. -type InterfacePropertiesFormat struct { - // VirtualMachine - READ-ONLY; The reference to a virtual machine. - VirtualMachine *SubResource `json:"virtualMachine,omitempty"` - // NetworkSecurityGroup - The reference to the NetworkSecurityGroup resource. - NetworkSecurityGroup *SecurityGroup `json:"networkSecurityGroup,omitempty"` - // PrivateEndpoint - READ-ONLY; A reference to the private endpoint to which the network interface is linked. - PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` - // IPConfigurations - A list of IPConfigurations of the network interface. - IPConfigurations *[]InterfaceIPConfiguration `json:"ipConfigurations,omitempty"` - // TapConfigurations - READ-ONLY; A list of TapConfigurations of the network interface. - TapConfigurations *[]InterfaceTapConfiguration `json:"tapConfigurations,omitempty"` - // DNSSettings - The DNS settings in network interface. - DNSSettings *InterfaceDNSSettings `json:"dnsSettings,omitempty"` - // MacAddress - READ-ONLY; The MAC address of the network interface. - MacAddress *string `json:"macAddress,omitempty"` - // Primary - READ-ONLY; Whether this is a primary network interface on a virtual machine. - Primary *bool `json:"primary,omitempty"` - // VnetEncryptionSupported - READ-ONLY; Whether the virtual machine this nic is attached to supports encryption. - VnetEncryptionSupported *bool `json:"vnetEncryptionSupported,omitempty"` - // EnableAcceleratedNetworking - If the network interface is configured for accelerated networking. Not applicable to VM sizes which require accelerated networking. - EnableAcceleratedNetworking *bool `json:"enableAcceleratedNetworking,omitempty"` - // DisableTCPStateTracking - Indicates whether to disable tcp state tracking. - DisableTCPStateTracking *bool `json:"disableTcpStateTracking,omitempty"` - // EnableIPForwarding - Indicates whether IP forwarding is enabled on this network interface. - EnableIPForwarding *bool `json:"enableIPForwarding,omitempty"` - // HostedWorkloads - READ-ONLY; A list of references to linked BareMetal resources. - HostedWorkloads *[]string `json:"hostedWorkloads,omitempty"` - // DscpConfiguration - READ-ONLY; A reference to the dscp configuration to which the network interface is linked. - DscpConfiguration *SubResource `json:"dscpConfiguration,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the network interface resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the network interface resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // WorkloadType - WorkloadType of the NetworkInterface for BareMetal resources - WorkloadType *string `json:"workloadType,omitempty"` - // NicType - Type of Network Interface resource. Possible values include: 'Standard', 'Elastic' - NicType InterfaceNicType `json:"nicType,omitempty"` - // PrivateLinkService - Privatelinkservice of the network interface resource. - PrivateLinkService *PrivateLinkService `json:"privateLinkService,omitempty"` - // MigrationPhase - Migration phase of Network Interface resource. Possible values include: 'InterfaceMigrationPhaseNone', 'InterfaceMigrationPhasePrepare', 'InterfaceMigrationPhaseCommit', 'InterfaceMigrationPhaseAbort', 'InterfaceMigrationPhaseCommitted' - MigrationPhase InterfaceMigrationPhase `json:"migrationPhase,omitempty"` - // AuxiliaryMode - Auxiliary mode of Network Interface resource. Possible values include: 'InterfaceAuxiliaryModeNone', 'InterfaceAuxiliaryModeMaxConnections', 'InterfaceAuxiliaryModeFloating' - AuxiliaryMode InterfaceAuxiliaryMode `json:"auxiliaryMode,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfacePropertiesFormat. -func (ipf InterfacePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ipf.NetworkSecurityGroup != nil { - objectMap["networkSecurityGroup"] = ipf.NetworkSecurityGroup - } - if ipf.IPConfigurations != nil { - objectMap["ipConfigurations"] = ipf.IPConfigurations - } - if ipf.DNSSettings != nil { - objectMap["dnsSettings"] = ipf.DNSSettings - } - if ipf.EnableAcceleratedNetworking != nil { - objectMap["enableAcceleratedNetworking"] = ipf.EnableAcceleratedNetworking - } - if ipf.DisableTCPStateTracking != nil { - objectMap["disableTcpStateTracking"] = ipf.DisableTCPStateTracking - } - if ipf.EnableIPForwarding != nil { - objectMap["enableIPForwarding"] = ipf.EnableIPForwarding - } - if ipf.WorkloadType != nil { - objectMap["workloadType"] = ipf.WorkloadType - } - if ipf.NicType != "" { - objectMap["nicType"] = ipf.NicType - } - if ipf.PrivateLinkService != nil { - objectMap["privateLinkService"] = ipf.PrivateLinkService - } - if ipf.MigrationPhase != "" { - objectMap["migrationPhase"] = ipf.MigrationPhase - } - if ipf.AuxiliaryMode != "" { - objectMap["auxiliaryMode"] = ipf.AuxiliaryMode - } - return json.Marshal(objectMap) -} - -// InterfacesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type InterfacesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfacesClient) (Interface, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfacesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfacesCreateOrUpdateFuture.Result. -func (future *InterfacesCreateOrUpdateFuture) result(client InterfacesClient) (i Interface, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - i.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfacesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if i.Response.Response, err = future.GetResult(sender); err == nil && i.Response.Response.StatusCode != http.StatusNoContent { - i, err = client.CreateOrUpdateResponder(i.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesCreateOrUpdateFuture", "Result", i.Response.Response, "Failure responding to request") - } - } - return -} - -// InterfacesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type InterfacesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfacesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfacesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfacesDeleteFuture.Result. -func (future *InterfacesDeleteFuture) result(client InterfacesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfacesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// InterfacesGetEffectiveRouteTableFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type InterfacesGetEffectiveRouteTableFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfacesClient) (EffectiveRouteListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfacesGetEffectiveRouteTableFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfacesGetEffectiveRouteTableFuture.Result. -func (future *InterfacesGetEffectiveRouteTableFuture) result(client InterfacesClient) (erlr EffectiveRouteListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesGetEffectiveRouteTableFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - erlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfacesGetEffectiveRouteTableFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if erlr.Response.Response, err = future.GetResult(sender); err == nil && erlr.Response.Response.StatusCode != http.StatusNoContent { - erlr, err = client.GetEffectiveRouteTableResponder(erlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesGetEffectiveRouteTableFuture", "Result", erlr.Response.Response, "Failure responding to request") - } - } - return -} - -// InterfacesListEffectiveNetworkSecurityGroupsFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type InterfacesListEffectiveNetworkSecurityGroupsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfacesClient) (EffectiveNetworkSecurityGroupListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfacesListEffectiveNetworkSecurityGroupsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfacesListEffectiveNetworkSecurityGroupsFuture.Result. -func (future *InterfacesListEffectiveNetworkSecurityGroupsFuture) result(client InterfacesClient) (ensglr EffectiveNetworkSecurityGroupListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesListEffectiveNetworkSecurityGroupsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ensglr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfacesListEffectiveNetworkSecurityGroupsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ensglr.Response.Response, err = future.GetResult(sender); err == nil && ensglr.Response.Response.StatusCode != http.StatusNoContent { - ensglr, err = client.ListEffectiveNetworkSecurityGroupsResponder(ensglr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesListEffectiveNetworkSecurityGroupsFuture", "Result", ensglr.Response.Response, "Failure responding to request") - } - } - return -} - -// InterfaceTapConfiguration tap configuration in a Network Interface. -type InterfaceTapConfiguration struct { - autorest.Response `json:"-"` - // InterfaceTapConfigurationPropertiesFormat - Properties of the Virtual Network Tap configuration. - *InterfaceTapConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Sub Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceTapConfiguration. -func (itc InterfaceTapConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if itc.InterfaceTapConfigurationPropertiesFormat != nil { - objectMap["properties"] = itc.InterfaceTapConfigurationPropertiesFormat - } - if itc.Name != nil { - objectMap["name"] = itc.Name - } - if itc.ID != nil { - objectMap["id"] = itc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for InterfaceTapConfiguration struct. -func (itc *InterfaceTapConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var interfaceTapConfigurationPropertiesFormat InterfaceTapConfigurationPropertiesFormat - err = json.Unmarshal(*v, &interfaceTapConfigurationPropertiesFormat) - if err != nil { - return err - } - itc.InterfaceTapConfigurationPropertiesFormat = &interfaceTapConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - itc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - itc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - itc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - itc.ID = &ID - } - } - } - - return nil -} - -// InterfaceTapConfigurationListResult response for list tap configurations API service call. -type InterfaceTapConfigurationListResult struct { - autorest.Response `json:"-"` - // Value - A list of tap configurations. - Value *[]InterfaceTapConfiguration `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceTapConfigurationListResult. -func (itclr InterfaceTapConfigurationListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if itclr.Value != nil { - objectMap["value"] = itclr.Value - } - return json.Marshal(objectMap) -} - -// InterfaceTapConfigurationListResultIterator provides access to a complete listing of -// InterfaceTapConfiguration values. -type InterfaceTapConfigurationListResultIterator struct { - i int - page InterfaceTapConfigurationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *InterfaceTapConfigurationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *InterfaceTapConfigurationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter InterfaceTapConfigurationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter InterfaceTapConfigurationListResultIterator) Response() InterfaceTapConfigurationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter InterfaceTapConfigurationListResultIterator) Value() InterfaceTapConfiguration { - if !iter.page.NotDone() { - return InterfaceTapConfiguration{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the InterfaceTapConfigurationListResultIterator type. -func NewInterfaceTapConfigurationListResultIterator(page InterfaceTapConfigurationListResultPage) InterfaceTapConfigurationListResultIterator { - return InterfaceTapConfigurationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (itclr InterfaceTapConfigurationListResult) IsEmpty() bool { - return itclr.Value == nil || len(*itclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (itclr InterfaceTapConfigurationListResult) hasNextLink() bool { - return itclr.NextLink != nil && len(*itclr.NextLink) != 0 -} - -// interfaceTapConfigurationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (itclr InterfaceTapConfigurationListResult) interfaceTapConfigurationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !itclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(itclr.NextLink))) -} - -// InterfaceTapConfigurationListResultPage contains a page of InterfaceTapConfiguration values. -type InterfaceTapConfigurationListResultPage struct { - fn func(context.Context, InterfaceTapConfigurationListResult) (InterfaceTapConfigurationListResult, error) - itclr InterfaceTapConfigurationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *InterfaceTapConfigurationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/InterfaceTapConfigurationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.itclr) - if err != nil { - return err - } - page.itclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *InterfaceTapConfigurationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page InterfaceTapConfigurationListResultPage) NotDone() bool { - return !page.itclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page InterfaceTapConfigurationListResultPage) Response() InterfaceTapConfigurationListResult { - return page.itclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page InterfaceTapConfigurationListResultPage) Values() []InterfaceTapConfiguration { - if page.itclr.IsEmpty() { - return nil - } - return *page.itclr.Value -} - -// Creates a new instance of the InterfaceTapConfigurationListResultPage type. -func NewInterfaceTapConfigurationListResultPage(cur InterfaceTapConfigurationListResult, getNextPage func(context.Context, InterfaceTapConfigurationListResult) (InterfaceTapConfigurationListResult, error)) InterfaceTapConfigurationListResultPage { - return InterfaceTapConfigurationListResultPage{ - fn: getNextPage, - itclr: cur, - } -} - -// InterfaceTapConfigurationPropertiesFormat properties of Virtual Network Tap configuration. -type InterfaceTapConfigurationPropertiesFormat struct { - // VirtualNetworkTap - The reference to the Virtual Network Tap resource. - VirtualNetworkTap *VirtualNetworkTap `json:"virtualNetworkTap,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the network interface tap configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for InterfaceTapConfigurationPropertiesFormat. -func (itcpf InterfaceTapConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if itcpf.VirtualNetworkTap != nil { - objectMap["virtualNetworkTap"] = itcpf.VirtualNetworkTap - } - return json.Marshal(objectMap) -} - -// InterfaceTapConfigurationsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type InterfaceTapConfigurationsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfaceTapConfigurationsClient) (InterfaceTapConfiguration, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfaceTapConfigurationsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfaceTapConfigurationsCreateOrUpdateFuture.Result. -func (future *InterfaceTapConfigurationsCreateOrUpdateFuture) result(client InterfaceTapConfigurationsClient) (itc InterfaceTapConfiguration, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - itc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfaceTapConfigurationsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if itc.Response.Response, err = future.GetResult(sender); err == nil && itc.Response.Response.StatusCode != http.StatusNoContent { - itc, err = client.CreateOrUpdateResponder(itc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsCreateOrUpdateFuture", "Result", itc.Response.Response, "Failure responding to request") - } - } - return -} - -// InterfaceTapConfigurationsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type InterfaceTapConfigurationsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(InterfaceTapConfigurationsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *InterfaceTapConfigurationsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for InterfaceTapConfigurationsDeleteFuture.Result. -func (future *InterfaceTapConfigurationsDeleteFuture) result(client InterfaceTapConfigurationsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfaceTapConfigurationsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.InterfaceTapConfigurationsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// IPAddressAvailabilityResult response for CheckIPAddressAvailability API service call. -type IPAddressAvailabilityResult struct { - autorest.Response `json:"-"` - // Available - Private IP address availability. - Available *bool `json:"available,omitempty"` - // AvailableIPAddresses - Contains other available private IP addresses if the asked for address is taken. - AvailableIPAddresses *[]string `json:"availableIPAddresses,omitempty"` - // IsPlatformReserved - Private IP address platform reserved. - IsPlatformReserved *bool `json:"isPlatformReserved,omitempty"` -} - -// IPAllocation ipAllocation resource. -type IPAllocation struct { - autorest.Response `json:"-"` - // IPAllocationPropertiesFormat - Properties of the IpAllocation. - *IPAllocationPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for IPAllocation. -func (ia IPAllocation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ia.IPAllocationPropertiesFormat != nil { - objectMap["properties"] = ia.IPAllocationPropertiesFormat - } - if ia.ID != nil { - objectMap["id"] = ia.ID - } - if ia.Location != nil { - objectMap["location"] = ia.Location - } - if ia.Tags != nil { - objectMap["tags"] = ia.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for IPAllocation struct. -func (ia *IPAllocation) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var IPAllocationPropertiesFormat IPAllocationPropertiesFormat - err = json.Unmarshal(*v, &IPAllocationPropertiesFormat) - if err != nil { - return err - } - ia.IPAllocationPropertiesFormat = &IPAllocationPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ia.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ia.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ia.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ia.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ia.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - ia.Tags = tags - } - } - } - - return nil -} - -// IPAllocationListResult response for the ListIpAllocations API service call. -type IPAllocationListResult struct { - autorest.Response `json:"-"` - // Value - A list of IpAllocation resources. - Value *[]IPAllocation `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// IPAllocationListResultIterator provides access to a complete listing of IPAllocation values. -type IPAllocationListResultIterator struct { - i int - page IPAllocationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *IPAllocationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPAllocationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *IPAllocationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter IPAllocationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter IPAllocationListResultIterator) Response() IPAllocationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter IPAllocationListResultIterator) Value() IPAllocation { - if !iter.page.NotDone() { - return IPAllocation{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the IPAllocationListResultIterator type. -func NewIPAllocationListResultIterator(page IPAllocationListResultPage) IPAllocationListResultIterator { - return IPAllocationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ialr IPAllocationListResult) IsEmpty() bool { - return ialr.Value == nil || len(*ialr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ialr IPAllocationListResult) hasNextLink() bool { - return ialr.NextLink != nil && len(*ialr.NextLink) != 0 -} - -// iPAllocationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ialr IPAllocationListResult) iPAllocationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ialr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ialr.NextLink))) -} - -// IPAllocationListResultPage contains a page of IPAllocation values. -type IPAllocationListResultPage struct { - fn func(context.Context, IPAllocationListResult) (IPAllocationListResult, error) - ialr IPAllocationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *IPAllocationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPAllocationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ialr) - if err != nil { - return err - } - page.ialr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *IPAllocationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page IPAllocationListResultPage) NotDone() bool { - return !page.ialr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page IPAllocationListResultPage) Response() IPAllocationListResult { - return page.ialr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page IPAllocationListResultPage) Values() []IPAllocation { - if page.ialr.IsEmpty() { - return nil - } - return *page.ialr.Value -} - -// Creates a new instance of the IPAllocationListResultPage type. -func NewIPAllocationListResultPage(cur IPAllocationListResult, getNextPage func(context.Context, IPAllocationListResult) (IPAllocationListResult, error)) IPAllocationListResultPage { - return IPAllocationListResultPage{ - fn: getNextPage, - ialr: cur, - } -} - -// IPAllocationPropertiesFormat properties of the IpAllocation. -type IPAllocationPropertiesFormat struct { - // Subnet - READ-ONLY; The Subnet that using the prefix of this IpAllocation resource. - Subnet *SubResource `json:"subnet,omitempty"` - // VirtualNetwork - READ-ONLY; The VirtualNetwork that using the prefix of this IpAllocation resource. - VirtualNetwork *SubResource `json:"virtualNetwork,omitempty"` - // Type - The type for the IpAllocation. Possible values include: 'Undefined', 'Hypernet' - Type IPAllocationType `json:"type,omitempty"` - // Prefix - The address prefix for the IpAllocation. - Prefix *string `json:"prefix,omitempty"` - // PrefixLength - The address prefix length for the IpAllocation. - PrefixLength *int32 `json:"prefixLength,omitempty"` - // PrefixType - The address prefix Type for the IpAllocation. Possible values include: 'IPv4', 'IPv6' - PrefixType IPVersion `json:"prefixType,omitempty"` - // IpamAllocationID - The IPAM allocation ID. - IpamAllocationID *string `json:"ipamAllocationId,omitempty"` - // AllocationTags - IpAllocation tags. - AllocationTags map[string]*string `json:"allocationTags"` -} - -// MarshalJSON is the custom marshaler for IPAllocationPropertiesFormat. -func (iapf IPAllocationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if iapf.Type != "" { - objectMap["type"] = iapf.Type - } - if iapf.Prefix != nil { - objectMap["prefix"] = iapf.Prefix - } - if iapf.PrefixLength != nil { - objectMap["prefixLength"] = iapf.PrefixLength - } - if iapf.PrefixType != "" { - objectMap["prefixType"] = iapf.PrefixType - } - if iapf.IpamAllocationID != nil { - objectMap["ipamAllocationId"] = iapf.IpamAllocationID - } - if iapf.AllocationTags != nil { - objectMap["allocationTags"] = iapf.AllocationTags - } - return json.Marshal(objectMap) -} - -// IPAllocationsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type IPAllocationsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(IPAllocationsClient) (IPAllocation, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *IPAllocationsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for IPAllocationsCreateOrUpdateFuture.Result. -func (future *IPAllocationsCreateOrUpdateFuture) result(client IPAllocationsClient) (ia IPAllocation, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ia.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.IPAllocationsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ia.Response.Response, err = future.GetResult(sender); err == nil && ia.Response.Response.StatusCode != http.StatusNoContent { - ia, err = client.CreateOrUpdateResponder(ia.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsCreateOrUpdateFuture", "Result", ia.Response.Response, "Failure responding to request") - } - } - return -} - -// IPAllocationsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type IPAllocationsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(IPAllocationsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *IPAllocationsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for IPAllocationsDeleteFuture.Result. -func (future *IPAllocationsDeleteFuture) result(client IPAllocationsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPAllocationsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.IPAllocationsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// IPConfiguration IP configuration. -type IPConfiguration struct { - // IPConfigurationPropertiesFormat - Properties of the IP configuration. - *IPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for IPConfiguration. -func (ic IPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ic.IPConfigurationPropertiesFormat != nil { - objectMap["properties"] = ic.IPConfigurationPropertiesFormat - } - if ic.Name != nil { - objectMap["name"] = ic.Name - } - if ic.ID != nil { - objectMap["id"] = ic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for IPConfiguration struct. -func (ic *IPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var IPConfigurationPropertiesFormat IPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &IPConfigurationPropertiesFormat) - if err != nil { - return err - } - ic.IPConfigurationPropertiesFormat = &IPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ic.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ic.ID = &ID - } - } - } - - return nil -} - -// IPConfigurationBgpPeeringAddress properties of IPConfigurationBgpPeeringAddress. -type IPConfigurationBgpPeeringAddress struct { - // IpconfigurationID - The ID of IP configuration which belongs to gateway. - IpconfigurationID *string `json:"ipconfigurationId,omitempty"` - // DefaultBgpIPAddresses - READ-ONLY; The list of default BGP peering addresses which belong to IP configuration. - DefaultBgpIPAddresses *[]string `json:"defaultBgpIpAddresses,omitempty"` - // CustomBgpIPAddresses - The list of custom BGP peering addresses which belong to IP configuration. - CustomBgpIPAddresses *[]string `json:"customBgpIpAddresses,omitempty"` - // TunnelIPAddresses - READ-ONLY; The list of tunnel public IP addresses which belong to IP configuration. - TunnelIPAddresses *[]string `json:"tunnelIpAddresses,omitempty"` -} - -// MarshalJSON is the custom marshaler for IPConfigurationBgpPeeringAddress. -func (icbpa IPConfigurationBgpPeeringAddress) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if icbpa.IpconfigurationID != nil { - objectMap["ipconfigurationId"] = icbpa.IpconfigurationID - } - if icbpa.CustomBgpIPAddresses != nil { - objectMap["customBgpIpAddresses"] = icbpa.CustomBgpIPAddresses - } - return json.Marshal(objectMap) -} - -// IPConfigurationProfile IP configuration profile child resource. -type IPConfigurationProfile struct { - // IPConfigurationProfilePropertiesFormat - Properties of the IP configuration profile. - *IPConfigurationProfilePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Sub Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for IPConfigurationProfile. -func (icp IPConfigurationProfile) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if icp.IPConfigurationProfilePropertiesFormat != nil { - objectMap["properties"] = icp.IPConfigurationProfilePropertiesFormat - } - if icp.Name != nil { - objectMap["name"] = icp.Name - } - if icp.ID != nil { - objectMap["id"] = icp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for IPConfigurationProfile struct. -func (icp *IPConfigurationProfile) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var IPConfigurationProfilePropertiesFormat IPConfigurationProfilePropertiesFormat - err = json.Unmarshal(*v, &IPConfigurationProfilePropertiesFormat) - if err != nil { - return err - } - icp.IPConfigurationProfilePropertiesFormat = &IPConfigurationProfilePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - icp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - icp.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - icp.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - icp.ID = &ID - } - } - } - - return nil -} - -// IPConfigurationProfilePropertiesFormat IP configuration profile properties. -type IPConfigurationProfilePropertiesFormat struct { - // Subnet - The reference to the subnet resource to create a container network interface ip configuration. - Subnet *Subnet `json:"subnet,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the IP configuration profile resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for IPConfigurationProfilePropertiesFormat. -func (icppf IPConfigurationProfilePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if icppf.Subnet != nil { - objectMap["subnet"] = icppf.Subnet - } - return json.Marshal(objectMap) -} - -// IPConfigurationPropertiesFormat properties of IP configuration. -type IPConfigurationPropertiesFormat struct { - // PrivateIPAddress - The private IP address of the IP configuration. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // PrivateIPAllocationMethod - The private IP address allocation method. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` - // Subnet - The reference to the subnet resource. - Subnet *Subnet `json:"subnet,omitempty"` - // PublicIPAddress - The reference to the public IP resource. - PublicIPAddress *PublicIPAddress `json:"publicIPAddress,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the IP configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for IPConfigurationPropertiesFormat. -func (icpf IPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if icpf.PrivateIPAddress != nil { - objectMap["privateIPAddress"] = icpf.PrivateIPAddress - } - if icpf.PrivateIPAllocationMethod != "" { - objectMap["privateIPAllocationMethod"] = icpf.PrivateIPAllocationMethod - } - if icpf.Subnet != nil { - objectMap["subnet"] = icpf.Subnet - } - if icpf.PublicIPAddress != nil { - objectMap["publicIPAddress"] = icpf.PublicIPAddress - } - return json.Marshal(objectMap) -} - -// IPGroup the IpGroups resource information. -type IPGroup struct { - autorest.Response `json:"-"` - // IPGroupPropertiesFormat - Properties of the IpGroups. - *IPGroupPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for IPGroup. -func (ig IPGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ig.IPGroupPropertiesFormat != nil { - objectMap["properties"] = ig.IPGroupPropertiesFormat - } - if ig.ID != nil { - objectMap["id"] = ig.ID - } - if ig.Location != nil { - objectMap["location"] = ig.Location - } - if ig.Tags != nil { - objectMap["tags"] = ig.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for IPGroup struct. -func (ig *IPGroup) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var IPGroupPropertiesFormat IPGroupPropertiesFormat - err = json.Unmarshal(*v, &IPGroupPropertiesFormat) - if err != nil { - return err - } - ig.IPGroupPropertiesFormat = &IPGroupPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ig.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ig.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ig.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ig.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ig.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - ig.Tags = tags - } - } - } - - return nil -} - -// IPGroupListResult response for the ListIpGroups API service call. -type IPGroupListResult struct { - autorest.Response `json:"-"` - // Value - The list of IpGroups information resources. - Value *[]IPGroup `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// IPGroupListResultIterator provides access to a complete listing of IPGroup values. -type IPGroupListResultIterator struct { - i int - page IPGroupListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *IPGroupListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPGroupListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *IPGroupListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter IPGroupListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter IPGroupListResultIterator) Response() IPGroupListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter IPGroupListResultIterator) Value() IPGroup { - if !iter.page.NotDone() { - return IPGroup{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the IPGroupListResultIterator type. -func NewIPGroupListResultIterator(page IPGroupListResultPage) IPGroupListResultIterator { - return IPGroupListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (iglr IPGroupListResult) IsEmpty() bool { - return iglr.Value == nil || len(*iglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (iglr IPGroupListResult) hasNextLink() bool { - return iglr.NextLink != nil && len(*iglr.NextLink) != 0 -} - -// iPGroupListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (iglr IPGroupListResult) iPGroupListResultPreparer(ctx context.Context) (*http.Request, error) { - if !iglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(iglr.NextLink))) -} - -// IPGroupListResultPage contains a page of IPGroup values. -type IPGroupListResultPage struct { - fn func(context.Context, IPGroupListResult) (IPGroupListResult, error) - iglr IPGroupListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *IPGroupListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/IPGroupListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.iglr) - if err != nil { - return err - } - page.iglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *IPGroupListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page IPGroupListResultPage) NotDone() bool { - return !page.iglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page IPGroupListResultPage) Response() IPGroupListResult { - return page.iglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page IPGroupListResultPage) Values() []IPGroup { - if page.iglr.IsEmpty() { - return nil - } - return *page.iglr.Value -} - -// Creates a new instance of the IPGroupListResultPage type. -func NewIPGroupListResultPage(cur IPGroupListResult, getNextPage func(context.Context, IPGroupListResult) (IPGroupListResult, error)) IPGroupListResultPage { - return IPGroupListResultPage{ - fn: getNextPage, - iglr: cur, - } -} - -// IPGroupPropertiesFormat the IpGroups property information. -type IPGroupPropertiesFormat struct { - // ProvisioningState - READ-ONLY; The provisioning state of the IpGroups resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // IPAddresses - IpAddresses/IpAddressPrefixes in the IpGroups resource. - IPAddresses *[]string `json:"ipAddresses,omitempty"` - // Firewalls - READ-ONLY; List of references to Firewall resources that this IpGroups is associated with. - Firewalls *[]SubResource `json:"firewalls,omitempty"` - // FirewallPolicies - READ-ONLY; List of references to Firewall Policies resources that this IpGroups is associated with. - FirewallPolicies *[]SubResource `json:"firewallPolicies,omitempty"` -} - -// MarshalJSON is the custom marshaler for IPGroupPropertiesFormat. -func (igpf IPGroupPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if igpf.IPAddresses != nil { - objectMap["ipAddresses"] = igpf.IPAddresses - } - return json.Marshal(objectMap) -} - -// IPGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type IPGroupsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(IPGroupsClient) (IPGroup, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *IPGroupsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for IPGroupsCreateOrUpdateFuture.Result. -func (future *IPGroupsCreateOrUpdateFuture) result(client IPGroupsClient) (ig IPGroup, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ig.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.IPGroupsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ig.Response.Response, err = future.GetResult(sender); err == nil && ig.Response.Response.StatusCode != http.StatusNoContent { - ig, err = client.CreateOrUpdateResponder(ig.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsCreateOrUpdateFuture", "Result", ig.Response.Response, "Failure responding to request") - } - } - return -} - -// IPGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type IPGroupsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(IPGroupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *IPGroupsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for IPGroupsDeleteFuture.Result. -func (future *IPGroupsDeleteFuture) result(client IPGroupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.IPGroupsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.IPGroupsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// IPPrefixesList list of SNAT IP Prefixes learnt by firewall to not SNAT -type IPPrefixesList struct { - autorest.Response `json:"-"` - // IPPrefixes - IP Prefix value. - IPPrefixes *[]string `json:"ipPrefixes,omitempty"` -} - -// IpsecPolicy an IPSec Policy configuration for a virtual network gateway connection. -type IpsecPolicy struct { - // SaLifeTimeSeconds - The IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds for a site to site VPN tunnel. - SaLifeTimeSeconds *int32 `json:"saLifeTimeSeconds,omitempty"` - // SaDataSizeKilobytes - The IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB for a site to site VPN tunnel. - SaDataSizeKilobytes *int32 `json:"saDataSizeKilobytes,omitempty"` - // IpsecEncryption - The IPSec encryption algorithm (IKE phase 1). Possible values include: 'IpsecEncryptionNone', 'IpsecEncryptionDES', 'IpsecEncryptionDES3', 'IpsecEncryptionAES128', 'IpsecEncryptionAES192', 'IpsecEncryptionAES256', 'IpsecEncryptionGCMAES128', 'IpsecEncryptionGCMAES192', 'IpsecEncryptionGCMAES256' - IpsecEncryption IpsecEncryption `json:"ipsecEncryption,omitempty"` - // IpsecIntegrity - The IPSec integrity algorithm (IKE phase 1). Possible values include: 'IpsecIntegrityMD5', 'IpsecIntegritySHA1', 'IpsecIntegritySHA256', 'IpsecIntegrityGCMAES128', 'IpsecIntegrityGCMAES192', 'IpsecIntegrityGCMAES256' - IpsecIntegrity IpsecIntegrity `json:"ipsecIntegrity,omitempty"` - // IkeEncryption - The IKE encryption algorithm (IKE phase 2). Possible values include: 'DES', 'DES3', 'AES128', 'AES192', 'AES256', 'GCMAES256', 'GCMAES128' - IkeEncryption IkeEncryption `json:"ikeEncryption,omitempty"` - // IkeIntegrity - The IKE integrity algorithm (IKE phase 2). Possible values include: 'IkeIntegrityMD5', 'IkeIntegritySHA1', 'IkeIntegritySHA256', 'IkeIntegritySHA384', 'IkeIntegrityGCMAES256', 'IkeIntegrityGCMAES128' - IkeIntegrity IkeIntegrity `json:"ikeIntegrity,omitempty"` - // DhGroup - The DH Group used in IKE Phase 1 for initial SA. Possible values include: 'DhGroupNone', 'DhGroupDHGroup1', 'DhGroupDHGroup2', 'DhGroupDHGroup14', 'DhGroupDHGroup2048', 'DhGroupECP256', 'DhGroupECP384', 'DhGroupDHGroup24' - DhGroup DhGroup `json:"dhGroup,omitempty"` - // PfsGroup - The Pfs Group used in IKE Phase 2 for new child SA. Possible values include: 'PfsGroupNone', 'PfsGroupPFS1', 'PfsGroupPFS2', 'PfsGroupPFS2048', 'PfsGroupECP256', 'PfsGroupECP384', 'PfsGroupPFS24', 'PfsGroupPFS14', 'PfsGroupPFSMM' - PfsGroup PfsGroup `json:"pfsGroup,omitempty"` -} - -// IPTag contains the IpTag associated with the object. -type IPTag struct { - // IPTagType - The IP tag type. Example: FirstPartyUsage. - IPTagType *string `json:"ipTagType,omitempty"` - // Tag - The value of the IP tag associated with the public IP. Example: SQL. - Tag *string `json:"tag,omitempty"` -} - -// Ipv6CircuitConnectionConfig iPv6 Circuit Connection properties for global reach. -type Ipv6CircuitConnectionConfig struct { - // AddressPrefix - /125 IP address space to carve out customer addresses for global reach. - AddressPrefix *string `json:"addressPrefix,omitempty"` - // CircuitConnectionStatus - READ-ONLY; Express Route Circuit connection state. Possible values include: 'Connected', 'Connecting', 'Disconnected' - CircuitConnectionStatus CircuitConnectionStatus `json:"circuitConnectionStatus,omitempty"` -} - -// MarshalJSON is the custom marshaler for Ipv6CircuitConnectionConfig. -func (i6ccc Ipv6CircuitConnectionConfig) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if i6ccc.AddressPrefix != nil { - objectMap["addressPrefix"] = i6ccc.AddressPrefix - } - return json.Marshal(objectMap) -} - -// Ipv6ExpressRouteCircuitPeeringConfig contains IPv6 peering config. -type Ipv6ExpressRouteCircuitPeeringConfig struct { - // PrimaryPeerAddressPrefix - The primary address prefix. - PrimaryPeerAddressPrefix *string `json:"primaryPeerAddressPrefix,omitempty"` - // SecondaryPeerAddressPrefix - The secondary address prefix. - SecondaryPeerAddressPrefix *string `json:"secondaryPeerAddressPrefix,omitempty"` - // MicrosoftPeeringConfig - The Microsoft peering configuration. - MicrosoftPeeringConfig *ExpressRouteCircuitPeeringConfig `json:"microsoftPeeringConfig,omitempty"` - // RouteFilter - The reference to the RouteFilter resource. - RouteFilter *SubResource `json:"routeFilter,omitempty"` - // State - The state of peering. Possible values include: 'ExpressRouteCircuitPeeringStateDisabled', 'ExpressRouteCircuitPeeringStateEnabled' - State ExpressRouteCircuitPeeringState `json:"state,omitempty"` -} - -// ListHubRouteTablesResult list of RouteTables and a URL nextLink to get the next set of results. -type ListHubRouteTablesResult struct { - autorest.Response `json:"-"` - // Value - List of RouteTables. - Value *[]HubRouteTable `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListHubRouteTablesResultIterator provides access to a complete listing of HubRouteTable values. -type ListHubRouteTablesResultIterator struct { - i int - page ListHubRouteTablesResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListHubRouteTablesResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListHubRouteTablesResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListHubRouteTablesResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListHubRouteTablesResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListHubRouteTablesResultIterator) Response() ListHubRouteTablesResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListHubRouteTablesResultIterator) Value() HubRouteTable { - if !iter.page.NotDone() { - return HubRouteTable{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListHubRouteTablesResultIterator type. -func NewListHubRouteTablesResultIterator(page ListHubRouteTablesResultPage) ListHubRouteTablesResultIterator { - return ListHubRouteTablesResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lhrtr ListHubRouteTablesResult) IsEmpty() bool { - return lhrtr.Value == nil || len(*lhrtr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lhrtr ListHubRouteTablesResult) hasNextLink() bool { - return lhrtr.NextLink != nil && len(*lhrtr.NextLink) != 0 -} - -// listHubRouteTablesResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lhrtr ListHubRouteTablesResult) listHubRouteTablesResultPreparer(ctx context.Context) (*http.Request, error) { - if !lhrtr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lhrtr.NextLink))) -} - -// ListHubRouteTablesResultPage contains a page of HubRouteTable values. -type ListHubRouteTablesResultPage struct { - fn func(context.Context, ListHubRouteTablesResult) (ListHubRouteTablesResult, error) - lhrtr ListHubRouteTablesResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListHubRouteTablesResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListHubRouteTablesResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lhrtr) - if err != nil { - return err - } - page.lhrtr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListHubRouteTablesResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListHubRouteTablesResultPage) NotDone() bool { - return !page.lhrtr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListHubRouteTablesResultPage) Response() ListHubRouteTablesResult { - return page.lhrtr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListHubRouteTablesResultPage) Values() []HubRouteTable { - if page.lhrtr.IsEmpty() { - return nil - } - return *page.lhrtr.Value -} - -// Creates a new instance of the ListHubRouteTablesResultPage type. -func NewListHubRouteTablesResultPage(cur ListHubRouteTablesResult, getNextPage func(context.Context, ListHubRouteTablesResult) (ListHubRouteTablesResult, error)) ListHubRouteTablesResultPage { - return ListHubRouteTablesResultPage{ - fn: getNextPage, - lhrtr: cur, - } -} - -// ListHubVirtualNetworkConnectionsResult list of HubVirtualNetworkConnections and a URL nextLink to get -// the next set of results. -type ListHubVirtualNetworkConnectionsResult struct { - autorest.Response `json:"-"` - // Value - List of HubVirtualNetworkConnections. - Value *[]HubVirtualNetworkConnection `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListHubVirtualNetworkConnectionsResultIterator provides access to a complete listing of -// HubVirtualNetworkConnection values. -type ListHubVirtualNetworkConnectionsResultIterator struct { - i int - page ListHubVirtualNetworkConnectionsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListHubVirtualNetworkConnectionsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListHubVirtualNetworkConnectionsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListHubVirtualNetworkConnectionsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListHubVirtualNetworkConnectionsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListHubVirtualNetworkConnectionsResultIterator) Response() ListHubVirtualNetworkConnectionsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListHubVirtualNetworkConnectionsResultIterator) Value() HubVirtualNetworkConnection { - if !iter.page.NotDone() { - return HubVirtualNetworkConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListHubVirtualNetworkConnectionsResultIterator type. -func NewListHubVirtualNetworkConnectionsResultIterator(page ListHubVirtualNetworkConnectionsResultPage) ListHubVirtualNetworkConnectionsResultIterator { - return ListHubVirtualNetworkConnectionsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lhvncr ListHubVirtualNetworkConnectionsResult) IsEmpty() bool { - return lhvncr.Value == nil || len(*lhvncr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lhvncr ListHubVirtualNetworkConnectionsResult) hasNextLink() bool { - return lhvncr.NextLink != nil && len(*lhvncr.NextLink) != 0 -} - -// listHubVirtualNetworkConnectionsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lhvncr ListHubVirtualNetworkConnectionsResult) listHubVirtualNetworkConnectionsResultPreparer(ctx context.Context) (*http.Request, error) { - if !lhvncr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lhvncr.NextLink))) -} - -// ListHubVirtualNetworkConnectionsResultPage contains a page of HubVirtualNetworkConnection values. -type ListHubVirtualNetworkConnectionsResultPage struct { - fn func(context.Context, ListHubVirtualNetworkConnectionsResult) (ListHubVirtualNetworkConnectionsResult, error) - lhvncr ListHubVirtualNetworkConnectionsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListHubVirtualNetworkConnectionsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListHubVirtualNetworkConnectionsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lhvncr) - if err != nil { - return err - } - page.lhvncr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListHubVirtualNetworkConnectionsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListHubVirtualNetworkConnectionsResultPage) NotDone() bool { - return !page.lhvncr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListHubVirtualNetworkConnectionsResultPage) Response() ListHubVirtualNetworkConnectionsResult { - return page.lhvncr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListHubVirtualNetworkConnectionsResultPage) Values() []HubVirtualNetworkConnection { - if page.lhvncr.IsEmpty() { - return nil - } - return *page.lhvncr.Value -} - -// Creates a new instance of the ListHubVirtualNetworkConnectionsResultPage type. -func NewListHubVirtualNetworkConnectionsResultPage(cur ListHubVirtualNetworkConnectionsResult, getNextPage func(context.Context, ListHubVirtualNetworkConnectionsResult) (ListHubVirtualNetworkConnectionsResult, error)) ListHubVirtualNetworkConnectionsResultPage { - return ListHubVirtualNetworkConnectionsResultPage{ - fn: getNextPage, - lhvncr: cur, - } -} - -// ListP2SVpnGatewaysResult result of the request to list P2SVpnGateways. It contains a list of -// P2SVpnGateways and a URL nextLink to get the next set of results. -type ListP2SVpnGatewaysResult struct { - autorest.Response `json:"-"` - // Value - List of P2SVpnGateways. - Value *[]P2SVpnGateway `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListP2SVpnGatewaysResultIterator provides access to a complete listing of P2SVpnGateway values. -type ListP2SVpnGatewaysResultIterator struct { - i int - page ListP2SVpnGatewaysResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListP2SVpnGatewaysResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListP2SVpnGatewaysResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListP2SVpnGatewaysResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListP2SVpnGatewaysResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListP2SVpnGatewaysResultIterator) Response() ListP2SVpnGatewaysResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListP2SVpnGatewaysResultIterator) Value() P2SVpnGateway { - if !iter.page.NotDone() { - return P2SVpnGateway{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListP2SVpnGatewaysResultIterator type. -func NewListP2SVpnGatewaysResultIterator(page ListP2SVpnGatewaysResultPage) ListP2SVpnGatewaysResultIterator { - return ListP2SVpnGatewaysResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lpvgr ListP2SVpnGatewaysResult) IsEmpty() bool { - return lpvgr.Value == nil || len(*lpvgr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lpvgr ListP2SVpnGatewaysResult) hasNextLink() bool { - return lpvgr.NextLink != nil && len(*lpvgr.NextLink) != 0 -} - -// listP2SVpnGatewaysResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lpvgr ListP2SVpnGatewaysResult) listP2SVpnGatewaysResultPreparer(ctx context.Context) (*http.Request, error) { - if !lpvgr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lpvgr.NextLink))) -} - -// ListP2SVpnGatewaysResultPage contains a page of P2SVpnGateway values. -type ListP2SVpnGatewaysResultPage struct { - fn func(context.Context, ListP2SVpnGatewaysResult) (ListP2SVpnGatewaysResult, error) - lpvgr ListP2SVpnGatewaysResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListP2SVpnGatewaysResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListP2SVpnGatewaysResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lpvgr) - if err != nil { - return err - } - page.lpvgr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListP2SVpnGatewaysResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListP2SVpnGatewaysResultPage) NotDone() bool { - return !page.lpvgr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListP2SVpnGatewaysResultPage) Response() ListP2SVpnGatewaysResult { - return page.lpvgr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListP2SVpnGatewaysResultPage) Values() []P2SVpnGateway { - if page.lpvgr.IsEmpty() { - return nil - } - return *page.lpvgr.Value -} - -// Creates a new instance of the ListP2SVpnGatewaysResultPage type. -func NewListP2SVpnGatewaysResultPage(cur ListP2SVpnGatewaysResult, getNextPage func(context.Context, ListP2SVpnGatewaysResult) (ListP2SVpnGatewaysResult, error)) ListP2SVpnGatewaysResultPage { - return ListP2SVpnGatewaysResultPage{ - fn: getNextPage, - lpvgr: cur, - } -} - -// ListRouteMapsResult list of RouteMaps and a URL nextLink to get the next set of results. -type ListRouteMapsResult struct { - autorest.Response `json:"-"` - // Value - List of RouteMaps. - Value *[]RouteMap `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListRouteMapsResultIterator provides access to a complete listing of RouteMap values. -type ListRouteMapsResultIterator struct { - i int - page ListRouteMapsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListRouteMapsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListRouteMapsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListRouteMapsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListRouteMapsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListRouteMapsResultIterator) Response() ListRouteMapsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListRouteMapsResultIterator) Value() RouteMap { - if !iter.page.NotDone() { - return RouteMap{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListRouteMapsResultIterator type. -func NewListRouteMapsResultIterator(page ListRouteMapsResultPage) ListRouteMapsResultIterator { - return ListRouteMapsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lrmr ListRouteMapsResult) IsEmpty() bool { - return lrmr.Value == nil || len(*lrmr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lrmr ListRouteMapsResult) hasNextLink() bool { - return lrmr.NextLink != nil && len(*lrmr.NextLink) != 0 -} - -// listRouteMapsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lrmr ListRouteMapsResult) listRouteMapsResultPreparer(ctx context.Context) (*http.Request, error) { - if !lrmr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lrmr.NextLink))) -} - -// ListRouteMapsResultPage contains a page of RouteMap values. -type ListRouteMapsResultPage struct { - fn func(context.Context, ListRouteMapsResult) (ListRouteMapsResult, error) - lrmr ListRouteMapsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListRouteMapsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListRouteMapsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lrmr) - if err != nil { - return err - } - page.lrmr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListRouteMapsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListRouteMapsResultPage) NotDone() bool { - return !page.lrmr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListRouteMapsResultPage) Response() ListRouteMapsResult { - return page.lrmr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListRouteMapsResultPage) Values() []RouteMap { - if page.lrmr.IsEmpty() { - return nil - } - return *page.lrmr.Value -} - -// Creates a new instance of the ListRouteMapsResultPage type. -func NewListRouteMapsResultPage(cur ListRouteMapsResult, getNextPage func(context.Context, ListRouteMapsResult) (ListRouteMapsResult, error)) ListRouteMapsResultPage { - return ListRouteMapsResultPage{ - fn: getNextPage, - lrmr: cur, - } -} - -// ListRoutingIntentResult list of the routing intent result and a URL nextLink to get the next set of -// results. -type ListRoutingIntentResult struct { - autorest.Response `json:"-"` - // Value - List of RoutingIntent resource. - Value *[]RoutingIntent `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListRoutingIntentResultIterator provides access to a complete listing of RoutingIntent values. -type ListRoutingIntentResultIterator struct { - i int - page ListRoutingIntentResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListRoutingIntentResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListRoutingIntentResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListRoutingIntentResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListRoutingIntentResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListRoutingIntentResultIterator) Response() ListRoutingIntentResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListRoutingIntentResultIterator) Value() RoutingIntent { - if !iter.page.NotDone() { - return RoutingIntent{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListRoutingIntentResultIterator type. -func NewListRoutingIntentResultIterator(page ListRoutingIntentResultPage) ListRoutingIntentResultIterator { - return ListRoutingIntentResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lrir ListRoutingIntentResult) IsEmpty() bool { - return lrir.Value == nil || len(*lrir.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lrir ListRoutingIntentResult) hasNextLink() bool { - return lrir.NextLink != nil && len(*lrir.NextLink) != 0 -} - -// listRoutingIntentResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lrir ListRoutingIntentResult) listRoutingIntentResultPreparer(ctx context.Context) (*http.Request, error) { - if !lrir.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lrir.NextLink))) -} - -// ListRoutingIntentResultPage contains a page of RoutingIntent values. -type ListRoutingIntentResultPage struct { - fn func(context.Context, ListRoutingIntentResult) (ListRoutingIntentResult, error) - lrir ListRoutingIntentResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListRoutingIntentResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListRoutingIntentResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lrir) - if err != nil { - return err - } - page.lrir = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListRoutingIntentResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListRoutingIntentResultPage) NotDone() bool { - return !page.lrir.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListRoutingIntentResultPage) Response() ListRoutingIntentResult { - return page.lrir -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListRoutingIntentResultPage) Values() []RoutingIntent { - if page.lrir.IsEmpty() { - return nil - } - return *page.lrir.Value -} - -// Creates a new instance of the ListRoutingIntentResultPage type. -func NewListRoutingIntentResultPage(cur ListRoutingIntentResult, getNextPage func(context.Context, ListRoutingIntentResult) (ListRoutingIntentResult, error)) ListRoutingIntentResultPage { - return ListRoutingIntentResultPage{ - fn: getNextPage, - lrir: cur, - } -} - -// ListString ... -type ListString struct { - autorest.Response `json:"-"` - Value *[]string `json:"value,omitempty"` -} - -// ListVirtualHubBgpConnectionResults virtualHubBgpConnections list. -type ListVirtualHubBgpConnectionResults struct { - autorest.Response `json:"-"` - // Value - The list of VirtualHubBgpConnections. - Value *[]BgpConnection `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVirtualHubBgpConnectionResultsIterator provides access to a complete listing of BgpConnection -// values. -type ListVirtualHubBgpConnectionResultsIterator struct { - i int - page ListVirtualHubBgpConnectionResultsPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVirtualHubBgpConnectionResultsIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualHubBgpConnectionResultsIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVirtualHubBgpConnectionResultsIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVirtualHubBgpConnectionResultsIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVirtualHubBgpConnectionResultsIterator) Response() ListVirtualHubBgpConnectionResults { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVirtualHubBgpConnectionResultsIterator) Value() BgpConnection { - if !iter.page.NotDone() { - return BgpConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVirtualHubBgpConnectionResultsIterator type. -func NewListVirtualHubBgpConnectionResultsIterator(page ListVirtualHubBgpConnectionResultsPage) ListVirtualHubBgpConnectionResultsIterator { - return ListVirtualHubBgpConnectionResultsIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvhbcr ListVirtualHubBgpConnectionResults) IsEmpty() bool { - return lvhbcr.Value == nil || len(*lvhbcr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvhbcr ListVirtualHubBgpConnectionResults) hasNextLink() bool { - return lvhbcr.NextLink != nil && len(*lvhbcr.NextLink) != 0 -} - -// listVirtualHubBgpConnectionResultsPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvhbcr ListVirtualHubBgpConnectionResults) listVirtualHubBgpConnectionResultsPreparer(ctx context.Context) (*http.Request, error) { - if !lvhbcr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvhbcr.NextLink))) -} - -// ListVirtualHubBgpConnectionResultsPage contains a page of BgpConnection values. -type ListVirtualHubBgpConnectionResultsPage struct { - fn func(context.Context, ListVirtualHubBgpConnectionResults) (ListVirtualHubBgpConnectionResults, error) - lvhbcr ListVirtualHubBgpConnectionResults -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVirtualHubBgpConnectionResultsPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualHubBgpConnectionResultsPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvhbcr) - if err != nil { - return err - } - page.lvhbcr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVirtualHubBgpConnectionResultsPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVirtualHubBgpConnectionResultsPage) NotDone() bool { - return !page.lvhbcr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVirtualHubBgpConnectionResultsPage) Response() ListVirtualHubBgpConnectionResults { - return page.lvhbcr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVirtualHubBgpConnectionResultsPage) Values() []BgpConnection { - if page.lvhbcr.IsEmpty() { - return nil - } - return *page.lvhbcr.Value -} - -// Creates a new instance of the ListVirtualHubBgpConnectionResultsPage type. -func NewListVirtualHubBgpConnectionResultsPage(cur ListVirtualHubBgpConnectionResults, getNextPage func(context.Context, ListVirtualHubBgpConnectionResults) (ListVirtualHubBgpConnectionResults, error)) ListVirtualHubBgpConnectionResultsPage { - return ListVirtualHubBgpConnectionResultsPage{ - fn: getNextPage, - lvhbcr: cur, - } -} - -// ListVirtualHubIPConfigurationResults virtualHubIpConfigurations list. -type ListVirtualHubIPConfigurationResults struct { - autorest.Response `json:"-"` - // Value - The list of VirtualHubIpConfigurations. - Value *[]HubIPConfiguration `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVirtualHubIPConfigurationResultsIterator provides access to a complete listing of HubIPConfiguration -// values. -type ListVirtualHubIPConfigurationResultsIterator struct { - i int - page ListVirtualHubIPConfigurationResultsPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVirtualHubIPConfigurationResultsIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualHubIPConfigurationResultsIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVirtualHubIPConfigurationResultsIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVirtualHubIPConfigurationResultsIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVirtualHubIPConfigurationResultsIterator) Response() ListVirtualHubIPConfigurationResults { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVirtualHubIPConfigurationResultsIterator) Value() HubIPConfiguration { - if !iter.page.NotDone() { - return HubIPConfiguration{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVirtualHubIPConfigurationResultsIterator type. -func NewListVirtualHubIPConfigurationResultsIterator(page ListVirtualHubIPConfigurationResultsPage) ListVirtualHubIPConfigurationResultsIterator { - return ListVirtualHubIPConfigurationResultsIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvhicr ListVirtualHubIPConfigurationResults) IsEmpty() bool { - return lvhicr.Value == nil || len(*lvhicr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvhicr ListVirtualHubIPConfigurationResults) hasNextLink() bool { - return lvhicr.NextLink != nil && len(*lvhicr.NextLink) != 0 -} - -// listVirtualHubIPConfigurationResultsPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvhicr ListVirtualHubIPConfigurationResults) listVirtualHubIPConfigurationResultsPreparer(ctx context.Context) (*http.Request, error) { - if !lvhicr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvhicr.NextLink))) -} - -// ListVirtualHubIPConfigurationResultsPage contains a page of HubIPConfiguration values. -type ListVirtualHubIPConfigurationResultsPage struct { - fn func(context.Context, ListVirtualHubIPConfigurationResults) (ListVirtualHubIPConfigurationResults, error) - lvhicr ListVirtualHubIPConfigurationResults -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVirtualHubIPConfigurationResultsPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualHubIPConfigurationResultsPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvhicr) - if err != nil { - return err - } - page.lvhicr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVirtualHubIPConfigurationResultsPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVirtualHubIPConfigurationResultsPage) NotDone() bool { - return !page.lvhicr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVirtualHubIPConfigurationResultsPage) Response() ListVirtualHubIPConfigurationResults { - return page.lvhicr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVirtualHubIPConfigurationResultsPage) Values() []HubIPConfiguration { - if page.lvhicr.IsEmpty() { - return nil - } - return *page.lvhicr.Value -} - -// Creates a new instance of the ListVirtualHubIPConfigurationResultsPage type. -func NewListVirtualHubIPConfigurationResultsPage(cur ListVirtualHubIPConfigurationResults, getNextPage func(context.Context, ListVirtualHubIPConfigurationResults) (ListVirtualHubIPConfigurationResults, error)) ListVirtualHubIPConfigurationResultsPage { - return ListVirtualHubIPConfigurationResultsPage{ - fn: getNextPage, - lvhicr: cur, - } -} - -// ListVirtualHubRouteTableV2sResult list of VirtualHubRouteTableV2s and a URL nextLink to get the next set -// of results. -type ListVirtualHubRouteTableV2sResult struct { - autorest.Response `json:"-"` - // Value - List of VirtualHubRouteTableV2s. - Value *[]VirtualHubRouteTableV2 `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVirtualHubRouteTableV2sResultIterator provides access to a complete listing of -// VirtualHubRouteTableV2 values. -type ListVirtualHubRouteTableV2sResultIterator struct { - i int - page ListVirtualHubRouteTableV2sResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVirtualHubRouteTableV2sResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualHubRouteTableV2sResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVirtualHubRouteTableV2sResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVirtualHubRouteTableV2sResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVirtualHubRouteTableV2sResultIterator) Response() ListVirtualHubRouteTableV2sResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVirtualHubRouteTableV2sResultIterator) Value() VirtualHubRouteTableV2 { - if !iter.page.NotDone() { - return VirtualHubRouteTableV2{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVirtualHubRouteTableV2sResultIterator type. -func NewListVirtualHubRouteTableV2sResultIterator(page ListVirtualHubRouteTableV2sResultPage) ListVirtualHubRouteTableV2sResultIterator { - return ListVirtualHubRouteTableV2sResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvhrtvr ListVirtualHubRouteTableV2sResult) IsEmpty() bool { - return lvhrtvr.Value == nil || len(*lvhrtvr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvhrtvr ListVirtualHubRouteTableV2sResult) hasNextLink() bool { - return lvhrtvr.NextLink != nil && len(*lvhrtvr.NextLink) != 0 -} - -// listVirtualHubRouteTableV2sResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvhrtvr ListVirtualHubRouteTableV2sResult) listVirtualHubRouteTableV2sResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvhrtvr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvhrtvr.NextLink))) -} - -// ListVirtualHubRouteTableV2sResultPage contains a page of VirtualHubRouteTableV2 values. -type ListVirtualHubRouteTableV2sResultPage struct { - fn func(context.Context, ListVirtualHubRouteTableV2sResult) (ListVirtualHubRouteTableV2sResult, error) - lvhrtvr ListVirtualHubRouteTableV2sResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVirtualHubRouteTableV2sResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualHubRouteTableV2sResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvhrtvr) - if err != nil { - return err - } - page.lvhrtvr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVirtualHubRouteTableV2sResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVirtualHubRouteTableV2sResultPage) NotDone() bool { - return !page.lvhrtvr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVirtualHubRouteTableV2sResultPage) Response() ListVirtualHubRouteTableV2sResult { - return page.lvhrtvr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVirtualHubRouteTableV2sResultPage) Values() []VirtualHubRouteTableV2 { - if page.lvhrtvr.IsEmpty() { - return nil - } - return *page.lvhrtvr.Value -} - -// Creates a new instance of the ListVirtualHubRouteTableV2sResultPage type. -func NewListVirtualHubRouteTableV2sResultPage(cur ListVirtualHubRouteTableV2sResult, getNextPage func(context.Context, ListVirtualHubRouteTableV2sResult) (ListVirtualHubRouteTableV2sResult, error)) ListVirtualHubRouteTableV2sResultPage { - return ListVirtualHubRouteTableV2sResultPage{ - fn: getNextPage, - lvhrtvr: cur, - } -} - -// ListVirtualHubsResult result of the request to list VirtualHubs. It contains a list of VirtualHubs and a -// URL nextLink to get the next set of results. -type ListVirtualHubsResult struct { - autorest.Response `json:"-"` - // Value - List of VirtualHubs. - Value *[]VirtualHub `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVirtualHubsResultIterator provides access to a complete listing of VirtualHub values. -type ListVirtualHubsResultIterator struct { - i int - page ListVirtualHubsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVirtualHubsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualHubsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVirtualHubsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVirtualHubsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVirtualHubsResultIterator) Response() ListVirtualHubsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVirtualHubsResultIterator) Value() VirtualHub { - if !iter.page.NotDone() { - return VirtualHub{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVirtualHubsResultIterator type. -func NewListVirtualHubsResultIterator(page ListVirtualHubsResultPage) ListVirtualHubsResultIterator { - return ListVirtualHubsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvhr ListVirtualHubsResult) IsEmpty() bool { - return lvhr.Value == nil || len(*lvhr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvhr ListVirtualHubsResult) hasNextLink() bool { - return lvhr.NextLink != nil && len(*lvhr.NextLink) != 0 -} - -// listVirtualHubsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvhr ListVirtualHubsResult) listVirtualHubsResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvhr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvhr.NextLink))) -} - -// ListVirtualHubsResultPage contains a page of VirtualHub values. -type ListVirtualHubsResultPage struct { - fn func(context.Context, ListVirtualHubsResult) (ListVirtualHubsResult, error) - lvhr ListVirtualHubsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVirtualHubsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualHubsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvhr) - if err != nil { - return err - } - page.lvhr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVirtualHubsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVirtualHubsResultPage) NotDone() bool { - return !page.lvhr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVirtualHubsResultPage) Response() ListVirtualHubsResult { - return page.lvhr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVirtualHubsResultPage) Values() []VirtualHub { - if page.lvhr.IsEmpty() { - return nil - } - return *page.lvhr.Value -} - -// Creates a new instance of the ListVirtualHubsResultPage type. -func NewListVirtualHubsResultPage(cur ListVirtualHubsResult, getNextPage func(context.Context, ListVirtualHubsResult) (ListVirtualHubsResult, error)) ListVirtualHubsResultPage { - return ListVirtualHubsResultPage{ - fn: getNextPage, - lvhr: cur, - } -} - -// ListVirtualNetworkGatewayNatRulesResult result of the request to list all nat rules to a virtual network -// gateway. It contains a list of Nat rules and a URL nextLink to get the next set of results. -type ListVirtualNetworkGatewayNatRulesResult struct { - autorest.Response `json:"-"` - // Value - List of Nat Rules. - Value *[]VirtualNetworkGatewayNatRule `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVirtualNetworkGatewayNatRulesResultIterator provides access to a complete listing of -// VirtualNetworkGatewayNatRule values. -type ListVirtualNetworkGatewayNatRulesResultIterator struct { - i int - page ListVirtualNetworkGatewayNatRulesResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVirtualNetworkGatewayNatRulesResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualNetworkGatewayNatRulesResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVirtualNetworkGatewayNatRulesResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVirtualNetworkGatewayNatRulesResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVirtualNetworkGatewayNatRulesResultIterator) Response() ListVirtualNetworkGatewayNatRulesResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVirtualNetworkGatewayNatRulesResultIterator) Value() VirtualNetworkGatewayNatRule { - if !iter.page.NotDone() { - return VirtualNetworkGatewayNatRule{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVirtualNetworkGatewayNatRulesResultIterator type. -func NewListVirtualNetworkGatewayNatRulesResultIterator(page ListVirtualNetworkGatewayNatRulesResultPage) ListVirtualNetworkGatewayNatRulesResultIterator { - return ListVirtualNetworkGatewayNatRulesResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvngnrr ListVirtualNetworkGatewayNatRulesResult) IsEmpty() bool { - return lvngnrr.Value == nil || len(*lvngnrr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvngnrr ListVirtualNetworkGatewayNatRulesResult) hasNextLink() bool { - return lvngnrr.NextLink != nil && len(*lvngnrr.NextLink) != 0 -} - -// listVirtualNetworkGatewayNatRulesResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvngnrr ListVirtualNetworkGatewayNatRulesResult) listVirtualNetworkGatewayNatRulesResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvngnrr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvngnrr.NextLink))) -} - -// ListVirtualNetworkGatewayNatRulesResultPage contains a page of VirtualNetworkGatewayNatRule values. -type ListVirtualNetworkGatewayNatRulesResultPage struct { - fn func(context.Context, ListVirtualNetworkGatewayNatRulesResult) (ListVirtualNetworkGatewayNatRulesResult, error) - lvngnrr ListVirtualNetworkGatewayNatRulesResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVirtualNetworkGatewayNatRulesResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualNetworkGatewayNatRulesResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvngnrr) - if err != nil { - return err - } - page.lvngnrr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVirtualNetworkGatewayNatRulesResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVirtualNetworkGatewayNatRulesResultPage) NotDone() bool { - return !page.lvngnrr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVirtualNetworkGatewayNatRulesResultPage) Response() ListVirtualNetworkGatewayNatRulesResult { - return page.lvngnrr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVirtualNetworkGatewayNatRulesResultPage) Values() []VirtualNetworkGatewayNatRule { - if page.lvngnrr.IsEmpty() { - return nil - } - return *page.lvngnrr.Value -} - -// Creates a new instance of the ListVirtualNetworkGatewayNatRulesResultPage type. -func NewListVirtualNetworkGatewayNatRulesResultPage(cur ListVirtualNetworkGatewayNatRulesResult, getNextPage func(context.Context, ListVirtualNetworkGatewayNatRulesResult) (ListVirtualNetworkGatewayNatRulesResult, error)) ListVirtualNetworkGatewayNatRulesResultPage { - return ListVirtualNetworkGatewayNatRulesResultPage{ - fn: getNextPage, - lvngnrr: cur, - } -} - -// ListVirtualWANsResult result of the request to list VirtualWANs. It contains a list of VirtualWANs and a -// URL nextLink to get the next set of results. -type ListVirtualWANsResult struct { - autorest.Response `json:"-"` - // Value - List of VirtualWANs. - Value *[]VirtualWAN `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVirtualWANsResultIterator provides access to a complete listing of VirtualWAN values. -type ListVirtualWANsResultIterator struct { - i int - page ListVirtualWANsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVirtualWANsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualWANsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVirtualWANsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVirtualWANsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVirtualWANsResultIterator) Response() ListVirtualWANsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVirtualWANsResultIterator) Value() VirtualWAN { - if !iter.page.NotDone() { - return VirtualWAN{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVirtualWANsResultIterator type. -func NewListVirtualWANsResultIterator(page ListVirtualWANsResultPage) ListVirtualWANsResultIterator { - return ListVirtualWANsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvwnr ListVirtualWANsResult) IsEmpty() bool { - return lvwnr.Value == nil || len(*lvwnr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvwnr ListVirtualWANsResult) hasNextLink() bool { - return lvwnr.NextLink != nil && len(*lvwnr.NextLink) != 0 -} - -// listVirtualWANsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvwnr ListVirtualWANsResult) listVirtualWANsResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvwnr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvwnr.NextLink))) -} - -// ListVirtualWANsResultPage contains a page of VirtualWAN values. -type ListVirtualWANsResultPage struct { - fn func(context.Context, ListVirtualWANsResult) (ListVirtualWANsResult, error) - lvwnr ListVirtualWANsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVirtualWANsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVirtualWANsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvwnr) - if err != nil { - return err - } - page.lvwnr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVirtualWANsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVirtualWANsResultPage) NotDone() bool { - return !page.lvwnr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVirtualWANsResultPage) Response() ListVirtualWANsResult { - return page.lvwnr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVirtualWANsResultPage) Values() []VirtualWAN { - if page.lvwnr.IsEmpty() { - return nil - } - return *page.lvwnr.Value -} - -// Creates a new instance of the ListVirtualWANsResultPage type. -func NewListVirtualWANsResultPage(cur ListVirtualWANsResult, getNextPage func(context.Context, ListVirtualWANsResult) (ListVirtualWANsResult, error)) ListVirtualWANsResultPage { - return ListVirtualWANsResultPage{ - fn: getNextPage, - lvwnr: cur, - } -} - -// ListVpnConnectionsResult result of the request to list all vpn connections to a virtual wan vpn gateway. -// It contains a list of Vpn Connections and a URL nextLink to get the next set of results. -type ListVpnConnectionsResult struct { - autorest.Response `json:"-"` - // Value - List of Vpn Connections. - Value *[]VpnConnection `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVpnConnectionsResultIterator provides access to a complete listing of VpnConnection values. -type ListVpnConnectionsResultIterator struct { - i int - page ListVpnConnectionsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVpnConnectionsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnConnectionsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVpnConnectionsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVpnConnectionsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVpnConnectionsResultIterator) Response() ListVpnConnectionsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVpnConnectionsResultIterator) Value() VpnConnection { - if !iter.page.NotDone() { - return VpnConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVpnConnectionsResultIterator type. -func NewListVpnConnectionsResultIterator(page ListVpnConnectionsResultPage) ListVpnConnectionsResultIterator { - return ListVpnConnectionsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvcr ListVpnConnectionsResult) IsEmpty() bool { - return lvcr.Value == nil || len(*lvcr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvcr ListVpnConnectionsResult) hasNextLink() bool { - return lvcr.NextLink != nil && len(*lvcr.NextLink) != 0 -} - -// listVpnConnectionsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvcr ListVpnConnectionsResult) listVpnConnectionsResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvcr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvcr.NextLink))) -} - -// ListVpnConnectionsResultPage contains a page of VpnConnection values. -type ListVpnConnectionsResultPage struct { - fn func(context.Context, ListVpnConnectionsResult) (ListVpnConnectionsResult, error) - lvcr ListVpnConnectionsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVpnConnectionsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnConnectionsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvcr) - if err != nil { - return err - } - page.lvcr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVpnConnectionsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVpnConnectionsResultPage) NotDone() bool { - return !page.lvcr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVpnConnectionsResultPage) Response() ListVpnConnectionsResult { - return page.lvcr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVpnConnectionsResultPage) Values() []VpnConnection { - if page.lvcr.IsEmpty() { - return nil - } - return *page.lvcr.Value -} - -// Creates a new instance of the ListVpnConnectionsResultPage type. -func NewListVpnConnectionsResultPage(cur ListVpnConnectionsResult, getNextPage func(context.Context, ListVpnConnectionsResult) (ListVpnConnectionsResult, error)) ListVpnConnectionsResultPage { - return ListVpnConnectionsResultPage{ - fn: getNextPage, - lvcr: cur, - } -} - -// ListVpnGatewayNatRulesResult result of the request to list all nat rules to a virtual wan vpn gateway. -// It contains a list of Nat rules and a URL nextLink to get the next set of results. -type ListVpnGatewayNatRulesResult struct { - autorest.Response `json:"-"` - // Value - List of Nat Rules. - Value *[]VpnGatewayNatRule `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVpnGatewayNatRulesResultIterator provides access to a complete listing of VpnGatewayNatRule values. -type ListVpnGatewayNatRulesResultIterator struct { - i int - page ListVpnGatewayNatRulesResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVpnGatewayNatRulesResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnGatewayNatRulesResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVpnGatewayNatRulesResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVpnGatewayNatRulesResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVpnGatewayNatRulesResultIterator) Response() ListVpnGatewayNatRulesResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVpnGatewayNatRulesResultIterator) Value() VpnGatewayNatRule { - if !iter.page.NotDone() { - return VpnGatewayNatRule{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVpnGatewayNatRulesResultIterator type. -func NewListVpnGatewayNatRulesResultIterator(page ListVpnGatewayNatRulesResultPage) ListVpnGatewayNatRulesResultIterator { - return ListVpnGatewayNatRulesResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvgnrr ListVpnGatewayNatRulesResult) IsEmpty() bool { - return lvgnrr.Value == nil || len(*lvgnrr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvgnrr ListVpnGatewayNatRulesResult) hasNextLink() bool { - return lvgnrr.NextLink != nil && len(*lvgnrr.NextLink) != 0 -} - -// listVpnGatewayNatRulesResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvgnrr ListVpnGatewayNatRulesResult) listVpnGatewayNatRulesResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvgnrr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvgnrr.NextLink))) -} - -// ListVpnGatewayNatRulesResultPage contains a page of VpnGatewayNatRule values. -type ListVpnGatewayNatRulesResultPage struct { - fn func(context.Context, ListVpnGatewayNatRulesResult) (ListVpnGatewayNatRulesResult, error) - lvgnrr ListVpnGatewayNatRulesResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVpnGatewayNatRulesResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnGatewayNatRulesResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvgnrr) - if err != nil { - return err - } - page.lvgnrr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVpnGatewayNatRulesResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVpnGatewayNatRulesResultPage) NotDone() bool { - return !page.lvgnrr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVpnGatewayNatRulesResultPage) Response() ListVpnGatewayNatRulesResult { - return page.lvgnrr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVpnGatewayNatRulesResultPage) Values() []VpnGatewayNatRule { - if page.lvgnrr.IsEmpty() { - return nil - } - return *page.lvgnrr.Value -} - -// Creates a new instance of the ListVpnGatewayNatRulesResultPage type. -func NewListVpnGatewayNatRulesResultPage(cur ListVpnGatewayNatRulesResult, getNextPage func(context.Context, ListVpnGatewayNatRulesResult) (ListVpnGatewayNatRulesResult, error)) ListVpnGatewayNatRulesResultPage { - return ListVpnGatewayNatRulesResultPage{ - fn: getNextPage, - lvgnrr: cur, - } -} - -// ListVpnGatewaysResult result of the request to list VpnGateways. It contains a list of VpnGateways and a -// URL nextLink to get the next set of results. -type ListVpnGatewaysResult struct { - autorest.Response `json:"-"` - // Value - List of VpnGateways. - Value *[]VpnGateway `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVpnGatewaysResultIterator provides access to a complete listing of VpnGateway values. -type ListVpnGatewaysResultIterator struct { - i int - page ListVpnGatewaysResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVpnGatewaysResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnGatewaysResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVpnGatewaysResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVpnGatewaysResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVpnGatewaysResultIterator) Response() ListVpnGatewaysResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVpnGatewaysResultIterator) Value() VpnGateway { - if !iter.page.NotDone() { - return VpnGateway{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVpnGatewaysResultIterator type. -func NewListVpnGatewaysResultIterator(page ListVpnGatewaysResultPage) ListVpnGatewaysResultIterator { - return ListVpnGatewaysResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvgr ListVpnGatewaysResult) IsEmpty() bool { - return lvgr.Value == nil || len(*lvgr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvgr ListVpnGatewaysResult) hasNextLink() bool { - return lvgr.NextLink != nil && len(*lvgr.NextLink) != 0 -} - -// listVpnGatewaysResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvgr ListVpnGatewaysResult) listVpnGatewaysResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvgr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvgr.NextLink))) -} - -// ListVpnGatewaysResultPage contains a page of VpnGateway values. -type ListVpnGatewaysResultPage struct { - fn func(context.Context, ListVpnGatewaysResult) (ListVpnGatewaysResult, error) - lvgr ListVpnGatewaysResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVpnGatewaysResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnGatewaysResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvgr) - if err != nil { - return err - } - page.lvgr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVpnGatewaysResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVpnGatewaysResultPage) NotDone() bool { - return !page.lvgr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVpnGatewaysResultPage) Response() ListVpnGatewaysResult { - return page.lvgr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVpnGatewaysResultPage) Values() []VpnGateway { - if page.lvgr.IsEmpty() { - return nil - } - return *page.lvgr.Value -} - -// Creates a new instance of the ListVpnGatewaysResultPage type. -func NewListVpnGatewaysResultPage(cur ListVpnGatewaysResult, getNextPage func(context.Context, ListVpnGatewaysResult) (ListVpnGatewaysResult, error)) ListVpnGatewaysResultPage { - return ListVpnGatewaysResultPage{ - fn: getNextPage, - lvgr: cur, - } -} - -// ListVpnServerConfigurationPolicyGroupsResult result of the request to list -// VpnServerConfigurationPolicyGroups. It contains a list of VpnServerConfigurationPolicyGroups and a URL -// nextLink to get the next set of results. -type ListVpnServerConfigurationPolicyGroupsResult struct { - autorest.Response `json:"-"` - // Value - List of VpnServerConfigurationPolicyGroups. - Value *[]VpnServerConfigurationPolicyGroup `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVpnServerConfigurationPolicyGroupsResultIterator provides access to a complete listing of -// VpnServerConfigurationPolicyGroup values. -type ListVpnServerConfigurationPolicyGroupsResultIterator struct { - i int - page ListVpnServerConfigurationPolicyGroupsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVpnServerConfigurationPolicyGroupsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnServerConfigurationPolicyGroupsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVpnServerConfigurationPolicyGroupsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVpnServerConfigurationPolicyGroupsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVpnServerConfigurationPolicyGroupsResultIterator) Response() ListVpnServerConfigurationPolicyGroupsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVpnServerConfigurationPolicyGroupsResultIterator) Value() VpnServerConfigurationPolicyGroup { - if !iter.page.NotDone() { - return VpnServerConfigurationPolicyGroup{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVpnServerConfigurationPolicyGroupsResultIterator type. -func NewListVpnServerConfigurationPolicyGroupsResultIterator(page ListVpnServerConfigurationPolicyGroupsResultPage) ListVpnServerConfigurationPolicyGroupsResultIterator { - return ListVpnServerConfigurationPolicyGroupsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvscpgr ListVpnServerConfigurationPolicyGroupsResult) IsEmpty() bool { - return lvscpgr.Value == nil || len(*lvscpgr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvscpgr ListVpnServerConfigurationPolicyGroupsResult) hasNextLink() bool { - return lvscpgr.NextLink != nil && len(*lvscpgr.NextLink) != 0 -} - -// listVpnServerConfigurationPolicyGroupsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvscpgr ListVpnServerConfigurationPolicyGroupsResult) listVpnServerConfigurationPolicyGroupsResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvscpgr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvscpgr.NextLink))) -} - -// ListVpnServerConfigurationPolicyGroupsResultPage contains a page of VpnServerConfigurationPolicyGroup -// values. -type ListVpnServerConfigurationPolicyGroupsResultPage struct { - fn func(context.Context, ListVpnServerConfigurationPolicyGroupsResult) (ListVpnServerConfigurationPolicyGroupsResult, error) - lvscpgr ListVpnServerConfigurationPolicyGroupsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVpnServerConfigurationPolicyGroupsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnServerConfigurationPolicyGroupsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvscpgr) - if err != nil { - return err - } - page.lvscpgr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVpnServerConfigurationPolicyGroupsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVpnServerConfigurationPolicyGroupsResultPage) NotDone() bool { - return !page.lvscpgr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVpnServerConfigurationPolicyGroupsResultPage) Response() ListVpnServerConfigurationPolicyGroupsResult { - return page.lvscpgr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVpnServerConfigurationPolicyGroupsResultPage) Values() []VpnServerConfigurationPolicyGroup { - if page.lvscpgr.IsEmpty() { - return nil - } - return *page.lvscpgr.Value -} - -// Creates a new instance of the ListVpnServerConfigurationPolicyGroupsResultPage type. -func NewListVpnServerConfigurationPolicyGroupsResultPage(cur ListVpnServerConfigurationPolicyGroupsResult, getNextPage func(context.Context, ListVpnServerConfigurationPolicyGroupsResult) (ListVpnServerConfigurationPolicyGroupsResult, error)) ListVpnServerConfigurationPolicyGroupsResultPage { - return ListVpnServerConfigurationPolicyGroupsResultPage{ - fn: getNextPage, - lvscpgr: cur, - } -} - -// ListVpnServerConfigurationsResult result of the request to list all VpnServerConfigurations. It contains -// a list of VpnServerConfigurations and a URL nextLink to get the next set of results. -type ListVpnServerConfigurationsResult struct { - autorest.Response `json:"-"` - // Value - List of VpnServerConfigurations. - Value *[]VpnServerConfiguration `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVpnServerConfigurationsResultIterator provides access to a complete listing of -// VpnServerConfiguration values. -type ListVpnServerConfigurationsResultIterator struct { - i int - page ListVpnServerConfigurationsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVpnServerConfigurationsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnServerConfigurationsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVpnServerConfigurationsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVpnServerConfigurationsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVpnServerConfigurationsResultIterator) Response() ListVpnServerConfigurationsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVpnServerConfigurationsResultIterator) Value() VpnServerConfiguration { - if !iter.page.NotDone() { - return VpnServerConfiguration{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVpnServerConfigurationsResultIterator type. -func NewListVpnServerConfigurationsResultIterator(page ListVpnServerConfigurationsResultPage) ListVpnServerConfigurationsResultIterator { - return ListVpnServerConfigurationsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvscr ListVpnServerConfigurationsResult) IsEmpty() bool { - return lvscr.Value == nil || len(*lvscr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvscr ListVpnServerConfigurationsResult) hasNextLink() bool { - return lvscr.NextLink != nil && len(*lvscr.NextLink) != 0 -} - -// listVpnServerConfigurationsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvscr ListVpnServerConfigurationsResult) listVpnServerConfigurationsResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvscr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvscr.NextLink))) -} - -// ListVpnServerConfigurationsResultPage contains a page of VpnServerConfiguration values. -type ListVpnServerConfigurationsResultPage struct { - fn func(context.Context, ListVpnServerConfigurationsResult) (ListVpnServerConfigurationsResult, error) - lvscr ListVpnServerConfigurationsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVpnServerConfigurationsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnServerConfigurationsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvscr) - if err != nil { - return err - } - page.lvscr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVpnServerConfigurationsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVpnServerConfigurationsResultPage) NotDone() bool { - return !page.lvscr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVpnServerConfigurationsResultPage) Response() ListVpnServerConfigurationsResult { - return page.lvscr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVpnServerConfigurationsResultPage) Values() []VpnServerConfiguration { - if page.lvscr.IsEmpty() { - return nil - } - return *page.lvscr.Value -} - -// Creates a new instance of the ListVpnServerConfigurationsResultPage type. -func NewListVpnServerConfigurationsResultPage(cur ListVpnServerConfigurationsResult, getNextPage func(context.Context, ListVpnServerConfigurationsResult) (ListVpnServerConfigurationsResult, error)) ListVpnServerConfigurationsResultPage { - return ListVpnServerConfigurationsResultPage{ - fn: getNextPage, - lvscr: cur, - } -} - -// ListVpnSiteLinkConnectionsResult result of the request to list all vpn connections to a virtual wan vpn -// gateway. It contains a list of Vpn Connections and a URL nextLink to get the next set of results. -type ListVpnSiteLinkConnectionsResult struct { - autorest.Response `json:"-"` - // Value - List of VpnSiteLinkConnections. - Value *[]VpnSiteLinkConnection `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVpnSiteLinkConnectionsResultIterator provides access to a complete listing of VpnSiteLinkConnection -// values. -type ListVpnSiteLinkConnectionsResultIterator struct { - i int - page ListVpnSiteLinkConnectionsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVpnSiteLinkConnectionsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnSiteLinkConnectionsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVpnSiteLinkConnectionsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVpnSiteLinkConnectionsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVpnSiteLinkConnectionsResultIterator) Response() ListVpnSiteLinkConnectionsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVpnSiteLinkConnectionsResultIterator) Value() VpnSiteLinkConnection { - if !iter.page.NotDone() { - return VpnSiteLinkConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVpnSiteLinkConnectionsResultIterator type. -func NewListVpnSiteLinkConnectionsResultIterator(page ListVpnSiteLinkConnectionsResultPage) ListVpnSiteLinkConnectionsResultIterator { - return ListVpnSiteLinkConnectionsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvslcr ListVpnSiteLinkConnectionsResult) IsEmpty() bool { - return lvslcr.Value == nil || len(*lvslcr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvslcr ListVpnSiteLinkConnectionsResult) hasNextLink() bool { - return lvslcr.NextLink != nil && len(*lvslcr.NextLink) != 0 -} - -// listVpnSiteLinkConnectionsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvslcr ListVpnSiteLinkConnectionsResult) listVpnSiteLinkConnectionsResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvslcr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvslcr.NextLink))) -} - -// ListVpnSiteLinkConnectionsResultPage contains a page of VpnSiteLinkConnection values. -type ListVpnSiteLinkConnectionsResultPage struct { - fn func(context.Context, ListVpnSiteLinkConnectionsResult) (ListVpnSiteLinkConnectionsResult, error) - lvslcr ListVpnSiteLinkConnectionsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVpnSiteLinkConnectionsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnSiteLinkConnectionsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvslcr) - if err != nil { - return err - } - page.lvslcr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVpnSiteLinkConnectionsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVpnSiteLinkConnectionsResultPage) NotDone() bool { - return !page.lvslcr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVpnSiteLinkConnectionsResultPage) Response() ListVpnSiteLinkConnectionsResult { - return page.lvslcr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVpnSiteLinkConnectionsResultPage) Values() []VpnSiteLinkConnection { - if page.lvslcr.IsEmpty() { - return nil - } - return *page.lvslcr.Value -} - -// Creates a new instance of the ListVpnSiteLinkConnectionsResultPage type. -func NewListVpnSiteLinkConnectionsResultPage(cur ListVpnSiteLinkConnectionsResult, getNextPage func(context.Context, ListVpnSiteLinkConnectionsResult) (ListVpnSiteLinkConnectionsResult, error)) ListVpnSiteLinkConnectionsResultPage { - return ListVpnSiteLinkConnectionsResultPage{ - fn: getNextPage, - lvslcr: cur, - } -} - -// ListVpnSiteLinksResult result of the request to list VpnSiteLinks. It contains a list of VpnSiteLinks -// and a URL nextLink to get the next set of results. -type ListVpnSiteLinksResult struct { - autorest.Response `json:"-"` - // Value - List of VpnSitesLinks. - Value *[]VpnSiteLink `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVpnSiteLinksResultIterator provides access to a complete listing of VpnSiteLink values. -type ListVpnSiteLinksResultIterator struct { - i int - page ListVpnSiteLinksResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVpnSiteLinksResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnSiteLinksResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVpnSiteLinksResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVpnSiteLinksResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVpnSiteLinksResultIterator) Response() ListVpnSiteLinksResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVpnSiteLinksResultIterator) Value() VpnSiteLink { - if !iter.page.NotDone() { - return VpnSiteLink{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVpnSiteLinksResultIterator type. -func NewListVpnSiteLinksResultIterator(page ListVpnSiteLinksResultPage) ListVpnSiteLinksResultIterator { - return ListVpnSiteLinksResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvslr ListVpnSiteLinksResult) IsEmpty() bool { - return lvslr.Value == nil || len(*lvslr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvslr ListVpnSiteLinksResult) hasNextLink() bool { - return lvslr.NextLink != nil && len(*lvslr.NextLink) != 0 -} - -// listVpnSiteLinksResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvslr ListVpnSiteLinksResult) listVpnSiteLinksResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvslr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvslr.NextLink))) -} - -// ListVpnSiteLinksResultPage contains a page of VpnSiteLink values. -type ListVpnSiteLinksResultPage struct { - fn func(context.Context, ListVpnSiteLinksResult) (ListVpnSiteLinksResult, error) - lvslr ListVpnSiteLinksResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVpnSiteLinksResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnSiteLinksResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvslr) - if err != nil { - return err - } - page.lvslr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVpnSiteLinksResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVpnSiteLinksResultPage) NotDone() bool { - return !page.lvslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVpnSiteLinksResultPage) Response() ListVpnSiteLinksResult { - return page.lvslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVpnSiteLinksResultPage) Values() []VpnSiteLink { - if page.lvslr.IsEmpty() { - return nil - } - return *page.lvslr.Value -} - -// Creates a new instance of the ListVpnSiteLinksResultPage type. -func NewListVpnSiteLinksResultPage(cur ListVpnSiteLinksResult, getNextPage func(context.Context, ListVpnSiteLinksResult) (ListVpnSiteLinksResult, error)) ListVpnSiteLinksResultPage { - return ListVpnSiteLinksResultPage{ - fn: getNextPage, - lvslr: cur, - } -} - -// ListVpnSitesResult result of the request to list VpnSites. It contains a list of VpnSites and a URL -// nextLink to get the next set of results. -type ListVpnSitesResult struct { - autorest.Response `json:"-"` - // Value - List of VpnSites. - Value *[]VpnSite `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// ListVpnSitesResultIterator provides access to a complete listing of VpnSite values. -type ListVpnSitesResultIterator struct { - i int - page ListVpnSitesResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ListVpnSitesResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnSitesResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ListVpnSitesResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ListVpnSitesResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ListVpnSitesResultIterator) Response() ListVpnSitesResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ListVpnSitesResultIterator) Value() VpnSite { - if !iter.page.NotDone() { - return VpnSite{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ListVpnSitesResultIterator type. -func NewListVpnSitesResultIterator(page ListVpnSitesResultPage) ListVpnSitesResultIterator { - return ListVpnSitesResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lvsr ListVpnSitesResult) IsEmpty() bool { - return lvsr.Value == nil || len(*lvsr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lvsr ListVpnSitesResult) hasNextLink() bool { - return lvsr.NextLink != nil && len(*lvsr.NextLink) != 0 -} - -// listVpnSitesResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lvsr ListVpnSitesResult) listVpnSitesResultPreparer(ctx context.Context) (*http.Request, error) { - if !lvsr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lvsr.NextLink))) -} - -// ListVpnSitesResultPage contains a page of VpnSite values. -type ListVpnSitesResultPage struct { - fn func(context.Context, ListVpnSitesResult) (ListVpnSitesResult, error) - lvsr ListVpnSitesResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ListVpnSitesResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ListVpnSitesResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lvsr) - if err != nil { - return err - } - page.lvsr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ListVpnSitesResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ListVpnSitesResultPage) NotDone() bool { - return !page.lvsr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ListVpnSitesResultPage) Response() ListVpnSitesResult { - return page.lvsr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ListVpnSitesResultPage) Values() []VpnSite { - if page.lvsr.IsEmpty() { - return nil - } - return *page.lvsr.Value -} - -// Creates a new instance of the ListVpnSitesResultPage type. -func NewListVpnSitesResultPage(cur ListVpnSitesResult, getNextPage func(context.Context, ListVpnSitesResult) (ListVpnSitesResult, error)) ListVpnSitesResultPage { - return ListVpnSitesResultPage{ - fn: getNextPage, - lvsr: cur, - } -} - -// LoadBalancer loadBalancer resource. -type LoadBalancer struct { - autorest.Response `json:"-"` - // ExtendedLocation - The extended location of the load balancer. - ExtendedLocation *ExtendedLocation `json:"extendedLocation,omitempty"` - // Sku - The load balancer SKU. - Sku *LoadBalancerSku `json:"sku,omitempty"` - // LoadBalancerPropertiesFormat - Properties of load balancer. - *LoadBalancerPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for LoadBalancer. -func (lb LoadBalancer) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lb.ExtendedLocation != nil { - objectMap["extendedLocation"] = lb.ExtendedLocation - } - if lb.Sku != nil { - objectMap["sku"] = lb.Sku - } - if lb.LoadBalancerPropertiesFormat != nil { - objectMap["properties"] = lb.LoadBalancerPropertiesFormat - } - if lb.ID != nil { - objectMap["id"] = lb.ID - } - if lb.Location != nil { - objectMap["location"] = lb.Location - } - if lb.Tags != nil { - objectMap["tags"] = lb.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for LoadBalancer struct. -func (lb *LoadBalancer) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "extendedLocation": - if v != nil { - var extendedLocation ExtendedLocation - err = json.Unmarshal(*v, &extendedLocation) - if err != nil { - return err - } - lb.ExtendedLocation = &extendedLocation - } - case "sku": - if v != nil { - var sku LoadBalancerSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - lb.Sku = &sku - } - case "properties": - if v != nil { - var loadBalancerPropertiesFormat LoadBalancerPropertiesFormat - err = json.Unmarshal(*v, &loadBalancerPropertiesFormat) - if err != nil { - return err - } - lb.LoadBalancerPropertiesFormat = &loadBalancerPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - lb.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - lb.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - lb.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - lb.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - lb.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - lb.Tags = tags - } - } - } - - return nil -} - -// LoadBalancerBackendAddress load balancer backend addresses. -type LoadBalancerBackendAddress struct { - // LoadBalancerBackendAddressPropertiesFormat - Properties of load balancer backend address pool. - *LoadBalancerBackendAddressPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the backend address. - Name *string `json:"name,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerBackendAddress. -func (lbba LoadBalancerBackendAddress) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lbba.LoadBalancerBackendAddressPropertiesFormat != nil { - objectMap["properties"] = lbba.LoadBalancerBackendAddressPropertiesFormat - } - if lbba.Name != nil { - objectMap["name"] = lbba.Name - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for LoadBalancerBackendAddress struct. -func (lbba *LoadBalancerBackendAddress) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var loadBalancerBackendAddressPropertiesFormat LoadBalancerBackendAddressPropertiesFormat - err = json.Unmarshal(*v, &loadBalancerBackendAddressPropertiesFormat) - if err != nil { - return err - } - lbba.LoadBalancerBackendAddressPropertiesFormat = &loadBalancerBackendAddressPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - lbba.Name = &name - } - } - } - - return nil -} - -// LoadBalancerBackendAddressPoolListResult response for ListBackendAddressPool API service call. -type LoadBalancerBackendAddressPoolListResult struct { - autorest.Response `json:"-"` - // Value - A list of backend address pools in a load balancer. - Value *[]BackendAddressPool `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerBackendAddressPoolListResult. -func (lbbaplr LoadBalancerBackendAddressPoolListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lbbaplr.Value != nil { - objectMap["value"] = lbbaplr.Value - } - return json.Marshal(objectMap) -} - -// LoadBalancerBackendAddressPoolListResultIterator provides access to a complete listing of -// BackendAddressPool values. -type LoadBalancerBackendAddressPoolListResultIterator struct { - i int - page LoadBalancerBackendAddressPoolListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LoadBalancerBackendAddressPoolListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerBackendAddressPoolListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LoadBalancerBackendAddressPoolListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LoadBalancerBackendAddressPoolListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LoadBalancerBackendAddressPoolListResultIterator) Response() LoadBalancerBackendAddressPoolListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LoadBalancerBackendAddressPoolListResultIterator) Value() BackendAddressPool { - if !iter.page.NotDone() { - return BackendAddressPool{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LoadBalancerBackendAddressPoolListResultIterator type. -func NewLoadBalancerBackendAddressPoolListResultIterator(page LoadBalancerBackendAddressPoolListResultPage) LoadBalancerBackendAddressPoolListResultIterator { - return LoadBalancerBackendAddressPoolListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lbbaplr LoadBalancerBackendAddressPoolListResult) IsEmpty() bool { - return lbbaplr.Value == nil || len(*lbbaplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lbbaplr LoadBalancerBackendAddressPoolListResult) hasNextLink() bool { - return lbbaplr.NextLink != nil && len(*lbbaplr.NextLink) != 0 -} - -// loadBalancerBackendAddressPoolListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lbbaplr LoadBalancerBackendAddressPoolListResult) loadBalancerBackendAddressPoolListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lbbaplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lbbaplr.NextLink))) -} - -// LoadBalancerBackendAddressPoolListResultPage contains a page of BackendAddressPool values. -type LoadBalancerBackendAddressPoolListResultPage struct { - fn func(context.Context, LoadBalancerBackendAddressPoolListResult) (LoadBalancerBackendAddressPoolListResult, error) - lbbaplr LoadBalancerBackendAddressPoolListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LoadBalancerBackendAddressPoolListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerBackendAddressPoolListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lbbaplr) - if err != nil { - return err - } - page.lbbaplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LoadBalancerBackendAddressPoolListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LoadBalancerBackendAddressPoolListResultPage) NotDone() bool { - return !page.lbbaplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LoadBalancerBackendAddressPoolListResultPage) Response() LoadBalancerBackendAddressPoolListResult { - return page.lbbaplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LoadBalancerBackendAddressPoolListResultPage) Values() []BackendAddressPool { - if page.lbbaplr.IsEmpty() { - return nil - } - return *page.lbbaplr.Value -} - -// Creates a new instance of the LoadBalancerBackendAddressPoolListResultPage type. -func NewLoadBalancerBackendAddressPoolListResultPage(cur LoadBalancerBackendAddressPoolListResult, getNextPage func(context.Context, LoadBalancerBackendAddressPoolListResult) (LoadBalancerBackendAddressPoolListResult, error)) LoadBalancerBackendAddressPoolListResultPage { - return LoadBalancerBackendAddressPoolListResultPage{ - fn: getNextPage, - lbbaplr: cur, - } -} - -// LoadBalancerBackendAddressPoolsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type LoadBalancerBackendAddressPoolsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LoadBalancerBackendAddressPoolsClient) (BackendAddressPool, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LoadBalancerBackendAddressPoolsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LoadBalancerBackendAddressPoolsCreateOrUpdateFuture.Result. -func (future *LoadBalancerBackendAddressPoolsCreateOrUpdateFuture) result(client LoadBalancerBackendAddressPoolsClient) (bap BackendAddressPool, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - bap.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LoadBalancerBackendAddressPoolsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if bap.Response.Response, err = future.GetResult(sender); err == nil && bap.Response.Response.StatusCode != http.StatusNoContent { - bap, err = client.CreateOrUpdateResponder(bap.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsCreateOrUpdateFuture", "Result", bap.Response.Response, "Failure responding to request") - } - } - return -} - -// LoadBalancerBackendAddressPoolsDeleteFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type LoadBalancerBackendAddressPoolsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LoadBalancerBackendAddressPoolsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LoadBalancerBackendAddressPoolsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LoadBalancerBackendAddressPoolsDeleteFuture.Result. -func (future *LoadBalancerBackendAddressPoolsDeleteFuture) result(client LoadBalancerBackendAddressPoolsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancerBackendAddressPoolsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LoadBalancerBackendAddressPoolsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// LoadBalancerBackendAddressPropertiesFormat properties of the load balancer backend addresses. -type LoadBalancerBackendAddressPropertiesFormat struct { - // VirtualNetwork - Reference to an existing virtual network. - VirtualNetwork *SubResource `json:"virtualNetwork,omitempty"` - // Subnet - Reference to an existing subnet. - Subnet *SubResource `json:"subnet,omitempty"` - // IPAddress - IP Address belonging to the referenced virtual network. - IPAddress *string `json:"ipAddress,omitempty"` - // NetworkInterfaceIPConfiguration - READ-ONLY; Reference to IP address defined in network interfaces. - NetworkInterfaceIPConfiguration *SubResource `json:"networkInterfaceIPConfiguration,omitempty"` - // LoadBalancerFrontendIPConfiguration - Reference to the frontend ip address configuration defined in regional loadbalancer. - LoadBalancerFrontendIPConfiguration *SubResource `json:"loadBalancerFrontendIPConfiguration,omitempty"` - // InboundNatRulesPortMapping - READ-ONLY; Collection of inbound NAT rule port mappings. - InboundNatRulesPortMapping *[]NatRulePortMapping `json:"inboundNatRulesPortMapping,omitempty"` - // AdminState - A list of administrative states which once set can override health probe so that Load Balancer will always forward new connections to backend, or deny new connections and reset existing connections. Possible values include: 'LoadBalancerBackendAddressAdminStateNone', 'LoadBalancerBackendAddressAdminStateUp', 'LoadBalancerBackendAddressAdminStateDown', 'LoadBalancerBackendAddressAdminStateDrain' - AdminState LoadBalancerBackendAddressAdminState `json:"adminState,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerBackendAddressPropertiesFormat. -func (lbbapf LoadBalancerBackendAddressPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lbbapf.VirtualNetwork != nil { - objectMap["virtualNetwork"] = lbbapf.VirtualNetwork - } - if lbbapf.Subnet != nil { - objectMap["subnet"] = lbbapf.Subnet - } - if lbbapf.IPAddress != nil { - objectMap["ipAddress"] = lbbapf.IPAddress - } - if lbbapf.LoadBalancerFrontendIPConfiguration != nil { - objectMap["loadBalancerFrontendIPConfiguration"] = lbbapf.LoadBalancerFrontendIPConfiguration - } - if lbbapf.AdminState != "" { - objectMap["adminState"] = lbbapf.AdminState - } - return json.Marshal(objectMap) -} - -// LoadBalancerFrontendIPConfigurationListResult response for ListFrontendIPConfiguration API service call. -type LoadBalancerFrontendIPConfigurationListResult struct { - autorest.Response `json:"-"` - // Value - A list of frontend IP configurations in a load balancer. - Value *[]FrontendIPConfiguration `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerFrontendIPConfigurationListResult. -func (lbficlr LoadBalancerFrontendIPConfigurationListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lbficlr.Value != nil { - objectMap["value"] = lbficlr.Value - } - return json.Marshal(objectMap) -} - -// LoadBalancerFrontendIPConfigurationListResultIterator provides access to a complete listing of -// FrontendIPConfiguration values. -type LoadBalancerFrontendIPConfigurationListResultIterator struct { - i int - page LoadBalancerFrontendIPConfigurationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LoadBalancerFrontendIPConfigurationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerFrontendIPConfigurationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LoadBalancerFrontendIPConfigurationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LoadBalancerFrontendIPConfigurationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LoadBalancerFrontendIPConfigurationListResultIterator) Response() LoadBalancerFrontendIPConfigurationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LoadBalancerFrontendIPConfigurationListResultIterator) Value() FrontendIPConfiguration { - if !iter.page.NotDone() { - return FrontendIPConfiguration{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LoadBalancerFrontendIPConfigurationListResultIterator type. -func NewLoadBalancerFrontendIPConfigurationListResultIterator(page LoadBalancerFrontendIPConfigurationListResultPage) LoadBalancerFrontendIPConfigurationListResultIterator { - return LoadBalancerFrontendIPConfigurationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lbficlr LoadBalancerFrontendIPConfigurationListResult) IsEmpty() bool { - return lbficlr.Value == nil || len(*lbficlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lbficlr LoadBalancerFrontendIPConfigurationListResult) hasNextLink() bool { - return lbficlr.NextLink != nil && len(*lbficlr.NextLink) != 0 -} - -// loadBalancerFrontendIPConfigurationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lbficlr LoadBalancerFrontendIPConfigurationListResult) loadBalancerFrontendIPConfigurationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lbficlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lbficlr.NextLink))) -} - -// LoadBalancerFrontendIPConfigurationListResultPage contains a page of FrontendIPConfiguration values. -type LoadBalancerFrontendIPConfigurationListResultPage struct { - fn func(context.Context, LoadBalancerFrontendIPConfigurationListResult) (LoadBalancerFrontendIPConfigurationListResult, error) - lbficlr LoadBalancerFrontendIPConfigurationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LoadBalancerFrontendIPConfigurationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerFrontendIPConfigurationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lbficlr) - if err != nil { - return err - } - page.lbficlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LoadBalancerFrontendIPConfigurationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LoadBalancerFrontendIPConfigurationListResultPage) NotDone() bool { - return !page.lbficlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LoadBalancerFrontendIPConfigurationListResultPage) Response() LoadBalancerFrontendIPConfigurationListResult { - return page.lbficlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LoadBalancerFrontendIPConfigurationListResultPage) Values() []FrontendIPConfiguration { - if page.lbficlr.IsEmpty() { - return nil - } - return *page.lbficlr.Value -} - -// Creates a new instance of the LoadBalancerFrontendIPConfigurationListResultPage type. -func NewLoadBalancerFrontendIPConfigurationListResultPage(cur LoadBalancerFrontendIPConfigurationListResult, getNextPage func(context.Context, LoadBalancerFrontendIPConfigurationListResult) (LoadBalancerFrontendIPConfigurationListResult, error)) LoadBalancerFrontendIPConfigurationListResultPage { - return LoadBalancerFrontendIPConfigurationListResultPage{ - fn: getNextPage, - lbficlr: cur, - } -} - -// LoadBalancerListResult response for ListLoadBalancers API service call. -type LoadBalancerListResult struct { - autorest.Response `json:"-"` - // Value - A list of load balancers in a resource group. - Value *[]LoadBalancer `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerListResult. -func (lblr LoadBalancerListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lblr.Value != nil { - objectMap["value"] = lblr.Value - } - return json.Marshal(objectMap) -} - -// LoadBalancerListResultIterator provides access to a complete listing of LoadBalancer values. -type LoadBalancerListResultIterator struct { - i int - page LoadBalancerListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LoadBalancerListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LoadBalancerListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LoadBalancerListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LoadBalancerListResultIterator) Response() LoadBalancerListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LoadBalancerListResultIterator) Value() LoadBalancer { - if !iter.page.NotDone() { - return LoadBalancer{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LoadBalancerListResultIterator type. -func NewLoadBalancerListResultIterator(page LoadBalancerListResultPage) LoadBalancerListResultIterator { - return LoadBalancerListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lblr LoadBalancerListResult) IsEmpty() bool { - return lblr.Value == nil || len(*lblr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lblr LoadBalancerListResult) hasNextLink() bool { - return lblr.NextLink != nil && len(*lblr.NextLink) != 0 -} - -// loadBalancerListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lblr LoadBalancerListResult) loadBalancerListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lblr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lblr.NextLink))) -} - -// LoadBalancerListResultPage contains a page of LoadBalancer values. -type LoadBalancerListResultPage struct { - fn func(context.Context, LoadBalancerListResult) (LoadBalancerListResult, error) - lblr LoadBalancerListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LoadBalancerListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lblr) - if err != nil { - return err - } - page.lblr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LoadBalancerListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LoadBalancerListResultPage) NotDone() bool { - return !page.lblr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LoadBalancerListResultPage) Response() LoadBalancerListResult { - return page.lblr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LoadBalancerListResultPage) Values() []LoadBalancer { - if page.lblr.IsEmpty() { - return nil - } - return *page.lblr.Value -} - -// Creates a new instance of the LoadBalancerListResultPage type. -func NewLoadBalancerListResultPage(cur LoadBalancerListResult, getNextPage func(context.Context, LoadBalancerListResult) (LoadBalancerListResult, error)) LoadBalancerListResultPage { - return LoadBalancerListResultPage{ - fn: getNextPage, - lblr: cur, - } -} - -// LoadBalancerLoadBalancingRuleListResult response for ListLoadBalancingRule API service call. -type LoadBalancerLoadBalancingRuleListResult struct { - autorest.Response `json:"-"` - // Value - A list of load balancing rules in a load balancer. - Value *[]LoadBalancingRule `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerLoadBalancingRuleListResult. -func (lblbrlr LoadBalancerLoadBalancingRuleListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lblbrlr.Value != nil { - objectMap["value"] = lblbrlr.Value - } - return json.Marshal(objectMap) -} - -// LoadBalancerLoadBalancingRuleListResultIterator provides access to a complete listing of -// LoadBalancingRule values. -type LoadBalancerLoadBalancingRuleListResultIterator struct { - i int - page LoadBalancerLoadBalancingRuleListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LoadBalancerLoadBalancingRuleListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRuleListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LoadBalancerLoadBalancingRuleListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LoadBalancerLoadBalancingRuleListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LoadBalancerLoadBalancingRuleListResultIterator) Response() LoadBalancerLoadBalancingRuleListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LoadBalancerLoadBalancingRuleListResultIterator) Value() LoadBalancingRule { - if !iter.page.NotDone() { - return LoadBalancingRule{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LoadBalancerLoadBalancingRuleListResultIterator type. -func NewLoadBalancerLoadBalancingRuleListResultIterator(page LoadBalancerLoadBalancingRuleListResultPage) LoadBalancerLoadBalancingRuleListResultIterator { - return LoadBalancerLoadBalancingRuleListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lblbrlr LoadBalancerLoadBalancingRuleListResult) IsEmpty() bool { - return lblbrlr.Value == nil || len(*lblbrlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lblbrlr LoadBalancerLoadBalancingRuleListResult) hasNextLink() bool { - return lblbrlr.NextLink != nil && len(*lblbrlr.NextLink) != 0 -} - -// loadBalancerLoadBalancingRuleListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lblbrlr LoadBalancerLoadBalancingRuleListResult) loadBalancerLoadBalancingRuleListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lblbrlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lblbrlr.NextLink))) -} - -// LoadBalancerLoadBalancingRuleListResultPage contains a page of LoadBalancingRule values. -type LoadBalancerLoadBalancingRuleListResultPage struct { - fn func(context.Context, LoadBalancerLoadBalancingRuleListResult) (LoadBalancerLoadBalancingRuleListResult, error) - lblbrlr LoadBalancerLoadBalancingRuleListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LoadBalancerLoadBalancingRuleListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerLoadBalancingRuleListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lblbrlr) - if err != nil { - return err - } - page.lblbrlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LoadBalancerLoadBalancingRuleListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LoadBalancerLoadBalancingRuleListResultPage) NotDone() bool { - return !page.lblbrlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LoadBalancerLoadBalancingRuleListResultPage) Response() LoadBalancerLoadBalancingRuleListResult { - return page.lblbrlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LoadBalancerLoadBalancingRuleListResultPage) Values() []LoadBalancingRule { - if page.lblbrlr.IsEmpty() { - return nil - } - return *page.lblbrlr.Value -} - -// Creates a new instance of the LoadBalancerLoadBalancingRuleListResultPage type. -func NewLoadBalancerLoadBalancingRuleListResultPage(cur LoadBalancerLoadBalancingRuleListResult, getNextPage func(context.Context, LoadBalancerLoadBalancingRuleListResult) (LoadBalancerLoadBalancingRuleListResult, error)) LoadBalancerLoadBalancingRuleListResultPage { - return LoadBalancerLoadBalancingRuleListResultPage{ - fn: getNextPage, - lblbrlr: cur, - } -} - -// LoadBalancerOutboundRuleListResult response for ListOutboundRule API service call. -type LoadBalancerOutboundRuleListResult struct { - autorest.Response `json:"-"` - // Value - A list of outbound rules in a load balancer. - Value *[]OutboundRule `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerOutboundRuleListResult. -func (lborlr LoadBalancerOutboundRuleListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lborlr.Value != nil { - objectMap["value"] = lborlr.Value - } - return json.Marshal(objectMap) -} - -// LoadBalancerOutboundRuleListResultIterator provides access to a complete listing of OutboundRule values. -type LoadBalancerOutboundRuleListResultIterator struct { - i int - page LoadBalancerOutboundRuleListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LoadBalancerOutboundRuleListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerOutboundRuleListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LoadBalancerOutboundRuleListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LoadBalancerOutboundRuleListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LoadBalancerOutboundRuleListResultIterator) Response() LoadBalancerOutboundRuleListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LoadBalancerOutboundRuleListResultIterator) Value() OutboundRule { - if !iter.page.NotDone() { - return OutboundRule{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LoadBalancerOutboundRuleListResultIterator type. -func NewLoadBalancerOutboundRuleListResultIterator(page LoadBalancerOutboundRuleListResultPage) LoadBalancerOutboundRuleListResultIterator { - return LoadBalancerOutboundRuleListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lborlr LoadBalancerOutboundRuleListResult) IsEmpty() bool { - return lborlr.Value == nil || len(*lborlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lborlr LoadBalancerOutboundRuleListResult) hasNextLink() bool { - return lborlr.NextLink != nil && len(*lborlr.NextLink) != 0 -} - -// loadBalancerOutboundRuleListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lborlr LoadBalancerOutboundRuleListResult) loadBalancerOutboundRuleListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lborlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lborlr.NextLink))) -} - -// LoadBalancerOutboundRuleListResultPage contains a page of OutboundRule values. -type LoadBalancerOutboundRuleListResultPage struct { - fn func(context.Context, LoadBalancerOutboundRuleListResult) (LoadBalancerOutboundRuleListResult, error) - lborlr LoadBalancerOutboundRuleListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LoadBalancerOutboundRuleListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerOutboundRuleListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lborlr) - if err != nil { - return err - } - page.lborlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LoadBalancerOutboundRuleListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LoadBalancerOutboundRuleListResultPage) NotDone() bool { - return !page.lborlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LoadBalancerOutboundRuleListResultPage) Response() LoadBalancerOutboundRuleListResult { - return page.lborlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LoadBalancerOutboundRuleListResultPage) Values() []OutboundRule { - if page.lborlr.IsEmpty() { - return nil - } - return *page.lborlr.Value -} - -// Creates a new instance of the LoadBalancerOutboundRuleListResultPage type. -func NewLoadBalancerOutboundRuleListResultPage(cur LoadBalancerOutboundRuleListResult, getNextPage func(context.Context, LoadBalancerOutboundRuleListResult) (LoadBalancerOutboundRuleListResult, error)) LoadBalancerOutboundRuleListResultPage { - return LoadBalancerOutboundRuleListResultPage{ - fn: getNextPage, - lborlr: cur, - } -} - -// LoadBalancerProbeListResult response for ListProbe API service call. -type LoadBalancerProbeListResult struct { - autorest.Response `json:"-"` - // Value - A list of probes in a load balancer. - Value *[]Probe `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerProbeListResult. -func (lbplr LoadBalancerProbeListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lbplr.Value != nil { - objectMap["value"] = lbplr.Value - } - return json.Marshal(objectMap) -} - -// LoadBalancerProbeListResultIterator provides access to a complete listing of Probe values. -type LoadBalancerProbeListResultIterator struct { - i int - page LoadBalancerProbeListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LoadBalancerProbeListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerProbeListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LoadBalancerProbeListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LoadBalancerProbeListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LoadBalancerProbeListResultIterator) Response() LoadBalancerProbeListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LoadBalancerProbeListResultIterator) Value() Probe { - if !iter.page.NotDone() { - return Probe{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LoadBalancerProbeListResultIterator type. -func NewLoadBalancerProbeListResultIterator(page LoadBalancerProbeListResultPage) LoadBalancerProbeListResultIterator { - return LoadBalancerProbeListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lbplr LoadBalancerProbeListResult) IsEmpty() bool { - return lbplr.Value == nil || len(*lbplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lbplr LoadBalancerProbeListResult) hasNextLink() bool { - return lbplr.NextLink != nil && len(*lbplr.NextLink) != 0 -} - -// loadBalancerProbeListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lbplr LoadBalancerProbeListResult) loadBalancerProbeListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lbplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lbplr.NextLink))) -} - -// LoadBalancerProbeListResultPage contains a page of Probe values. -type LoadBalancerProbeListResultPage struct { - fn func(context.Context, LoadBalancerProbeListResult) (LoadBalancerProbeListResult, error) - lbplr LoadBalancerProbeListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LoadBalancerProbeListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancerProbeListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lbplr) - if err != nil { - return err - } - page.lbplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LoadBalancerProbeListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LoadBalancerProbeListResultPage) NotDone() bool { - return !page.lbplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LoadBalancerProbeListResultPage) Response() LoadBalancerProbeListResult { - return page.lbplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LoadBalancerProbeListResultPage) Values() []Probe { - if page.lbplr.IsEmpty() { - return nil - } - return *page.lbplr.Value -} - -// Creates a new instance of the LoadBalancerProbeListResultPage type. -func NewLoadBalancerProbeListResultPage(cur LoadBalancerProbeListResult, getNextPage func(context.Context, LoadBalancerProbeListResult) (LoadBalancerProbeListResult, error)) LoadBalancerProbeListResultPage { - return LoadBalancerProbeListResultPage{ - fn: getNextPage, - lbplr: cur, - } -} - -// LoadBalancerPropertiesFormat properties of the load balancer. -type LoadBalancerPropertiesFormat struct { - // FrontendIPConfigurations - Object representing the frontend IPs to be used for the load balancer. - FrontendIPConfigurations *[]FrontendIPConfiguration `json:"frontendIPConfigurations,omitempty"` - // BackendAddressPools - Collection of backend address pools used by a load balancer. - BackendAddressPools *[]BackendAddressPool `json:"backendAddressPools,omitempty"` - // LoadBalancingRules - Object collection representing the load balancing rules Gets the provisioning. - LoadBalancingRules *[]LoadBalancingRule `json:"loadBalancingRules,omitempty"` - // Probes - Collection of probe objects used in the load balancer. - Probes *[]Probe `json:"probes,omitempty"` - // InboundNatRules - Collection of inbound NAT Rules used by a load balancer. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. - InboundNatRules *[]InboundNatRule `json:"inboundNatRules,omitempty"` - // InboundNatPools - Defines an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. - InboundNatPools *[]InboundNatPool `json:"inboundNatPools,omitempty"` - // OutboundRules - The outbound rules. - OutboundRules *[]OutboundRule `json:"outboundRules,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the load balancer resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the load balancer resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerPropertiesFormat. -func (lbpf LoadBalancerPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lbpf.FrontendIPConfigurations != nil { - objectMap["frontendIPConfigurations"] = lbpf.FrontendIPConfigurations - } - if lbpf.BackendAddressPools != nil { - objectMap["backendAddressPools"] = lbpf.BackendAddressPools - } - if lbpf.LoadBalancingRules != nil { - objectMap["loadBalancingRules"] = lbpf.LoadBalancingRules - } - if lbpf.Probes != nil { - objectMap["probes"] = lbpf.Probes - } - if lbpf.InboundNatRules != nil { - objectMap["inboundNatRules"] = lbpf.InboundNatRules - } - if lbpf.InboundNatPools != nil { - objectMap["inboundNatPools"] = lbpf.InboundNatPools - } - if lbpf.OutboundRules != nil { - objectMap["outboundRules"] = lbpf.OutboundRules - } - return json.Marshal(objectMap) -} - -// LoadBalancersCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type LoadBalancersCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LoadBalancersClient) (LoadBalancer, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LoadBalancersCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LoadBalancersCreateOrUpdateFuture.Result. -func (future *LoadBalancersCreateOrUpdateFuture) result(client LoadBalancersClient) (lb LoadBalancer, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - lb.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LoadBalancersCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if lb.Response.Response, err = future.GetResult(sender); err == nil && lb.Response.Response.StatusCode != http.StatusNoContent { - lb, err = client.CreateOrUpdateResponder(lb.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersCreateOrUpdateFuture", "Result", lb.Response.Response, "Failure responding to request") - } - } - return -} - -// LoadBalancersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type LoadBalancersDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LoadBalancersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LoadBalancersDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LoadBalancersDeleteFuture.Result. -func (future *LoadBalancersDeleteFuture) result(client LoadBalancersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LoadBalancersDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// LoadBalancerSku SKU of a load balancer. -type LoadBalancerSku struct { - // Name - Name of a load balancer SKU. Possible values include: 'LoadBalancerSkuNameBasic', 'LoadBalancerSkuNameStandard', 'LoadBalancerSkuNameGateway' - Name LoadBalancerSkuName `json:"name,omitempty"` - // Tier - Tier of a load balancer SKU. Possible values include: 'Regional', 'Global' - Tier LoadBalancerSkuTier `json:"tier,omitempty"` -} - -// LoadBalancersListInboundNatRulePortMappingsFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type LoadBalancersListInboundNatRulePortMappingsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LoadBalancersClient) (BackendAddressInboundNatRulePortMappings, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LoadBalancersListInboundNatRulePortMappingsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LoadBalancersListInboundNatRulePortMappingsFuture.Result. -func (future *LoadBalancersListInboundNatRulePortMappingsFuture) result(client LoadBalancersClient) (bainrpm BackendAddressInboundNatRulePortMappings, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersListInboundNatRulePortMappingsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - bainrpm.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LoadBalancersListInboundNatRulePortMappingsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if bainrpm.Response.Response, err = future.GetResult(sender); err == nil && bainrpm.Response.Response.StatusCode != http.StatusNoContent { - bainrpm, err = client.ListInboundNatRulePortMappingsResponder(bainrpm.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersListInboundNatRulePortMappingsFuture", "Result", bainrpm.Response.Response, "Failure responding to request") - } - } - return -} - -// LoadBalancersSwapPublicIPAddressesFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type LoadBalancersSwapPublicIPAddressesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LoadBalancersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LoadBalancersSwapPublicIPAddressesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LoadBalancersSwapPublicIPAddressesFuture.Result. -func (future *LoadBalancersSwapPublicIPAddressesFuture) result(client LoadBalancersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersSwapPublicIPAddressesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LoadBalancersSwapPublicIPAddressesFuture") - return - } - ar.Response = future.Response() - return -} - -// LoadBalancerVipSwapRequest the request for a VIP swap. -type LoadBalancerVipSwapRequest struct { - // FrontendIPConfigurations - A list of frontend IP configuration resources that should swap VIPs. - FrontendIPConfigurations *[]LoadBalancerVipSwapRequestFrontendIPConfiguration `json:"frontendIPConfigurations,omitempty"` -} - -// LoadBalancerVipSwapRequestFrontendIPConfiguration VIP swap request's frontend IP configuration object. -type LoadBalancerVipSwapRequestFrontendIPConfiguration struct { - // ID - The ID of frontend IP configuration resource. - ID *string `json:"id,omitempty"` - // LoadBalancerVipSwapRequestFrontendIPConfigurationProperties - The properties of VIP swap request's frontend IP configuration object. - *LoadBalancerVipSwapRequestFrontendIPConfigurationProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancerVipSwapRequestFrontendIPConfiguration. -func (lbvsrfic LoadBalancerVipSwapRequestFrontendIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lbvsrfic.ID != nil { - objectMap["id"] = lbvsrfic.ID - } - if lbvsrfic.LoadBalancerVipSwapRequestFrontendIPConfigurationProperties != nil { - objectMap["properties"] = lbvsrfic.LoadBalancerVipSwapRequestFrontendIPConfigurationProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for LoadBalancerVipSwapRequestFrontendIPConfiguration struct. -func (lbvsrfic *LoadBalancerVipSwapRequestFrontendIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - lbvsrfic.ID = &ID - } - case "properties": - if v != nil { - var loadBalancerVipSwapRequestFrontendIPConfigurationProperties LoadBalancerVipSwapRequestFrontendIPConfigurationProperties - err = json.Unmarshal(*v, &loadBalancerVipSwapRequestFrontendIPConfigurationProperties) - if err != nil { - return err - } - lbvsrfic.LoadBalancerVipSwapRequestFrontendIPConfigurationProperties = &loadBalancerVipSwapRequestFrontendIPConfigurationProperties - } - } - } - - return nil -} - -// LoadBalancerVipSwapRequestFrontendIPConfigurationProperties the properties of VIP swap request's -// frontend IP configuration object. -type LoadBalancerVipSwapRequestFrontendIPConfigurationProperties struct { - // PublicIPAddress - A reference to public IP address resource. - PublicIPAddress *SubResource `json:"publicIPAddress,omitempty"` -} - -// LoadBalancingRule a load balancing rule for a load balancer. -type LoadBalancingRule struct { - autorest.Response `json:"-"` - // LoadBalancingRulePropertiesFormat - Properties of load balancer load balancing rule. - *LoadBalancingRulePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within the set of load balancing rules used by the load balancer. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancingRule. -func (lbr LoadBalancingRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lbr.LoadBalancingRulePropertiesFormat != nil { - objectMap["properties"] = lbr.LoadBalancingRulePropertiesFormat - } - if lbr.Name != nil { - objectMap["name"] = lbr.Name - } - if lbr.ID != nil { - objectMap["id"] = lbr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for LoadBalancingRule struct. -func (lbr *LoadBalancingRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var loadBalancingRulePropertiesFormat LoadBalancingRulePropertiesFormat - err = json.Unmarshal(*v, &loadBalancingRulePropertiesFormat) - if err != nil { - return err - } - lbr.LoadBalancingRulePropertiesFormat = &loadBalancingRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - lbr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - lbr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - lbr.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - lbr.ID = &ID - } - } - } - - return nil -} - -// LoadBalancingRulePropertiesFormat properties of the load balancer. -type LoadBalancingRulePropertiesFormat struct { - // FrontendIPConfiguration - A reference to frontend IP addresses. - FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` - // BackendAddressPool - A reference to a pool of DIPs. Inbound traffic is randomly load balanced across IPs in the backend IPs. - BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` - // BackendAddressPools - An array of references to pool of DIPs. - BackendAddressPools *[]SubResource `json:"backendAddressPools,omitempty"` - // Probe - The reference to the load balancer probe used by the load balancing rule. - Probe *SubResource `json:"probe,omitempty"` - // Protocol - The reference to the transport protocol used by the load balancing rule. Possible values include: 'TransportProtocolUDP', 'TransportProtocolTCP', 'TransportProtocolAll' - Protocol TransportProtocol `json:"protocol,omitempty"` - // LoadDistribution - The load distribution policy for this rule. Possible values include: 'LoadDistributionDefault', 'LoadDistributionSourceIP', 'LoadDistributionSourceIPProtocol' - LoadDistribution LoadDistribution `json:"loadDistribution,omitempty"` - // FrontendPort - The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables "Any Port". - FrontendPort *int32 `json:"frontendPort,omitempty"` - // BackendPort - The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables "Any Port". - BackendPort *int32 `json:"backendPort,omitempty"` - // IdleTimeoutInMinutes - The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` - // EnableFloatingIP - Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - EnableFloatingIP *bool `json:"enableFloatingIP,omitempty"` - // EnableTCPReset - Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP. - EnableTCPReset *bool `json:"enableTcpReset,omitempty"` - // DisableOutboundSnat - Configures SNAT for the VMs in the backend pool to use the publicIP address specified in the frontend of the load balancing rule. - DisableOutboundSnat *bool `json:"disableOutboundSnat,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the load balancing rule resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for LoadBalancingRulePropertiesFormat. -func (lbrpf LoadBalancingRulePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lbrpf.FrontendIPConfiguration != nil { - objectMap["frontendIPConfiguration"] = lbrpf.FrontendIPConfiguration - } - if lbrpf.BackendAddressPool != nil { - objectMap["backendAddressPool"] = lbrpf.BackendAddressPool - } - if lbrpf.BackendAddressPools != nil { - objectMap["backendAddressPools"] = lbrpf.BackendAddressPools - } - if lbrpf.Probe != nil { - objectMap["probe"] = lbrpf.Probe - } - if lbrpf.Protocol != "" { - objectMap["protocol"] = lbrpf.Protocol - } - if lbrpf.LoadDistribution != "" { - objectMap["loadDistribution"] = lbrpf.LoadDistribution - } - if lbrpf.FrontendPort != nil { - objectMap["frontendPort"] = lbrpf.FrontendPort - } - if lbrpf.BackendPort != nil { - objectMap["backendPort"] = lbrpf.BackendPort - } - if lbrpf.IdleTimeoutInMinutes != nil { - objectMap["idleTimeoutInMinutes"] = lbrpf.IdleTimeoutInMinutes - } - if lbrpf.EnableFloatingIP != nil { - objectMap["enableFloatingIP"] = lbrpf.EnableFloatingIP - } - if lbrpf.EnableTCPReset != nil { - objectMap["enableTcpReset"] = lbrpf.EnableTCPReset - } - if lbrpf.DisableOutboundSnat != nil { - objectMap["disableOutboundSnat"] = lbrpf.DisableOutboundSnat - } - return json.Marshal(objectMap) -} - -// LocalNetworkGateway a common class for general resource information. -type LocalNetworkGateway struct { - autorest.Response `json:"-"` - // LocalNetworkGatewayPropertiesFormat - Properties of the local network gateway. - *LocalNetworkGatewayPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for LocalNetworkGateway. -func (lng LocalNetworkGateway) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lng.LocalNetworkGatewayPropertiesFormat != nil { - objectMap["properties"] = lng.LocalNetworkGatewayPropertiesFormat - } - if lng.ID != nil { - objectMap["id"] = lng.ID - } - if lng.Location != nil { - objectMap["location"] = lng.Location - } - if lng.Tags != nil { - objectMap["tags"] = lng.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for LocalNetworkGateway struct. -func (lng *LocalNetworkGateway) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var localNetworkGatewayPropertiesFormat LocalNetworkGatewayPropertiesFormat - err = json.Unmarshal(*v, &localNetworkGatewayPropertiesFormat) - if err != nil { - return err - } - lng.LocalNetworkGatewayPropertiesFormat = &localNetworkGatewayPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - lng.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - lng.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - lng.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - lng.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - lng.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - lng.Tags = tags - } - } - } - - return nil -} - -// LocalNetworkGatewayListResult response for ListLocalNetworkGateways API service call. -type LocalNetworkGatewayListResult struct { - autorest.Response `json:"-"` - // Value - A list of local network gateways that exists in a resource group. - Value *[]LocalNetworkGateway `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for LocalNetworkGatewayListResult. -func (lnglr LocalNetworkGatewayListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lnglr.Value != nil { - objectMap["value"] = lnglr.Value - } - return json.Marshal(objectMap) -} - -// LocalNetworkGatewayListResultIterator provides access to a complete listing of LocalNetworkGateway -// values. -type LocalNetworkGatewayListResultIterator struct { - i int - page LocalNetworkGatewayListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *LocalNetworkGatewayListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewayListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *LocalNetworkGatewayListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter LocalNetworkGatewayListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter LocalNetworkGatewayListResultIterator) Response() LocalNetworkGatewayListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter LocalNetworkGatewayListResultIterator) Value() LocalNetworkGateway { - if !iter.page.NotDone() { - return LocalNetworkGateway{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the LocalNetworkGatewayListResultIterator type. -func NewLocalNetworkGatewayListResultIterator(page LocalNetworkGatewayListResultPage) LocalNetworkGatewayListResultIterator { - return LocalNetworkGatewayListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (lnglr LocalNetworkGatewayListResult) IsEmpty() bool { - return lnglr.Value == nil || len(*lnglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (lnglr LocalNetworkGatewayListResult) hasNextLink() bool { - return lnglr.NextLink != nil && len(*lnglr.NextLink) != 0 -} - -// localNetworkGatewayListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (lnglr LocalNetworkGatewayListResult) localNetworkGatewayListResultPreparer(ctx context.Context) (*http.Request, error) { - if !lnglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(lnglr.NextLink))) -} - -// LocalNetworkGatewayListResultPage contains a page of LocalNetworkGateway values. -type LocalNetworkGatewayListResultPage struct { - fn func(context.Context, LocalNetworkGatewayListResult) (LocalNetworkGatewayListResult, error) - lnglr LocalNetworkGatewayListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *LocalNetworkGatewayListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/LocalNetworkGatewayListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.lnglr) - if err != nil { - return err - } - page.lnglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *LocalNetworkGatewayListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page LocalNetworkGatewayListResultPage) NotDone() bool { - return !page.lnglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page LocalNetworkGatewayListResultPage) Response() LocalNetworkGatewayListResult { - return page.lnglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page LocalNetworkGatewayListResultPage) Values() []LocalNetworkGateway { - if page.lnglr.IsEmpty() { - return nil - } - return *page.lnglr.Value -} - -// Creates a new instance of the LocalNetworkGatewayListResultPage type. -func NewLocalNetworkGatewayListResultPage(cur LocalNetworkGatewayListResult, getNextPage func(context.Context, LocalNetworkGatewayListResult) (LocalNetworkGatewayListResult, error)) LocalNetworkGatewayListResultPage { - return LocalNetworkGatewayListResultPage{ - fn: getNextPage, - lnglr: cur, - } -} - -// LocalNetworkGatewayPropertiesFormat localNetworkGateway properties. -type LocalNetworkGatewayPropertiesFormat struct { - // LocalNetworkAddressSpace - Local network site address space. - LocalNetworkAddressSpace *AddressSpace `json:"localNetworkAddressSpace,omitempty"` - // GatewayIPAddress - IP address of local network gateway. - GatewayIPAddress *string `json:"gatewayIpAddress,omitempty"` - // Fqdn - FQDN of local network gateway. - Fqdn *string `json:"fqdn,omitempty"` - // BgpSettings - Local network gateway's BGP speaker settings. - BgpSettings *BgpSettings `json:"bgpSettings,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the local network gateway resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the local network gateway resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for LocalNetworkGatewayPropertiesFormat. -func (lngpf LocalNetworkGatewayPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if lngpf.LocalNetworkAddressSpace != nil { - objectMap["localNetworkAddressSpace"] = lngpf.LocalNetworkAddressSpace - } - if lngpf.GatewayIPAddress != nil { - objectMap["gatewayIpAddress"] = lngpf.GatewayIPAddress - } - if lngpf.Fqdn != nil { - objectMap["fqdn"] = lngpf.Fqdn - } - if lngpf.BgpSettings != nil { - objectMap["bgpSettings"] = lngpf.BgpSettings - } - return json.Marshal(objectMap) -} - -// LocalNetworkGatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type LocalNetworkGatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LocalNetworkGatewaysClient) (LocalNetworkGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LocalNetworkGatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LocalNetworkGatewaysCreateOrUpdateFuture.Result. -func (future *LocalNetworkGatewaysCreateOrUpdateFuture) result(client LocalNetworkGatewaysClient) (lng LocalNetworkGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - lng.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LocalNetworkGatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if lng.Response.Response, err = future.GetResult(sender); err == nil && lng.Response.Response.StatusCode != http.StatusNoContent { - lng, err = client.CreateOrUpdateResponder(lng.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysCreateOrUpdateFuture", "Result", lng.Response.Response, "Failure responding to request") - } - } - return -} - -// LocalNetworkGatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type LocalNetworkGatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(LocalNetworkGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *LocalNetworkGatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for LocalNetworkGatewaysDeleteFuture.Result. -func (future *LocalNetworkGatewaysDeleteFuture) result(client LocalNetworkGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.LocalNetworkGatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// LogSpecification description of logging specification. -type LogSpecification struct { - // Name - The name of the specification. - Name *string `json:"name,omitempty"` - // DisplayName - The display name of the specification. - DisplayName *string `json:"displayName,omitempty"` - // BlobDuration - Duration of the blob. - BlobDuration *string `json:"blobDuration,omitempty"` -} - -// ManagedRuleGroupOverride defines a managed rule group override setting. -type ManagedRuleGroupOverride struct { - // RuleGroupName - The managed rule group to override. - RuleGroupName *string `json:"ruleGroupName,omitempty"` - // Rules - List of rules that will be disabled. If none specified, all rules in the group will be disabled. - Rules *[]ManagedRuleOverride `json:"rules,omitempty"` -} - -// ManagedRuleOverride defines a managed rule group override setting. -type ManagedRuleOverride struct { - // RuleID - Identifier for the managed rule. - RuleID *string `json:"ruleId,omitempty"` - // State - The state of the managed rule. Defaults to Disabled if not specified. Possible values include: 'ManagedRuleEnabledStateDisabled', 'ManagedRuleEnabledStateEnabled' - State ManagedRuleEnabledState `json:"state,omitempty"` - // Action - Describes the override action to be applied when rule matches. Possible values include: 'ActionTypeAnomalyScoring', 'ActionTypeAllow', 'ActionTypeBlock', 'ActionTypeLog' - Action ActionType `json:"action,omitempty"` -} - -// ManagedRulesDefinition allow to exclude some variable satisfy the condition for the WAF check. -type ManagedRulesDefinition struct { - // Exclusions - The Exclusions that are applied on the policy. - Exclusions *[]OwaspCrsExclusionEntry `json:"exclusions,omitempty"` - // ManagedRuleSets - The managed rule sets that are associated with the policy. - ManagedRuleSets *[]ManagedRuleSet `json:"managedRuleSets,omitempty"` -} - -// ManagedRuleSet defines a managed rule set. -type ManagedRuleSet struct { - // RuleSetType - Defines the rule set type to use. - RuleSetType *string `json:"ruleSetType,omitempty"` - // RuleSetVersion - Defines the version of the rule set to use. - RuleSetVersion *string `json:"ruleSetVersion,omitempty"` - // RuleGroupOverrides - Defines the rule group overrides to apply to the rule set. - RuleGroupOverrides *[]ManagedRuleGroupOverride `json:"ruleGroupOverrides,omitempty"` -} - -// ManagedServiceIdentity identity for the resource. -type ManagedServiceIdentity struct { - // PrincipalID - READ-ONLY; The principal id of the system assigned identity. This property will only be provided for a system assigned identity. - PrincipalID *string `json:"principalId,omitempty"` - // TenantID - READ-ONLY; The tenant id of the system assigned identity. This property will only be provided for a system assigned identity. - TenantID *string `json:"tenantId,omitempty"` - // Type - The type of identity used for the resource. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine. Possible values include: 'ResourceIdentityTypeSystemAssigned', 'ResourceIdentityTypeUserAssigned', 'ResourceIdentityTypeSystemAssignedUserAssigned', 'ResourceIdentityTypeNone' - Type ResourceIdentityType `json:"type,omitempty"` - // UserAssignedIdentities - The list of user identities associated with resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. - UserAssignedIdentities map[string]*ManagedServiceIdentityUserAssignedIdentitiesValue `json:"userAssignedIdentities"` -} - -// MarshalJSON is the custom marshaler for ManagedServiceIdentity. -func (msi ManagedServiceIdentity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if msi.Type != "" { - objectMap["type"] = msi.Type - } - if msi.UserAssignedIdentities != nil { - objectMap["userAssignedIdentities"] = msi.UserAssignedIdentities - } - return json.Marshal(objectMap) -} - -// ManagedServiceIdentityUserAssignedIdentitiesValue ... -type ManagedServiceIdentityUserAssignedIdentitiesValue struct { - // PrincipalID - READ-ONLY; The principal id of user assigned identity. - PrincipalID *string `json:"principalId,omitempty"` - // ClientID - READ-ONLY; The client id of user assigned identity. - ClientID *string `json:"clientId,omitempty"` -} - -// MarshalJSON is the custom marshaler for ManagedServiceIdentityUserAssignedIdentitiesValue. -func (msiAiv ManagedServiceIdentityUserAssignedIdentitiesValue) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// Manager the Managed Network resource -type Manager struct { - autorest.Response `json:"-"` - // ManagerProperties - The network manager properties - *ManagerProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // SystemData - READ-ONLY; The system metadata related to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Manager. -func (mVar Manager) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if mVar.ManagerProperties != nil { - objectMap["properties"] = mVar.ManagerProperties - } - if mVar.ID != nil { - objectMap["id"] = mVar.ID - } - if mVar.Location != nil { - objectMap["location"] = mVar.Location - } - if mVar.Tags != nil { - objectMap["tags"] = mVar.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Manager struct. -func (mVar *Manager) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var managerProperties ManagerProperties - err = json.Unmarshal(*v, &managerProperties) - if err != nil { - return err - } - mVar.ManagerProperties = &managerProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - mVar.Etag = &etag - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - mVar.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - mVar.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - mVar.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - mVar.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - mVar.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - mVar.Tags = tags - } - } - } - - return nil -} - -// ManagerCommit network Manager Commit. -type ManagerCommit struct { - autorest.Response `json:"-"` - // CommitID - READ-ONLY; Commit Id. - CommitID *string `json:"commitId,omitempty"` - // TargetLocations - List of target locations. - TargetLocations *[]string `json:"targetLocations,omitempty"` - // ConfigurationIds - List of configuration ids. - ConfigurationIds *[]string `json:"configurationIds,omitempty"` - // CommitType - Commit Type. Possible values include: 'SecurityAdmin', 'Connectivity' - CommitType ConfigurationType `json:"commitType,omitempty"` -} - -// MarshalJSON is the custom marshaler for ManagerCommit. -func (mc ManagerCommit) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if mc.TargetLocations != nil { - objectMap["targetLocations"] = mc.TargetLocations - } - if mc.ConfigurationIds != nil { - objectMap["configurationIds"] = mc.ConfigurationIds - } - if mc.CommitType != "" { - objectMap["commitType"] = mc.CommitType - } - return json.Marshal(objectMap) -} - -// ManagerCommitsPostFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ManagerCommitsPostFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ManagerCommitsClient) (ManagerCommit, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ManagerCommitsPostFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ManagerCommitsPostFuture.Result. -func (future *ManagerCommitsPostFuture) result(client ManagerCommitsClient) (mc ManagerCommit, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagerCommitsPostFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - mc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ManagerCommitsPostFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if mc.Response.Response, err = future.GetResult(sender); err == nil && mc.Response.Response.StatusCode != http.StatusNoContent { - mc, err = client.PostResponder(mc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagerCommitsPostFuture", "Result", mc.Response.Response, "Failure responding to request") - } - } - return -} - -// ManagerConnection the Network Manager Connection resource -type ManagerConnection struct { - autorest.Response `json:"-"` - // ManagerConnectionProperties - The scope connection properties - *ManagerConnectionProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system metadata related to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for ManagerConnection. -func (mc ManagerConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if mc.ManagerConnectionProperties != nil { - objectMap["properties"] = mc.ManagerConnectionProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ManagerConnection struct. -func (mc *ManagerConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var managerConnectionProperties ManagerConnectionProperties - err = json.Unmarshal(*v, &managerConnectionProperties) - if err != nil { - return err - } - mc.ManagerConnectionProperties = &managerConnectionProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - mc.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - mc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - mc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - mc.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - mc.Etag = &etag - } - } - } - - return nil -} - -// ManagerConnectionListResult list of network manager connections. -type ManagerConnectionListResult struct { - autorest.Response `json:"-"` - // Value - List of network manager connections. - Value *[]ManagerConnection `json:"value,omitempty"` - // NextLink - Gets the URL to get the next page of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ManagerConnectionListResultIterator provides access to a complete listing of ManagerConnection values. -type ManagerConnectionListResultIterator struct { - i int - page ManagerConnectionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ManagerConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagerConnectionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ManagerConnectionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ManagerConnectionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ManagerConnectionListResultIterator) Response() ManagerConnectionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ManagerConnectionListResultIterator) Value() ManagerConnection { - if !iter.page.NotDone() { - return ManagerConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ManagerConnectionListResultIterator type. -func NewManagerConnectionListResultIterator(page ManagerConnectionListResultPage) ManagerConnectionListResultIterator { - return ManagerConnectionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (mclr ManagerConnectionListResult) IsEmpty() bool { - return mclr.Value == nil || len(*mclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (mclr ManagerConnectionListResult) hasNextLink() bool { - return mclr.NextLink != nil && len(*mclr.NextLink) != 0 -} - -// managerConnectionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (mclr ManagerConnectionListResult) managerConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !mclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(mclr.NextLink))) -} - -// ManagerConnectionListResultPage contains a page of ManagerConnection values. -type ManagerConnectionListResultPage struct { - fn func(context.Context, ManagerConnectionListResult) (ManagerConnectionListResult, error) - mclr ManagerConnectionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ManagerConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagerConnectionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.mclr) - if err != nil { - return err - } - page.mclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ManagerConnectionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ManagerConnectionListResultPage) NotDone() bool { - return !page.mclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ManagerConnectionListResultPage) Response() ManagerConnectionListResult { - return page.mclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ManagerConnectionListResultPage) Values() []ManagerConnection { - if page.mclr.IsEmpty() { - return nil - } - return *page.mclr.Value -} - -// Creates a new instance of the ManagerConnectionListResultPage type. -func NewManagerConnectionListResultPage(cur ManagerConnectionListResult, getNextPage func(context.Context, ManagerConnectionListResult) (ManagerConnectionListResult, error)) ManagerConnectionListResultPage { - return ManagerConnectionListResultPage{ - fn: getNextPage, - mclr: cur, - } -} - -// ManagerConnectionProperties information about the network manager connection. -type ManagerConnectionProperties struct { - // NetworkManagerID - Network Manager Id. - NetworkManagerID *string `json:"networkManagerId,omitempty"` - // ConnectionState - Connection state. Possible values include: 'ScopeConnectionStateConnected', 'ScopeConnectionStatePending', 'ScopeConnectionStateConflict', 'ScopeConnectionStateRevoked', 'ScopeConnectionStateRejected' - ConnectionState ScopeConnectionState `json:"connectionState,omitempty"` - // Description - A description of the network manager connection. - Description *string `json:"description,omitempty"` -} - -// ManagerDeploymentStatus network Manager Deployment Status. -type ManagerDeploymentStatus struct { - // CommitTime - Commit Time. - CommitTime *date.Time `json:"commitTime,omitempty"` - // Region - Region Name. - Region *string `json:"region,omitempty"` - // DeploymentStatus - Deployment Status. Possible values include: 'NotStarted', 'Deploying', 'Deployed', 'Failed' - DeploymentStatus DeploymentStatus `json:"deploymentStatus,omitempty"` - // ConfigurationIds - List of configuration ids. - ConfigurationIds *[]string `json:"configurationIds,omitempty"` - // DeploymentType - Possible values include: 'SecurityAdmin', 'Connectivity' - DeploymentType ConfigurationType `json:"deploymentType,omitempty"` - // ErrorMessage - Error Message. - ErrorMessage *string `json:"errorMessage,omitempty"` -} - -// ManagerDeploymentStatusListResult a list of Network Manager Deployment Status -type ManagerDeploymentStatusListResult struct { - autorest.Response `json:"-"` - // Value - Gets a page of Network Manager Deployment Status - Value *[]ManagerDeploymentStatus `json:"value,omitempty"` - // SkipToken - When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current request) to retrieve the next page of data. - SkipToken *string `json:"skipToken,omitempty"` -} - -// ManagerDeploymentStatusParameter network Manager Deployment Status Parameter. -type ManagerDeploymentStatusParameter struct { - // Regions - List of locations. - Regions *[]string `json:"regions,omitempty"` - // DeploymentTypes - List of deployment types. - DeploymentTypes *[]ConfigurationType `json:"deploymentTypes,omitempty"` - // SkipToken - Continuation token for pagination, capturing the next page size and offset, as well as the context of the query. - SkipToken *string `json:"skipToken,omitempty"` -} - -// ManagerEffectiveConnectivityConfigurationListResult result of the request to list -// networkManagerEffectiveConnectivityConfiguration. It contains a list of groups and a skiptoken to get -// the next set of results. -type ManagerEffectiveConnectivityConfigurationListResult struct { - autorest.Response `json:"-"` - // Value - Gets a page of NetworkManagerEffectiveConnectivityConfiguration - Value *[]EffectiveConnectivityConfiguration `json:"value,omitempty"` - // SkipToken - When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current request) to retrieve the next page of data. - SkipToken *string `json:"skipToken,omitempty"` -} - -// ManagerEffectiveSecurityAdminRulesListResult result of the request to list -// networkManagerEffectiveSecurityAdminRules. It contains a list of groups and a skiptoken to get the next -// set of results. -type ManagerEffectiveSecurityAdminRulesListResult struct { - autorest.Response `json:"-"` - // Value - Gets a page of NetworkManagerEffectiveSecurityAdminRules - Value *[]BasicEffectiveBaseSecurityAdminRule `json:"value,omitempty"` - // SkipToken - When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current request) to retrieve the next page of data. - SkipToken *string `json:"skipToken,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for ManagerEffectiveSecurityAdminRulesListResult struct. -func (mesarlr *ManagerEffectiveSecurityAdminRulesListResult) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "value": - if v != nil { - value, err := unmarshalBasicEffectiveBaseSecurityAdminRuleArray(*v) - if err != nil { - return err - } - mesarlr.Value = &value - } - case "skipToken": - if v != nil { - var skipToken string - err = json.Unmarshal(*v, &skipToken) - if err != nil { - return err - } - mesarlr.SkipToken = &skipToken - } - } - } - - return nil -} - -// ManagerListResult result of the request to list NetworkManager. It contains a list of network managers -// and a URL link to get the next set of results. -type ManagerListResult struct { - autorest.Response `json:"-"` - // Value - Gets a page of NetworkManager - Value *[]Manager `json:"value,omitempty"` - // NextLink - Gets the URL to get the next page of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ManagerListResultIterator provides access to a complete listing of Manager values. -type ManagerListResultIterator struct { - i int - page ManagerListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ManagerListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagerListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ManagerListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ManagerListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ManagerListResultIterator) Response() ManagerListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ManagerListResultIterator) Value() Manager { - if !iter.page.NotDone() { - return Manager{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ManagerListResultIterator type. -func NewManagerListResultIterator(page ManagerListResultPage) ManagerListResultIterator { - return ManagerListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (mlr ManagerListResult) IsEmpty() bool { - return mlr.Value == nil || len(*mlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (mlr ManagerListResult) hasNextLink() bool { - return mlr.NextLink != nil && len(*mlr.NextLink) != 0 -} - -// managerListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (mlr ManagerListResult) managerListResultPreparer(ctx context.Context) (*http.Request, error) { - if !mlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(mlr.NextLink))) -} - -// ManagerListResultPage contains a page of Manager values. -type ManagerListResultPage struct { - fn func(context.Context, ManagerListResult) (ManagerListResult, error) - mlr ManagerListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ManagerListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ManagerListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.mlr) - if err != nil { - return err - } - page.mlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ManagerListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ManagerListResultPage) NotDone() bool { - return !page.mlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ManagerListResultPage) Response() ManagerListResult { - return page.mlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ManagerListResultPage) Values() []Manager { - if page.mlr.IsEmpty() { - return nil - } - return *page.mlr.Value -} - -// Creates a new instance of the ManagerListResultPage type. -func NewManagerListResultPage(cur ManagerListResult, getNextPage func(context.Context, ManagerListResult) (ManagerListResult, error)) ManagerListResultPage { - return ManagerListResultPage{ - fn: getNextPage, - mlr: cur, - } -} - -// ManagerProperties properties of Managed Network -type ManagerProperties struct { - // Description - A description of the network manager. - Description *string `json:"description,omitempty"` - // NetworkManagerScopes - Scope of Network Manager. - NetworkManagerScopes *ManagerPropertiesNetworkManagerScopes `json:"networkManagerScopes,omitempty"` - // NetworkManagerScopeAccesses - Scope Access. - NetworkManagerScopeAccesses *[]ConfigurationType `json:"networkManagerScopeAccesses,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the network manager resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ManagerProperties. -func (mp ManagerProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if mp.Description != nil { - objectMap["description"] = mp.Description - } - if mp.NetworkManagerScopes != nil { - objectMap["networkManagerScopes"] = mp.NetworkManagerScopes - } - if mp.NetworkManagerScopeAccesses != nil { - objectMap["networkManagerScopeAccesses"] = mp.NetworkManagerScopeAccesses - } - return json.Marshal(objectMap) -} - -// ManagerPropertiesNetworkManagerScopes scope of Network Manager. -type ManagerPropertiesNetworkManagerScopes struct { - // ManagementGroups - List of management groups. - ManagementGroups *[]string `json:"managementGroups,omitempty"` - // Subscriptions - List of subscriptions. - Subscriptions *[]string `json:"subscriptions,omitempty"` - // CrossTenantScopes - READ-ONLY; List of cross tenant scopes. - CrossTenantScopes *[]CrossTenantScopes `json:"crossTenantScopes,omitempty"` -} - -// MarshalJSON is the custom marshaler for ManagerPropertiesNetworkManagerScopes. -func (mpMs ManagerPropertiesNetworkManagerScopes) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if mpMs.ManagementGroups != nil { - objectMap["managementGroups"] = mpMs.ManagementGroups - } - if mpMs.Subscriptions != nil { - objectMap["subscriptions"] = mpMs.Subscriptions - } - return json.Marshal(objectMap) -} - -// ManagersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ManagersDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ManagersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ManagersDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ManagersDeleteFuture.Result. -func (future *ManagersDeleteFuture) result(client ManagersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ManagersDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ManagersDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ManagerSecurityGroupItem network manager security group item. -type ManagerSecurityGroupItem struct { - // NetworkGroupID - Network manager group Id. - NetworkGroupID *string `json:"networkGroupId,omitempty"` -} - -// MatchCondition define match conditions. -type MatchCondition struct { - // MatchVariables - List of match variables. - MatchVariables *[]MatchVariable `json:"matchVariables,omitempty"` - // Operator - The operator to be matched. Possible values include: 'WebApplicationFirewallOperatorIPMatch', 'WebApplicationFirewallOperatorEqual', 'WebApplicationFirewallOperatorContains', 'WebApplicationFirewallOperatorLessThan', 'WebApplicationFirewallOperatorGreaterThan', 'WebApplicationFirewallOperatorLessThanOrEqual', 'WebApplicationFirewallOperatorGreaterThanOrEqual', 'WebApplicationFirewallOperatorBeginsWith', 'WebApplicationFirewallOperatorEndsWith', 'WebApplicationFirewallOperatorRegex', 'WebApplicationFirewallOperatorGeoMatch', 'WebApplicationFirewallOperatorAny' - Operator WebApplicationFirewallOperator `json:"operator,omitempty"` - // NegationConditon - Whether this is negate condition or not. - NegationConditon *bool `json:"negationConditon,omitempty"` - // MatchValues - Match value. - MatchValues *[]string `json:"matchValues,omitempty"` - // Transforms - List of transforms. - Transforms *[]WebApplicationFirewallTransform `json:"transforms,omitempty"` -} - -// MatchedRule matched rule. -type MatchedRule struct { - // RuleName - Name of the matched network security rule. - RuleName *string `json:"ruleName,omitempty"` - // Action - The network traffic is allowed or denied. Possible values are 'Allow' and 'Deny'. - Action *string `json:"action,omitempty"` -} - -// MatchVariable define match variables. -type MatchVariable struct { - // VariableName - Match Variable. Possible values include: 'RemoteAddr', 'RequestMethod', 'QueryString', 'PostArgs', 'RequestURI', 'RequestHeaders', 'RequestBody', 'RequestCookies' - VariableName WebApplicationFirewallMatchVariable `json:"variableName,omitempty"` - // Selector - The selector of match variable. - Selector *string `json:"selector,omitempty"` -} - -// MetricSpecification description of metrics specification. -type MetricSpecification struct { - // Name - The name of the metric. - Name *string `json:"name,omitempty"` - // DisplayName - The display name of the metric. - DisplayName *string `json:"displayName,omitempty"` - // DisplayDescription - The description of the metric. - DisplayDescription *string `json:"displayDescription,omitempty"` - // Unit - Units the metric to be displayed in. - Unit *string `json:"unit,omitempty"` - // AggregationType - The aggregation type. - AggregationType *string `json:"aggregationType,omitempty"` - // Availabilities - List of availability. - Availabilities *[]Availability `json:"availabilities,omitempty"` - // EnableRegionalMdmAccount - Whether regional MDM account enabled. - EnableRegionalMdmAccount *bool `json:"enableRegionalMdmAccount,omitempty"` - // FillGapWithZero - Whether gaps would be filled with zeros. - FillGapWithZero *bool `json:"fillGapWithZero,omitempty"` - // MetricFilterPattern - Pattern for the filter of the metric. - MetricFilterPattern *string `json:"metricFilterPattern,omitempty"` - // Dimensions - List of dimensions. - Dimensions *[]Dimension `json:"dimensions,omitempty"` - // IsInternal - Whether the metric is internal. - IsInternal *bool `json:"isInternal,omitempty"` - // SourceMdmAccount - The source MDM account. - SourceMdmAccount *string `json:"sourceMdmAccount,omitempty"` - // SourceMdmNamespace - The source MDM namespace. - SourceMdmNamespace *string `json:"sourceMdmNamespace,omitempty"` - // ResourceIDDimensionNameOverride - The resource Id dimension name override. - ResourceIDDimensionNameOverride *string `json:"resourceIdDimensionNameOverride,omitempty"` -} - -// NatGateway nat Gateway resource. -type NatGateway struct { - autorest.Response `json:"-"` - // Sku - The nat gateway SKU. - Sku *NatGatewaySku `json:"sku,omitempty"` - // NatGatewayPropertiesFormat - Nat Gateway properties. - *NatGatewayPropertiesFormat `json:"properties,omitempty"` - // Zones - A list of availability zones denoting the zone in which Nat Gateway should be deployed. - Zones *[]string `json:"zones,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for NatGateway. -func (ng NatGateway) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ng.Sku != nil { - objectMap["sku"] = ng.Sku - } - if ng.NatGatewayPropertiesFormat != nil { - objectMap["properties"] = ng.NatGatewayPropertiesFormat - } - if ng.Zones != nil { - objectMap["zones"] = ng.Zones - } - if ng.ID != nil { - objectMap["id"] = ng.ID - } - if ng.Location != nil { - objectMap["location"] = ng.Location - } - if ng.Tags != nil { - objectMap["tags"] = ng.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for NatGateway struct. -func (ng *NatGateway) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "sku": - if v != nil { - var sku NatGatewaySku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - ng.Sku = &sku - } - case "properties": - if v != nil { - var natGatewayPropertiesFormat NatGatewayPropertiesFormat - err = json.Unmarshal(*v, &natGatewayPropertiesFormat) - if err != nil { - return err - } - ng.NatGatewayPropertiesFormat = &natGatewayPropertiesFormat - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - ng.Zones = &zones - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ng.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ng.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ng.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ng.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - ng.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - ng.Tags = tags - } - } - } - - return nil -} - -// NatGatewayListResult response for ListNatGateways API service call. -type NatGatewayListResult struct { - autorest.Response `json:"-"` - // Value - A list of Nat Gateways that exists in a resource group. - Value *[]NatGateway `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// NatGatewayListResultIterator provides access to a complete listing of NatGateway values. -type NatGatewayListResultIterator struct { - i int - page NatGatewayListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *NatGatewayListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatGatewayListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *NatGatewayListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter NatGatewayListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter NatGatewayListResultIterator) Response() NatGatewayListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter NatGatewayListResultIterator) Value() NatGateway { - if !iter.page.NotDone() { - return NatGateway{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the NatGatewayListResultIterator type. -func NewNatGatewayListResultIterator(page NatGatewayListResultPage) NatGatewayListResultIterator { - return NatGatewayListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (nglr NatGatewayListResult) IsEmpty() bool { - return nglr.Value == nil || len(*nglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (nglr NatGatewayListResult) hasNextLink() bool { - return nglr.NextLink != nil && len(*nglr.NextLink) != 0 -} - -// natGatewayListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (nglr NatGatewayListResult) natGatewayListResultPreparer(ctx context.Context) (*http.Request, error) { - if !nglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(nglr.NextLink))) -} - -// NatGatewayListResultPage contains a page of NatGateway values. -type NatGatewayListResultPage struct { - fn func(context.Context, NatGatewayListResult) (NatGatewayListResult, error) - nglr NatGatewayListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *NatGatewayListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatGatewayListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.nglr) - if err != nil { - return err - } - page.nglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *NatGatewayListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page NatGatewayListResultPage) NotDone() bool { - return !page.nglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page NatGatewayListResultPage) Response() NatGatewayListResult { - return page.nglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page NatGatewayListResultPage) Values() []NatGateway { - if page.nglr.IsEmpty() { - return nil - } - return *page.nglr.Value -} - -// Creates a new instance of the NatGatewayListResultPage type. -func NewNatGatewayListResultPage(cur NatGatewayListResult, getNextPage func(context.Context, NatGatewayListResult) (NatGatewayListResult, error)) NatGatewayListResultPage { - return NatGatewayListResultPage{ - fn: getNextPage, - nglr: cur, - } -} - -// NatGatewayPropertiesFormat nat Gateway properties. -type NatGatewayPropertiesFormat struct { - // IdleTimeoutInMinutes - The idle timeout of the nat gateway. - IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` - // PublicIPAddresses - An array of public ip addresses associated with the nat gateway resource. - PublicIPAddresses *[]SubResource `json:"publicIpAddresses,omitempty"` - // PublicIPPrefixes - An array of public ip prefixes associated with the nat gateway resource. - PublicIPPrefixes *[]SubResource `json:"publicIpPrefixes,omitempty"` - // Subnets - READ-ONLY; An array of references to the subnets using this nat gateway resource. - Subnets *[]SubResource `json:"subnets,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the NAT gateway resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the NAT gateway resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for NatGatewayPropertiesFormat. -func (ngpf NatGatewayPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ngpf.IdleTimeoutInMinutes != nil { - objectMap["idleTimeoutInMinutes"] = ngpf.IdleTimeoutInMinutes - } - if ngpf.PublicIPAddresses != nil { - objectMap["publicIpAddresses"] = ngpf.PublicIPAddresses - } - if ngpf.PublicIPPrefixes != nil { - objectMap["publicIpPrefixes"] = ngpf.PublicIPPrefixes - } - return json.Marshal(objectMap) -} - -// NatGatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type NatGatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(NatGatewaysClient) (NatGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *NatGatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for NatGatewaysCreateOrUpdateFuture.Result. -func (future *NatGatewaysCreateOrUpdateFuture) result(client NatGatewaysClient) (ng NatGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ng.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.NatGatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ng.Response.Response, err = future.GetResult(sender); err == nil && ng.Response.Response.StatusCode != http.StatusNoContent { - ng, err = client.CreateOrUpdateResponder(ng.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysCreateOrUpdateFuture", "Result", ng.Response.Response, "Failure responding to request") - } - } - return -} - -// NatGatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type NatGatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(NatGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *NatGatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for NatGatewaysDeleteFuture.Result. -func (future *NatGatewaysDeleteFuture) result(client NatGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.NatGatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// NatGatewaySku SKU of nat gateway. -type NatGatewaySku struct { - // Name - Name of Nat Gateway SKU. Possible values include: 'NatGatewaySkuNameStandard' - Name NatGatewaySkuName `json:"name,omitempty"` -} - -// NatRule rule of type nat. -type NatRule struct { - // IPProtocols - Array of FirewallPolicyRuleNetworkProtocols. - IPProtocols *[]FirewallPolicyRuleNetworkProtocol `json:"ipProtocols,omitempty"` - // SourceAddresses - List of source IP addresses for this rule. - SourceAddresses *[]string `json:"sourceAddresses,omitempty"` - // DestinationAddresses - List of destination IP addresses or Service Tags. - DestinationAddresses *[]string `json:"destinationAddresses,omitempty"` - // DestinationPorts - List of destination ports. - DestinationPorts *[]string `json:"destinationPorts,omitempty"` - // TranslatedAddress - The translated address for this NAT rule. - TranslatedAddress *string `json:"translatedAddress,omitempty"` - // TranslatedPort - The translated port for this NAT rule. - TranslatedPort *string `json:"translatedPort,omitempty"` - // SourceIPGroups - List of source IpGroups for this rule. - SourceIPGroups *[]string `json:"sourceIpGroups,omitempty"` - // TranslatedFqdn - The translated FQDN for this NAT rule. - TranslatedFqdn *string `json:"translatedFqdn,omitempty"` - // Name - Name of the rule. - Name *string `json:"name,omitempty"` - // Description - Description of the rule. - Description *string `json:"description,omitempty"` - // RuleType - Possible values include: 'RuleTypeFirewallPolicyRule', 'RuleTypeApplicationRule', 'RuleTypeNatRule', 'RuleTypeNetworkRule' - RuleType RuleType `json:"ruleType,omitempty"` -} - -// MarshalJSON is the custom marshaler for NatRule. -func (nr NatRule) MarshalJSON() ([]byte, error) { - nr.RuleType = RuleTypeNatRule - objectMap := make(map[string]interface{}) - if nr.IPProtocols != nil { - objectMap["ipProtocols"] = nr.IPProtocols - } - if nr.SourceAddresses != nil { - objectMap["sourceAddresses"] = nr.SourceAddresses - } - if nr.DestinationAddresses != nil { - objectMap["destinationAddresses"] = nr.DestinationAddresses - } - if nr.DestinationPorts != nil { - objectMap["destinationPorts"] = nr.DestinationPorts - } - if nr.TranslatedAddress != nil { - objectMap["translatedAddress"] = nr.TranslatedAddress - } - if nr.TranslatedPort != nil { - objectMap["translatedPort"] = nr.TranslatedPort - } - if nr.SourceIPGroups != nil { - objectMap["sourceIpGroups"] = nr.SourceIPGroups - } - if nr.TranslatedFqdn != nil { - objectMap["translatedFqdn"] = nr.TranslatedFqdn - } - if nr.Name != nil { - objectMap["name"] = nr.Name - } - if nr.Description != nil { - objectMap["description"] = nr.Description - } - if nr.RuleType != "" { - objectMap["ruleType"] = nr.RuleType - } - return json.Marshal(objectMap) -} - -// AsApplicationRule is the BasicFirewallPolicyRule implementation for NatRule. -func (nr NatRule) AsApplicationRule() (*ApplicationRule, bool) { - return nil, false -} - -// AsNatRule is the BasicFirewallPolicyRule implementation for NatRule. -func (nr NatRule) AsNatRule() (*NatRule, bool) { - return &nr, true -} - -// AsRule is the BasicFirewallPolicyRule implementation for NatRule. -func (nr NatRule) AsRule() (*Rule, bool) { - return nil, false -} - -// AsFirewallPolicyRule is the BasicFirewallPolicyRule implementation for NatRule. -func (nr NatRule) AsFirewallPolicyRule() (*FirewallPolicyRule, bool) { - return nil, false -} - -// AsBasicFirewallPolicyRule is the BasicFirewallPolicyRule implementation for NatRule. -func (nr NatRule) AsBasicFirewallPolicyRule() (BasicFirewallPolicyRule, bool) { - return &nr, true -} - -// NatRulePortMapping individual port mappings for inbound NAT rule created for backend pool. -type NatRulePortMapping struct { - // InboundNatRuleName - Name of inbound NAT rule. - InboundNatRuleName *string `json:"inboundNatRuleName,omitempty"` - // FrontendPort - Frontend port. - FrontendPort *int32 `json:"frontendPort,omitempty"` - // BackendPort - Backend port. - BackendPort *int32 `json:"backendPort,omitempty"` -} - -// NatRulesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type NatRulesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(NatRulesClient) (VpnGatewayNatRule, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *NatRulesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for NatRulesCreateOrUpdateFuture.Result. -func (future *NatRulesCreateOrUpdateFuture) result(client NatRulesClient) (vgnr VpnGatewayNatRule, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatRulesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vgnr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.NatRulesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vgnr.Response.Response, err = future.GetResult(sender); err == nil && vgnr.Response.Response.StatusCode != http.StatusNoContent { - vgnr, err = client.CreateOrUpdateResponder(vgnr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatRulesCreateOrUpdateFuture", "Result", vgnr.Response.Response, "Failure responding to request") - } - } - return -} - -// NatRulesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type NatRulesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(NatRulesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *NatRulesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for NatRulesDeleteFuture.Result. -func (future *NatRulesDeleteFuture) result(client NatRulesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatRulesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.NatRulesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// NextHopParameters parameters that define the source and destination endpoint. -type NextHopParameters struct { - // TargetResourceID - The resource identifier of the target resource against which the action is to be performed. - TargetResourceID *string `json:"targetResourceId,omitempty"` - // SourceIPAddress - The source IP address. - SourceIPAddress *string `json:"sourceIPAddress,omitempty"` - // DestinationIPAddress - The destination IP address. - DestinationIPAddress *string `json:"destinationIPAddress,omitempty"` - // TargetNicResourceID - The NIC ID. (If VM has multiple NICs and IP forwarding is enabled on any of the nics, then this parameter must be specified. Otherwise optional). - TargetNicResourceID *string `json:"targetNicResourceId,omitempty"` -} - -// NextHopResult the information about next hop from the specified VM. -type NextHopResult struct { - autorest.Response `json:"-"` - // NextHopType - Next hop type. Possible values include: 'NextHopTypeInternet', 'NextHopTypeVirtualAppliance', 'NextHopTypeVirtualNetworkGateway', 'NextHopTypeVnetLocal', 'NextHopTypeHyperNetGateway', 'NextHopTypeNone' - NextHopType NextHopType `json:"nextHopType,omitempty"` - // NextHopIPAddress - Next hop IP Address. - NextHopIPAddress *string `json:"nextHopIpAddress,omitempty"` - // RouteTableID - The resource identifier for the route table associated with the route being returned. If the route being returned does not correspond to any user created routes then this field will be the string 'System Route'. - RouteTableID *string `json:"routeTableId,omitempty"` -} - -// O365BreakOutCategoryPolicies office365 breakout categories. -type O365BreakOutCategoryPolicies struct { - // Allow - Flag to control allow category. - Allow *bool `json:"allow,omitempty"` - // Optimize - Flag to control optimize category. - Optimize *bool `json:"optimize,omitempty"` - // Default - Flag to control default category. - Default *bool `json:"default,omitempty"` -} - -// O365PolicyProperties the Office365 breakout policy. -type O365PolicyProperties struct { - // BreakOutCategories - Office365 breakout categories. - BreakOutCategories *O365BreakOutCategoryPolicies `json:"breakOutCategories,omitempty"` -} - -// Office365PolicyProperties network Virtual Appliance Sku Properties. -type Office365PolicyProperties struct { - // BreakOutCategories - Office 365 breakout categories. - BreakOutCategories *BreakOutCategoryPolicies `json:"breakOutCategories,omitempty"` -} - -// Operation network REST API operation definition. -type Operation struct { - // Name - Operation name: {provider}/{resource}/{operation}. - Name *string `json:"name,omitempty"` - // Display - Display metadata associated with the operation. - Display *OperationDisplay `json:"display,omitempty"` - // Origin - Origin of the operation. - Origin *string `json:"origin,omitempty"` - // OperationPropertiesFormat - Operation properties format. - *OperationPropertiesFormat `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for Operation. -func (o Operation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if o.Name != nil { - objectMap["name"] = o.Name - } - if o.Display != nil { - objectMap["display"] = o.Display - } - if o.Origin != nil { - objectMap["origin"] = o.Origin - } - if o.OperationPropertiesFormat != nil { - objectMap["properties"] = o.OperationPropertiesFormat - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Operation struct. -func (o *Operation) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - o.Name = &name - } - case "display": - if v != nil { - var display OperationDisplay - err = json.Unmarshal(*v, &display) - if err != nil { - return err - } - o.Display = &display - } - case "origin": - if v != nil { - var origin string - err = json.Unmarshal(*v, &origin) - if err != nil { - return err - } - o.Origin = &origin - } - case "properties": - if v != nil { - var operationPropertiesFormat OperationPropertiesFormat - err = json.Unmarshal(*v, &operationPropertiesFormat) - if err != nil { - return err - } - o.OperationPropertiesFormat = &operationPropertiesFormat - } - } - } - - return nil -} - -// OperationDisplay display metadata associated with the operation. -type OperationDisplay struct { - // Provider - Service provider: Microsoft Network. - Provider *string `json:"provider,omitempty"` - // Resource - Resource on which the operation is performed. - Resource *string `json:"resource,omitempty"` - // Operation - Type of the operation: get, read, delete, etc. - Operation *string `json:"operation,omitempty"` - // Description - Description of the operation. - Description *string `json:"description,omitempty"` -} - -// OperationListResult result of the request to list Network operations. It contains a list of operations -// and a URL link to get the next set of results. -type OperationListResult struct { - autorest.Response `json:"-"` - // Value - List of Network operations supported by the Network resource provider. - Value *[]Operation `json:"value,omitempty"` - // NextLink - URL to get the next set of operation list results if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// OperationListResultIterator provides access to a complete listing of Operation values. -type OperationListResultIterator struct { - i int - page OperationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *OperationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *OperationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter OperationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter OperationListResultIterator) Response() OperationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter OperationListResultIterator) Value() Operation { - if !iter.page.NotDone() { - return Operation{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the OperationListResultIterator type. -func NewOperationListResultIterator(page OperationListResultPage) OperationListResultIterator { - return OperationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (olr OperationListResult) IsEmpty() bool { - return olr.Value == nil || len(*olr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (olr OperationListResult) hasNextLink() bool { - return olr.NextLink != nil && len(*olr.NextLink) != 0 -} - -// operationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (olr OperationListResult) operationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !olr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(olr.NextLink))) -} - -// OperationListResultPage contains a page of Operation values. -type OperationListResultPage struct { - fn func(context.Context, OperationListResult) (OperationListResult, error) - olr OperationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.olr) - if err != nil { - return err - } - page.olr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *OperationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page OperationListResultPage) NotDone() bool { - return !page.olr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page OperationListResultPage) Response() OperationListResult { - return page.olr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page OperationListResultPage) Values() []Operation { - if page.olr.IsEmpty() { - return nil - } - return *page.olr.Value -} - -// Creates a new instance of the OperationListResultPage type. -func NewOperationListResultPage(cur OperationListResult, getNextPage func(context.Context, OperationListResult) (OperationListResult, error)) OperationListResultPage { - return OperationListResultPage{ - fn: getNextPage, - olr: cur, - } -} - -// OperationPropertiesFormat description of operation properties format. -type OperationPropertiesFormat struct { - // ServiceSpecification - Specification of the service. - ServiceSpecification *OperationPropertiesFormatServiceSpecification `json:"serviceSpecification,omitempty"` -} - -// OperationPropertiesFormatServiceSpecification specification of the service. -type OperationPropertiesFormatServiceSpecification struct { - // MetricSpecifications - Operation service specification. - MetricSpecifications *[]MetricSpecification `json:"metricSpecifications,omitempty"` - // LogSpecifications - Operation log specification. - LogSpecifications *[]LogSpecification `json:"logSpecifications,omitempty"` -} - -// OrderBy describes a column to sort -type OrderBy struct { - // Field - Describes the actual column name to sort by - Field *string `json:"field,omitempty"` - // Order - Describes if results should be in ascending/descending order. Possible values include: 'Ascending', 'Descending' - Order FirewallPolicyIDPSQuerySortOrder `json:"order,omitempty"` -} - -// OutboundRule outbound rule of the load balancer. -type OutboundRule struct { - autorest.Response `json:"-"` - // OutboundRulePropertiesFormat - Properties of load balancer outbound rule. - *OutboundRulePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within the set of outbound rules used by the load balancer. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for OutboundRule. -func (or OutboundRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if or.OutboundRulePropertiesFormat != nil { - objectMap["properties"] = or.OutboundRulePropertiesFormat - } - if or.Name != nil { - objectMap["name"] = or.Name - } - if or.ID != nil { - objectMap["id"] = or.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for OutboundRule struct. -func (or *OutboundRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var outboundRulePropertiesFormat OutboundRulePropertiesFormat - err = json.Unmarshal(*v, &outboundRulePropertiesFormat) - if err != nil { - return err - } - or.OutboundRulePropertiesFormat = &outboundRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - or.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - or.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - or.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - or.ID = &ID - } - } - } - - return nil -} - -// OutboundRulePropertiesFormat outbound rule of the load balancer. -type OutboundRulePropertiesFormat struct { - // AllocatedOutboundPorts - The number of outbound ports to be used for NAT. - AllocatedOutboundPorts *int32 `json:"allocatedOutboundPorts,omitempty"` - // FrontendIPConfigurations - The Frontend IP addresses of the load balancer. - FrontendIPConfigurations *[]SubResource `json:"frontendIPConfigurations,omitempty"` - // BackendAddressPool - A reference to a pool of DIPs. Outbound traffic is randomly load balanced across IPs in the backend IPs. - BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the outbound rule resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // Protocol - The protocol for the outbound rule in load balancer. Possible values include: 'LoadBalancerOutboundRuleProtocolTCP', 'LoadBalancerOutboundRuleProtocolUDP', 'LoadBalancerOutboundRuleProtocolAll' - Protocol LoadBalancerOutboundRuleProtocol `json:"protocol,omitempty"` - // EnableTCPReset - Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination. This element is only used when the protocol is set to TCP. - EnableTCPReset *bool `json:"enableTcpReset,omitempty"` - // IdleTimeoutInMinutes - The timeout for the TCP idle connection. - IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` -} - -// MarshalJSON is the custom marshaler for OutboundRulePropertiesFormat. -func (orpf OutboundRulePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if orpf.AllocatedOutboundPorts != nil { - objectMap["allocatedOutboundPorts"] = orpf.AllocatedOutboundPorts - } - if orpf.FrontendIPConfigurations != nil { - objectMap["frontendIPConfigurations"] = orpf.FrontendIPConfigurations - } - if orpf.BackendAddressPool != nil { - objectMap["backendAddressPool"] = orpf.BackendAddressPool - } - if orpf.Protocol != "" { - objectMap["protocol"] = orpf.Protocol - } - if orpf.EnableTCPReset != nil { - objectMap["enableTcpReset"] = orpf.EnableTCPReset - } - if orpf.IdleTimeoutInMinutes != nil { - objectMap["idleTimeoutInMinutes"] = orpf.IdleTimeoutInMinutes - } - return json.Marshal(objectMap) -} - -// OwaspCrsExclusionEntry allow to exclude some variable satisfy the condition for the WAF check. -type OwaspCrsExclusionEntry struct { - // MatchVariable - The variable to be excluded. Possible values include: 'RequestHeaderNames', 'RequestCookieNames', 'RequestArgNames', 'RequestHeaderKeys', 'RequestHeaderValues', 'RequestCookieKeys', 'RequestCookieValues', 'RequestArgKeys', 'RequestArgValues' - MatchVariable OwaspCrsExclusionEntryMatchVariable `json:"matchVariable,omitempty"` - // SelectorMatchOperator - When matchVariable is a collection, operate on the selector to specify which elements in the collection this exclusion applies to. Possible values include: 'OwaspCrsExclusionEntrySelectorMatchOperatorEquals', 'OwaspCrsExclusionEntrySelectorMatchOperatorContains', 'OwaspCrsExclusionEntrySelectorMatchOperatorStartsWith', 'OwaspCrsExclusionEntrySelectorMatchOperatorEndsWith', 'OwaspCrsExclusionEntrySelectorMatchOperatorEqualsAny' - SelectorMatchOperator OwaspCrsExclusionEntrySelectorMatchOperator `json:"selectorMatchOperator,omitempty"` - // Selector - When matchVariable is a collection, operator used to specify which elements in the collection this exclusion applies to. - Selector *string `json:"selector,omitempty"` - // ExclusionManagedRuleSets - The managed rule sets that are associated with the exclusion. - ExclusionManagedRuleSets *[]ExclusionManagedRuleSet `json:"exclusionManagedRuleSets,omitempty"` -} - -// P2SConnectionConfiguration p2SConnectionConfiguration Resource. -type P2SConnectionConfiguration struct { - // P2SConnectionConfigurationProperties - Properties of the P2S connection configuration. - *P2SConnectionConfigurationProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SConnectionConfiguration. -func (pcc P2SConnectionConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pcc.P2SConnectionConfigurationProperties != nil { - objectMap["properties"] = pcc.P2SConnectionConfigurationProperties - } - if pcc.Name != nil { - objectMap["name"] = pcc.Name - } - if pcc.ID != nil { - objectMap["id"] = pcc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for P2SConnectionConfiguration struct. -func (pcc *P2SConnectionConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var p2SConnectionConfigurationProperties P2SConnectionConfigurationProperties - err = json.Unmarshal(*v, &p2SConnectionConfigurationProperties) - if err != nil { - return err - } - pcc.P2SConnectionConfigurationProperties = &p2SConnectionConfigurationProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pcc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pcc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pcc.ID = &ID - } - } - } - - return nil -} - -// P2SConnectionConfigurationProperties parameters for P2SConnectionConfiguration. -type P2SConnectionConfigurationProperties struct { - // VpnClientAddressPool - The reference to the address space resource which represents Address space for P2S VpnClient. - VpnClientAddressPool *AddressSpace `json:"vpnClientAddressPool,omitempty"` - // RoutingConfiguration - The Routing Configuration indicating the associated and propagated route tables on this connection. - RoutingConfiguration *RoutingConfiguration `json:"routingConfiguration,omitempty"` - // EnableInternetSecurity - Flag indicating whether the enable internet security flag is turned on for the P2S Connections or not. - EnableInternetSecurity *bool `json:"enableInternetSecurity,omitempty"` - // ConfigurationPolicyGroupAssociations - READ-ONLY; List of Configuration Policy Groups that this P2SConnectionConfiguration is attached to. - ConfigurationPolicyGroupAssociations *[]SubResource `json:"configurationPolicyGroupAssociations,omitempty"` - // PreviousConfigurationPolicyGroupAssociations - READ-ONLY; List of previous Configuration Policy Groups that this P2SConnectionConfiguration was attached to. - PreviousConfigurationPolicyGroupAssociations *[]VpnServerConfigurationPolicyGroup `json:"previousConfigurationPolicyGroupAssociations,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the P2SConnectionConfiguration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SConnectionConfigurationProperties. -func (pccp P2SConnectionConfigurationProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pccp.VpnClientAddressPool != nil { - objectMap["vpnClientAddressPool"] = pccp.VpnClientAddressPool - } - if pccp.RoutingConfiguration != nil { - objectMap["routingConfiguration"] = pccp.RoutingConfiguration - } - if pccp.EnableInternetSecurity != nil { - objectMap["enableInternetSecurity"] = pccp.EnableInternetSecurity - } - return json.Marshal(objectMap) -} - -// P2SVpnConnectionHealth p2S Vpn connection detailed health written to sas url. -type P2SVpnConnectionHealth struct { - autorest.Response `json:"-"` - // SasURL - Returned sas url of the blob to which the p2s vpn connection detailed health will be written. - SasURL *string `json:"sasUrl,omitempty"` -} - -// P2SVpnConnectionHealthRequest list of P2S Vpn connection health request. -type P2SVpnConnectionHealthRequest struct { - // VpnUserNamesFilter - The list of p2s vpn user names whose p2s vpn connection detailed health to retrieve for. - VpnUserNamesFilter *[]string `json:"vpnUserNamesFilter,omitempty"` - // OutputBlobSasURL - The sas-url to download the P2S Vpn connection health detail. - OutputBlobSasURL *string `json:"outputBlobSasUrl,omitempty"` -} - -// P2SVpnConnectionRequest list of p2s vpn connections to be disconnected. -type P2SVpnConnectionRequest struct { - // VpnConnectionIds - List of p2s vpn connection Ids. - VpnConnectionIds *[]string `json:"vpnConnectionIds,omitempty"` -} - -// P2SVpnGateway p2SVpnGateway Resource. -type P2SVpnGateway struct { - autorest.Response `json:"-"` - // P2SVpnGatewayProperties - Properties of the P2SVpnGateway. - *P2SVpnGatewayProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for P2SVpnGateway. -func (pvg P2SVpnGateway) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvg.P2SVpnGatewayProperties != nil { - objectMap["properties"] = pvg.P2SVpnGatewayProperties - } - if pvg.ID != nil { - objectMap["id"] = pvg.ID - } - if pvg.Location != nil { - objectMap["location"] = pvg.Location - } - if pvg.Tags != nil { - objectMap["tags"] = pvg.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for P2SVpnGateway struct. -func (pvg *P2SVpnGateway) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var p2SVpnGatewayProperties P2SVpnGatewayProperties - err = json.Unmarshal(*v, &p2SVpnGatewayProperties) - if err != nil { - return err - } - pvg.P2SVpnGatewayProperties = &p2SVpnGatewayProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pvg.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pvg.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pvg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - pvg.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - pvg.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - pvg.Tags = tags - } - } - } - - return nil -} - -// P2SVpnGatewayProperties parameters for P2SVpnGateway. -type P2SVpnGatewayProperties struct { - // VirtualHub - The VirtualHub to which the gateway belongs. - VirtualHub *SubResource `json:"virtualHub,omitempty"` - // P2SConnectionConfigurations - List of all p2s connection configurations of the gateway. - P2SConnectionConfigurations *[]P2SConnectionConfiguration `json:"p2SConnectionConfigurations,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the P2S VPN gateway resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // VpnGatewayScaleUnit - The scale unit for this p2s vpn gateway. - VpnGatewayScaleUnit *int32 `json:"vpnGatewayScaleUnit,omitempty"` - // VpnServerConfiguration - The VpnServerConfiguration to which the p2sVpnGateway is attached to. - VpnServerConfiguration *SubResource `json:"vpnServerConfiguration,omitempty"` - // VpnClientConnectionHealth - READ-ONLY; All P2S VPN clients' connection health status. - VpnClientConnectionHealth *VpnClientConnectionHealth `json:"vpnClientConnectionHealth,omitempty"` - // CustomDNSServers - List of all customer specified DNS servers IP addresses. - CustomDNSServers *[]string `json:"customDnsServers,omitempty"` - // IsRoutingPreferenceInternet - Enable Routing Preference property for the Public IP Interface of the P2SVpnGateway. - IsRoutingPreferenceInternet *bool `json:"isRoutingPreferenceInternet,omitempty"` -} - -// MarshalJSON is the custom marshaler for P2SVpnGatewayProperties. -func (pvgp P2SVpnGatewayProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pvgp.VirtualHub != nil { - objectMap["virtualHub"] = pvgp.VirtualHub - } - if pvgp.P2SConnectionConfigurations != nil { - objectMap["p2SConnectionConfigurations"] = pvgp.P2SConnectionConfigurations - } - if pvgp.VpnGatewayScaleUnit != nil { - objectMap["vpnGatewayScaleUnit"] = pvgp.VpnGatewayScaleUnit - } - if pvgp.VpnServerConfiguration != nil { - objectMap["vpnServerConfiguration"] = pvgp.VpnServerConfiguration - } - if pvgp.CustomDNSServers != nil { - objectMap["customDnsServers"] = pvgp.CustomDNSServers - } - if pvgp.IsRoutingPreferenceInternet != nil { - objectMap["isRoutingPreferenceInternet"] = pvgp.IsRoutingPreferenceInternet - } - return json.Marshal(objectMap) -} - -// P2sVpnGatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type P2sVpnGatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnGatewaysClient) (P2SVpnGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2sVpnGatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2sVpnGatewaysCreateOrUpdateFuture.Result. -func (future *P2sVpnGatewaysCreateOrUpdateFuture) result(client P2sVpnGatewaysClient) (pvg P2SVpnGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pvg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2sVpnGatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pvg.Response.Response, err = future.GetResult(sender); err == nil && pvg.Response.Response.StatusCode != http.StatusNoContent { - pvg, err = client.CreateOrUpdateResponder(pvg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysCreateOrUpdateFuture", "Result", pvg.Response.Response, "Failure responding to request") - } - } - return -} - -// P2sVpnGatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type P2sVpnGatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2sVpnGatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2sVpnGatewaysDeleteFuture.Result. -func (future *P2sVpnGatewaysDeleteFuture) result(client P2sVpnGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2sVpnGatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// P2sVpnGatewaysDisconnectP2sVpnConnectionsFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type P2sVpnGatewaysDisconnectP2sVpnConnectionsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2sVpnGatewaysDisconnectP2sVpnConnectionsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2sVpnGatewaysDisconnectP2sVpnConnectionsFuture.Result. -func (future *P2sVpnGatewaysDisconnectP2sVpnConnectionsFuture) result(client P2sVpnGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysDisconnectP2sVpnConnectionsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2sVpnGatewaysDisconnectP2sVpnConnectionsFuture") - return - } - ar.Response = future.Response() - return -} - -// P2sVpnGatewaysGenerateVpnProfileFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type P2sVpnGatewaysGenerateVpnProfileFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnGatewaysClient) (VpnProfileResponse, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2sVpnGatewaysGenerateVpnProfileFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2sVpnGatewaysGenerateVpnProfileFuture.Result. -func (future *P2sVpnGatewaysGenerateVpnProfileFuture) result(client P2sVpnGatewaysClient) (vpr VpnProfileResponse, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysGenerateVpnProfileFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vpr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2sVpnGatewaysGenerateVpnProfileFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vpr.Response.Response, err = future.GetResult(sender); err == nil && vpr.Response.Response.StatusCode != http.StatusNoContent { - vpr, err = client.GenerateVpnProfileResponder(vpr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysGenerateVpnProfileFuture", "Result", vpr.Response.Response, "Failure responding to request") - } - } - return -} - -// P2sVpnGatewaysGetP2sVpnConnectionHealthDetailedFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type P2sVpnGatewaysGetP2sVpnConnectionHealthDetailedFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnGatewaysClient) (P2SVpnConnectionHealth, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2sVpnGatewaysGetP2sVpnConnectionHealthDetailedFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2sVpnGatewaysGetP2sVpnConnectionHealthDetailedFuture.Result. -func (future *P2sVpnGatewaysGetP2sVpnConnectionHealthDetailedFuture) result(client P2sVpnGatewaysClient) (pvch P2SVpnConnectionHealth, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysGetP2sVpnConnectionHealthDetailedFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pvch.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2sVpnGatewaysGetP2sVpnConnectionHealthDetailedFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pvch.Response.Response, err = future.GetResult(sender); err == nil && pvch.Response.Response.StatusCode != http.StatusNoContent { - pvch, err = client.GetP2sVpnConnectionHealthDetailedResponder(pvch.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysGetP2sVpnConnectionHealthDetailedFuture", "Result", pvch.Response.Response, "Failure responding to request") - } - } - return -} - -// P2sVpnGatewaysGetP2sVpnConnectionHealthFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type P2sVpnGatewaysGetP2sVpnConnectionHealthFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnGatewaysClient) (P2SVpnGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2sVpnGatewaysGetP2sVpnConnectionHealthFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2sVpnGatewaysGetP2sVpnConnectionHealthFuture.Result. -func (future *P2sVpnGatewaysGetP2sVpnConnectionHealthFuture) result(client P2sVpnGatewaysClient) (pvg P2SVpnGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysGetP2sVpnConnectionHealthFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pvg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2sVpnGatewaysGetP2sVpnConnectionHealthFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pvg.Response.Response, err = future.GetResult(sender); err == nil && pvg.Response.Response.StatusCode != http.StatusNoContent { - pvg, err = client.GetP2sVpnConnectionHealthResponder(pvg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysGetP2sVpnConnectionHealthFuture", "Result", pvg.Response.Response, "Failure responding to request") - } - } - return -} - -// P2SVpnGatewaysResetFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type P2SVpnGatewaysResetFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnGatewaysClient) (P2SVpnGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2SVpnGatewaysResetFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2SVpnGatewaysResetFuture.Result. -func (future *P2SVpnGatewaysResetFuture) result(client P2sVpnGatewaysClient) (pvg P2SVpnGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2SVpnGatewaysResetFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pvg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2SVpnGatewaysResetFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pvg.Response.Response, err = future.GetResult(sender); err == nil && pvg.Response.Response.StatusCode != http.StatusNoContent { - pvg, err = client.ResetResponder(pvg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2SVpnGatewaysResetFuture", "Result", pvg.Response.Response, "Failure responding to request") - } - } - return -} - -// P2sVpnGatewaysUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type P2sVpnGatewaysUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(P2sVpnGatewaysClient) (P2SVpnGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *P2sVpnGatewaysUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for P2sVpnGatewaysUpdateTagsFuture.Result. -func (future *P2sVpnGatewaysUpdateTagsFuture) result(client P2sVpnGatewaysClient) (pvg P2SVpnGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pvg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.P2sVpnGatewaysUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pvg.Response.Response, err = future.GetResult(sender); err == nil && pvg.Response.Response.StatusCode != http.StatusNoContent { - pvg, err = client.UpdateTagsResponder(pvg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysUpdateTagsFuture", "Result", pvg.Response.Response, "Failure responding to request") - } - } - return -} - -// P2SVpnProfileParameters vpn Client Parameters for package generation. -type P2SVpnProfileParameters struct { - // AuthenticationMethod - VPN client authentication method. Possible values include: 'EAPTLS', 'EAPMSCHAPv2' - AuthenticationMethod AuthenticationMethod `json:"authenticationMethod,omitempty"` -} - -// PacketCapture parameters that define the create packet capture operation. -type PacketCapture struct { - // PacketCaptureParameters - Properties of the packet capture. - *PacketCaptureParameters `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for PacketCapture. -func (pc PacketCapture) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pc.PacketCaptureParameters != nil { - objectMap["properties"] = pc.PacketCaptureParameters - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PacketCapture struct. -func (pc *PacketCapture) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var packetCaptureParameters PacketCaptureParameters - err = json.Unmarshal(*v, &packetCaptureParameters) - if err != nil { - return err - } - pc.PacketCaptureParameters = &packetCaptureParameters - } - } - } - - return nil -} - -// PacketCaptureFilter filter that is applied to packet capture request. Multiple filters can be applied. -type PacketCaptureFilter struct { - // Protocol - Protocol to be filtered on. Possible values include: 'PcProtocolTCP', 'PcProtocolUDP', 'PcProtocolAny' - Protocol PcProtocol `json:"protocol,omitempty"` - // LocalIPAddress - Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5"? for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. - LocalIPAddress *string `json:"localIPAddress,omitempty"` - // RemoteIPAddress - Local IP Address to be filtered on. Notation: "127.0.0.1" for single address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. - RemoteIPAddress *string `json:"remoteIPAddress,omitempty"` - // LocalPort - Local port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. - LocalPort *string `json:"localPort,omitempty"` - // RemotePort - Remote port to be filtered on. Notation: "80" for single port entry."80-85" for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null. - RemotePort *string `json:"remotePort,omitempty"` -} - -// PacketCaptureListResult list of packet capture sessions. -type PacketCaptureListResult struct { - autorest.Response `json:"-"` - // Value - Information about packet capture sessions. - Value *[]PacketCaptureResult `json:"value,omitempty"` -} - -// PacketCaptureMachineScope a list of AzureVMSS instances which can be included or excluded to run packet -// capture. If both included and excluded are empty, then the packet capture will run on all instances of -// AzureVMSS. -type PacketCaptureMachineScope struct { - // Include - List of AzureVMSS instances to run packet capture on. - Include *[]string `json:"include,omitempty"` - // Exclude - List of AzureVMSS instances which has to be excluded from the AzureVMSS from running packet capture. - Exclude *[]string `json:"exclude,omitempty"` -} - -// PacketCaptureParameters parameters that define the create packet capture operation. -type PacketCaptureParameters struct { - // Target - The ID of the targeted resource, only AzureVM and AzureVMSS as target type are currently supported. - Target *string `json:"target,omitempty"` - // Scope - A list of AzureVMSS instances which can be included or excluded to run packet capture. If both included and excluded are empty, then the packet capture will run on all instances of AzureVMSS. - Scope *PacketCaptureMachineScope `json:"scope,omitempty"` - // TargetType - Target type of the resource provided. Possible values include: 'PacketCaptureTargetTypeAzureVM', 'PacketCaptureTargetTypeAzureVMSS' - TargetType PacketCaptureTargetType `json:"targetType,omitempty"` - // BytesToCapturePerPacket - Number of bytes captured per packet, the remaining bytes are truncated. - BytesToCapturePerPacket *int64 `json:"bytesToCapturePerPacket,omitempty"` - // TotalBytesPerSession - Maximum size of the capture output. - TotalBytesPerSession *int64 `json:"totalBytesPerSession,omitempty"` - // TimeLimitInSeconds - Maximum duration of the capture session in seconds. - TimeLimitInSeconds *int32 `json:"timeLimitInSeconds,omitempty"` - // StorageLocation - The storage location for a packet capture session. - StorageLocation *PacketCaptureStorageLocation `json:"storageLocation,omitempty"` - // Filters - A list of packet capture filters. - Filters *[]PacketCaptureFilter `json:"filters,omitempty"` -} - -// PacketCaptureQueryStatusResult status of packet capture session. -type PacketCaptureQueryStatusResult struct { - autorest.Response `json:"-"` - // Name - The name of the packet capture resource. - Name *string `json:"name,omitempty"` - // ID - The ID of the packet capture resource. - ID *string `json:"id,omitempty"` - // CaptureStartTime - The start time of the packet capture session. - CaptureStartTime *date.Time `json:"captureStartTime,omitempty"` - // PacketCaptureStatus - The status of the packet capture session. Possible values include: 'PcStatusNotStarted', 'PcStatusRunning', 'PcStatusStopped', 'PcStatusError', 'PcStatusUnknown' - PacketCaptureStatus PcStatus `json:"packetCaptureStatus,omitempty"` - // StopReason - The reason the current packet capture session was stopped. - StopReason *string `json:"stopReason,omitempty"` - // PacketCaptureError - List of errors of packet capture session. - PacketCaptureError *[]PcError `json:"packetCaptureError,omitempty"` -} - -// PacketCaptureResult information about packet capture session. -type PacketCaptureResult struct { - autorest.Response `json:"-"` - // Name - READ-ONLY; Name of the packet capture session. - Name *string `json:"name,omitempty"` - // ID - READ-ONLY; ID of the packet capture operation. - ID *string `json:"id,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // PacketCaptureResultProperties - Properties of the packet capture result. - *PacketCaptureResultProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for PacketCaptureResult. -func (pcr PacketCaptureResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pcr.PacketCaptureResultProperties != nil { - objectMap["properties"] = pcr.PacketCaptureResultProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PacketCaptureResult struct. -func (pcr *PacketCaptureResult) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pcr.Name = &name - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pcr.ID = &ID - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pcr.Etag = &etag - } - case "properties": - if v != nil { - var packetCaptureResultProperties PacketCaptureResultProperties - err = json.Unmarshal(*v, &packetCaptureResultProperties) - if err != nil { - return err - } - pcr.PacketCaptureResultProperties = &packetCaptureResultProperties - } - } - } - - return nil -} - -// PacketCaptureResultProperties the properties of a packet capture session. -type PacketCaptureResultProperties struct { - // ProvisioningState - READ-ONLY; The provisioning state of the packet capture session. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // Target - The ID of the targeted resource, only AzureVM and AzureVMSS as target type are currently supported. - Target *string `json:"target,omitempty"` - // Scope - A list of AzureVMSS instances which can be included or excluded to run packet capture. If both included and excluded are empty, then the packet capture will run on all instances of AzureVMSS. - Scope *PacketCaptureMachineScope `json:"scope,omitempty"` - // TargetType - Target type of the resource provided. Possible values include: 'PacketCaptureTargetTypeAzureVM', 'PacketCaptureTargetTypeAzureVMSS' - TargetType PacketCaptureTargetType `json:"targetType,omitempty"` - // BytesToCapturePerPacket - Number of bytes captured per packet, the remaining bytes are truncated. - BytesToCapturePerPacket *int64 `json:"bytesToCapturePerPacket,omitempty"` - // TotalBytesPerSession - Maximum size of the capture output. - TotalBytesPerSession *int64 `json:"totalBytesPerSession,omitempty"` - // TimeLimitInSeconds - Maximum duration of the capture session in seconds. - TimeLimitInSeconds *int32 `json:"timeLimitInSeconds,omitempty"` - // StorageLocation - The storage location for a packet capture session. - StorageLocation *PacketCaptureStorageLocation `json:"storageLocation,omitempty"` - // Filters - A list of packet capture filters. - Filters *[]PacketCaptureFilter `json:"filters,omitempty"` -} - -// MarshalJSON is the custom marshaler for PacketCaptureResultProperties. -func (pcrp PacketCaptureResultProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pcrp.Target != nil { - objectMap["target"] = pcrp.Target - } - if pcrp.Scope != nil { - objectMap["scope"] = pcrp.Scope - } - if pcrp.TargetType != "" { - objectMap["targetType"] = pcrp.TargetType - } - if pcrp.BytesToCapturePerPacket != nil { - objectMap["bytesToCapturePerPacket"] = pcrp.BytesToCapturePerPacket - } - if pcrp.TotalBytesPerSession != nil { - objectMap["totalBytesPerSession"] = pcrp.TotalBytesPerSession - } - if pcrp.TimeLimitInSeconds != nil { - objectMap["timeLimitInSeconds"] = pcrp.TimeLimitInSeconds - } - if pcrp.StorageLocation != nil { - objectMap["storageLocation"] = pcrp.StorageLocation - } - if pcrp.Filters != nil { - objectMap["filters"] = pcrp.Filters - } - return json.Marshal(objectMap) -} - -// PacketCapturesCreateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PacketCapturesCreateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PacketCapturesClient) (PacketCaptureResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PacketCapturesCreateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PacketCapturesCreateFuture.Result. -func (future *PacketCapturesCreateFuture) result(client PacketCapturesClient) (pcr PacketCaptureResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesCreateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pcr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PacketCapturesCreateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pcr.Response.Response, err = future.GetResult(sender); err == nil && pcr.Response.Response.StatusCode != http.StatusNoContent { - pcr, err = client.CreateResponder(pcr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesCreateFuture", "Result", pcr.Response.Response, "Failure responding to request") - } - } - return -} - -// PacketCapturesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PacketCapturesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PacketCapturesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PacketCapturesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PacketCapturesDeleteFuture.Result. -func (future *PacketCapturesDeleteFuture) result(client PacketCapturesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PacketCapturesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// PacketCapturesGetStatusFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PacketCapturesGetStatusFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PacketCapturesClient) (PacketCaptureQueryStatusResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PacketCapturesGetStatusFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PacketCapturesGetStatusFuture.Result. -func (future *PacketCapturesGetStatusFuture) result(client PacketCapturesClient) (pcqsr PacketCaptureQueryStatusResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesGetStatusFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pcqsr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PacketCapturesGetStatusFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pcqsr.Response.Response, err = future.GetResult(sender); err == nil && pcqsr.Response.Response.StatusCode != http.StatusNoContent { - pcqsr, err = client.GetStatusResponder(pcqsr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesGetStatusFuture", "Result", pcqsr.Response.Response, "Failure responding to request") - } - } - return -} - -// PacketCapturesStopFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PacketCapturesStopFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PacketCapturesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PacketCapturesStopFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PacketCapturesStopFuture.Result. -func (future *PacketCapturesStopFuture) result(client PacketCapturesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesStopFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PacketCapturesStopFuture") - return - } - ar.Response = future.Response() - return -} - -// PacketCaptureStorageLocation the storage location for a packet capture session. -type PacketCaptureStorageLocation struct { - // StorageID - The ID of the storage account to save the packet capture session. Required if no local file path is provided. - StorageID *string `json:"storageId,omitempty"` - // StoragePath - The URI of the storage path to save the packet capture. Must be a well-formed URI describing the location to save the packet capture. - StoragePath *string `json:"storagePath,omitempty"` - // FilePath - A valid local path on the targeting VM. Must include the name of the capture file (*.cap). For linux virtual machine it must start with /var/captures. Required if no storage ID is provided, otherwise optional. - FilePath *string `json:"filePath,omitempty"` -} - -// Parameter parameters for an Action. -type Parameter struct { - // RoutePrefix - List of route prefixes. - RoutePrefix *[]string `json:"routePrefix,omitempty"` - // Community - List of BGP communities. - Community *[]string `json:"community,omitempty"` - // AsPath - List of AS paths. - AsPath *[]string `json:"asPath,omitempty"` -} - -// PartnerManagedResourceProperties properties of the partner managed resource. -type PartnerManagedResourceProperties struct { - // ID - READ-ONLY; The partner managed resource id. - ID *string `json:"id,omitempty"` - // InternalLoadBalancerID - READ-ONLY; The partner managed ILB resource id - InternalLoadBalancerID *string `json:"internalLoadBalancerId,omitempty"` - // StandardLoadBalancerID - READ-ONLY; The partner managed SLB resource id - StandardLoadBalancerID *string `json:"standardLoadBalancerId,omitempty"` -} - -// MarshalJSON is the custom marshaler for PartnerManagedResourceProperties. -func (pmrp PartnerManagedResourceProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// PatchObject object for patch operations. -type PatchObject struct { - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for PatchObject. -func (po PatchObject) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if po.Tags != nil { - objectMap["tags"] = po.Tags - } - return json.Marshal(objectMap) -} - -// PatchRouteFilter route Filter Resource. -type PatchRouteFilter struct { - // RouteFilterPropertiesFormat - Properties of the route filter. - *RouteFilterPropertiesFormat `json:"properties,omitempty"` - // Name - READ-ONLY; The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for PatchRouteFilter. -func (prf PatchRouteFilter) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if prf.RouteFilterPropertiesFormat != nil { - objectMap["properties"] = prf.RouteFilterPropertiesFormat - } - if prf.Tags != nil { - objectMap["tags"] = prf.Tags - } - if prf.ID != nil { - objectMap["id"] = prf.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PatchRouteFilter struct. -func (prf *PatchRouteFilter) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routeFilterPropertiesFormat RouteFilterPropertiesFormat - err = json.Unmarshal(*v, &routeFilterPropertiesFormat) - if err != nil { - return err - } - prf.RouteFilterPropertiesFormat = &routeFilterPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - prf.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - prf.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - prf.Type = &typeVar - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - prf.Tags = tags - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - prf.ID = &ID - } - } - } - - return nil -} - -// PatchRouteFilterRule route Filter Rule Resource. -type PatchRouteFilterRule struct { - // RouteFilterRulePropertiesFormat - Properties of the route filter rule. - *RouteFilterRulePropertiesFormat `json:"properties,omitempty"` - // Name - READ-ONLY; The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for PatchRouteFilterRule. -func (prfr PatchRouteFilterRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if prfr.RouteFilterRulePropertiesFormat != nil { - objectMap["properties"] = prfr.RouteFilterRulePropertiesFormat - } - if prfr.ID != nil { - objectMap["id"] = prfr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PatchRouteFilterRule struct. -func (prfr *PatchRouteFilterRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routeFilterRulePropertiesFormat RouteFilterRulePropertiesFormat - err = json.Unmarshal(*v, &routeFilterRulePropertiesFormat) - if err != nil { - return err - } - prfr.RouteFilterRulePropertiesFormat = &routeFilterRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - prfr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - prfr.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - prfr.ID = &ID - } - } - } - - return nil -} - -// PeerExpressRouteCircuitConnection peer Express Route Circuit Connection in an ExpressRouteCircuitPeering -// resource. -type PeerExpressRouteCircuitConnection struct { - autorest.Response `json:"-"` - // PeerExpressRouteCircuitConnectionPropertiesFormat - Properties of the peer express route circuit connection. - *PeerExpressRouteCircuitConnectionPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for PeerExpressRouteCircuitConnection. -func (percc PeerExpressRouteCircuitConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if percc.PeerExpressRouteCircuitConnectionPropertiesFormat != nil { - objectMap["properties"] = percc.PeerExpressRouteCircuitConnectionPropertiesFormat - } - if percc.Name != nil { - objectMap["name"] = percc.Name - } - if percc.ID != nil { - objectMap["id"] = percc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PeerExpressRouteCircuitConnection struct. -func (percc *PeerExpressRouteCircuitConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var peerExpressRouteCircuitConnectionPropertiesFormat PeerExpressRouteCircuitConnectionPropertiesFormat - err = json.Unmarshal(*v, &peerExpressRouteCircuitConnectionPropertiesFormat) - if err != nil { - return err - } - percc.PeerExpressRouteCircuitConnectionPropertiesFormat = &peerExpressRouteCircuitConnectionPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - percc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - percc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - percc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - percc.ID = &ID - } - } - } - - return nil -} - -// PeerExpressRouteCircuitConnectionListResult response for ListPeeredConnections API service call -// retrieves all global reach peer circuit connections that belongs to a Private Peering for an -// ExpressRouteCircuit. -type PeerExpressRouteCircuitConnectionListResult struct { - autorest.Response `json:"-"` - // Value - The global reach peer circuit connection associated with Private Peering in an ExpressRoute Circuit. - Value *[]PeerExpressRouteCircuitConnection `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// PeerExpressRouteCircuitConnectionListResultIterator provides access to a complete listing of -// PeerExpressRouteCircuitConnection values. -type PeerExpressRouteCircuitConnectionListResultIterator struct { - i int - page PeerExpressRouteCircuitConnectionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *PeerExpressRouteCircuitConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PeerExpressRouteCircuitConnectionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PeerExpressRouteCircuitConnectionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PeerExpressRouteCircuitConnectionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter PeerExpressRouteCircuitConnectionListResultIterator) Response() PeerExpressRouteCircuitConnectionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter PeerExpressRouteCircuitConnectionListResultIterator) Value() PeerExpressRouteCircuitConnection { - if !iter.page.NotDone() { - return PeerExpressRouteCircuitConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PeerExpressRouteCircuitConnectionListResultIterator type. -func NewPeerExpressRouteCircuitConnectionListResultIterator(page PeerExpressRouteCircuitConnectionListResultPage) PeerExpressRouteCircuitConnectionListResultIterator { - return PeerExpressRouteCircuitConnectionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (percclr PeerExpressRouteCircuitConnectionListResult) IsEmpty() bool { - return percclr.Value == nil || len(*percclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (percclr PeerExpressRouteCircuitConnectionListResult) hasNextLink() bool { - return percclr.NextLink != nil && len(*percclr.NextLink) != 0 -} - -// peerExpressRouteCircuitConnectionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (percclr PeerExpressRouteCircuitConnectionListResult) peerExpressRouteCircuitConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !percclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(percclr.NextLink))) -} - -// PeerExpressRouteCircuitConnectionListResultPage contains a page of PeerExpressRouteCircuitConnection -// values. -type PeerExpressRouteCircuitConnectionListResultPage struct { - fn func(context.Context, PeerExpressRouteCircuitConnectionListResult) (PeerExpressRouteCircuitConnectionListResult, error) - percclr PeerExpressRouteCircuitConnectionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PeerExpressRouteCircuitConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PeerExpressRouteCircuitConnectionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.percclr) - if err != nil { - return err - } - page.percclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PeerExpressRouteCircuitConnectionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PeerExpressRouteCircuitConnectionListResultPage) NotDone() bool { - return !page.percclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PeerExpressRouteCircuitConnectionListResultPage) Response() PeerExpressRouteCircuitConnectionListResult { - return page.percclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PeerExpressRouteCircuitConnectionListResultPage) Values() []PeerExpressRouteCircuitConnection { - if page.percclr.IsEmpty() { - return nil - } - return *page.percclr.Value -} - -// Creates a new instance of the PeerExpressRouteCircuitConnectionListResultPage type. -func NewPeerExpressRouteCircuitConnectionListResultPage(cur PeerExpressRouteCircuitConnectionListResult, getNextPage func(context.Context, PeerExpressRouteCircuitConnectionListResult) (PeerExpressRouteCircuitConnectionListResult, error)) PeerExpressRouteCircuitConnectionListResultPage { - return PeerExpressRouteCircuitConnectionListResultPage{ - fn: getNextPage, - percclr: cur, - } -} - -// PeerExpressRouteCircuitConnectionPropertiesFormat properties of the peer express route circuit -// connection. -type PeerExpressRouteCircuitConnectionPropertiesFormat struct { - // ExpressRouteCircuitPeering - Reference to Express Route Circuit Private Peering Resource of the circuit. - ExpressRouteCircuitPeering *SubResource `json:"expressRouteCircuitPeering,omitempty"` - // PeerExpressRouteCircuitPeering - Reference to Express Route Circuit Private Peering Resource of the peered circuit. - PeerExpressRouteCircuitPeering *SubResource `json:"peerExpressRouteCircuitPeering,omitempty"` - // AddressPrefix - /29 IP address space to carve out Customer addresses for tunnels. - AddressPrefix *string `json:"addressPrefix,omitempty"` - // CircuitConnectionStatus - Express Route Circuit connection state. Possible values include: 'Connected', 'Connecting', 'Disconnected' - CircuitConnectionStatus CircuitConnectionStatus `json:"circuitConnectionStatus,omitempty"` - // ConnectionName - The name of the express route circuit connection resource. - ConnectionName *string `json:"connectionName,omitempty"` - // AuthResourceGUID - The resource guid of the authorization used for the express route circuit connection. - AuthResourceGUID *string `json:"authResourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the peer express route circuit connection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for PeerExpressRouteCircuitConnectionPropertiesFormat. -func (perccpf PeerExpressRouteCircuitConnectionPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if perccpf.ExpressRouteCircuitPeering != nil { - objectMap["expressRouteCircuitPeering"] = perccpf.ExpressRouteCircuitPeering - } - if perccpf.PeerExpressRouteCircuitPeering != nil { - objectMap["peerExpressRouteCircuitPeering"] = perccpf.PeerExpressRouteCircuitPeering - } - if perccpf.AddressPrefix != nil { - objectMap["addressPrefix"] = perccpf.AddressPrefix - } - if perccpf.CircuitConnectionStatus != "" { - objectMap["circuitConnectionStatus"] = perccpf.CircuitConnectionStatus - } - if perccpf.ConnectionName != nil { - objectMap["connectionName"] = perccpf.ConnectionName - } - if perccpf.AuthResourceGUID != nil { - objectMap["authResourceGuid"] = perccpf.AuthResourceGUID - } - return json.Marshal(objectMap) -} - -// PeerRoute peer routing details. -type PeerRoute struct { - // LocalAddress - READ-ONLY; The peer's local address. - LocalAddress *string `json:"localAddress,omitempty"` - // NetworkProperty - READ-ONLY; The route's network prefix. - NetworkProperty *string `json:"network,omitempty"` - // NextHop - READ-ONLY; The route's next hop. - NextHop *string `json:"nextHop,omitempty"` - // SourcePeer - READ-ONLY; The peer this route was learned from. - SourcePeer *string `json:"sourcePeer,omitempty"` - // Origin - READ-ONLY; The source this route was learned from. - Origin *string `json:"origin,omitempty"` - // AsPath - READ-ONLY; The route's AS path sequence. - AsPath *string `json:"asPath,omitempty"` - // Weight - READ-ONLY; The route's weight. - Weight *int32 `json:"weight,omitempty"` -} - -// MarshalJSON is the custom marshaler for PeerRoute. -func (pr PeerRoute) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// PeerRouteList list of virtual router peer routes. -type PeerRouteList struct { - autorest.Response `json:"-"` - // Value - List of peer routes. - Value *[]PeerRoute `json:"value,omitempty"` -} - -// PolicySettings defines contents of a web application firewall global configuration. -type PolicySettings struct { - // State - The state of the policy. Possible values include: 'WebApplicationFirewallEnabledStateDisabled', 'WebApplicationFirewallEnabledStateEnabled' - State WebApplicationFirewallEnabledState `json:"state,omitempty"` - // Mode - The mode of the policy. Possible values include: 'WebApplicationFirewallModePrevention', 'WebApplicationFirewallModeDetection' - Mode WebApplicationFirewallMode `json:"mode,omitempty"` - // RequestBodyCheck - Whether to allow WAF to check request Body. - RequestBodyCheck *bool `json:"requestBodyCheck,omitempty"` - // MaxRequestBodySizeInKb - Maximum request body size in Kb for WAF. - MaxRequestBodySizeInKb *int32 `json:"maxRequestBodySizeInKb,omitempty"` - // FileUploadLimitInMb - Maximum file upload size in Mb for WAF. - FileUploadLimitInMb *int32 `json:"fileUploadLimitInMb,omitempty"` - // CustomBlockResponseStatusCode - If the action type is block, customer can override the response status code. - CustomBlockResponseStatusCode *int32 `json:"customBlockResponseStatusCode,omitempty"` - // CustomBlockResponseBody - If the action type is block, customer can override the response body. The body must be specified in base64 encoding. - CustomBlockResponseBody *string `json:"customBlockResponseBody,omitempty"` -} - -// PrepareNetworkPoliciesRequest details of PrepareNetworkPolicies for Subnet. -type PrepareNetworkPoliciesRequest struct { - // ServiceName - The name of the service for which subnet is being prepared for. - ServiceName *string `json:"serviceName,omitempty"` - // NetworkIntentPolicyConfigurations - A list of NetworkIntentPolicyConfiguration. - NetworkIntentPolicyConfigurations *[]IntentPolicyConfiguration `json:"networkIntentPolicyConfigurations,omitempty"` -} - -// PrivateDNSZoneConfig privateDnsZoneConfig resource. -type PrivateDNSZoneConfig struct { - // Name - Name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // PrivateDNSZonePropertiesFormat - Properties of the private dns zone configuration. - *PrivateDNSZonePropertiesFormat `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateDNSZoneConfig. -func (pdzc PrivateDNSZoneConfig) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pdzc.Name != nil { - objectMap["name"] = pdzc.Name - } - if pdzc.PrivateDNSZonePropertiesFormat != nil { - objectMap["properties"] = pdzc.PrivateDNSZonePropertiesFormat - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PrivateDNSZoneConfig struct. -func (pdzc *PrivateDNSZoneConfig) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pdzc.Name = &name - } - case "properties": - if v != nil { - var privateDNSZonePropertiesFormat PrivateDNSZonePropertiesFormat - err = json.Unmarshal(*v, &privateDNSZonePropertiesFormat) - if err != nil { - return err - } - pdzc.PrivateDNSZonePropertiesFormat = &privateDNSZonePropertiesFormat - } - } - } - - return nil -} - -// PrivateDNSZoneGroup private dns zone group resource. -type PrivateDNSZoneGroup struct { - autorest.Response `json:"-"` - // Name - Name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // PrivateDNSZoneGroupPropertiesFormat - Properties of the private dns zone group. - *PrivateDNSZoneGroupPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateDNSZoneGroup. -func (pdzg PrivateDNSZoneGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pdzg.Name != nil { - objectMap["name"] = pdzg.Name - } - if pdzg.PrivateDNSZoneGroupPropertiesFormat != nil { - objectMap["properties"] = pdzg.PrivateDNSZoneGroupPropertiesFormat - } - if pdzg.ID != nil { - objectMap["id"] = pdzg.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PrivateDNSZoneGroup struct. -func (pdzg *PrivateDNSZoneGroup) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pdzg.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pdzg.Etag = &etag - } - case "properties": - if v != nil { - var privateDNSZoneGroupPropertiesFormat PrivateDNSZoneGroupPropertiesFormat - err = json.Unmarshal(*v, &privateDNSZoneGroupPropertiesFormat) - if err != nil { - return err - } - pdzg.PrivateDNSZoneGroupPropertiesFormat = &privateDNSZoneGroupPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pdzg.ID = &ID - } - } - } - - return nil -} - -// PrivateDNSZoneGroupListResult response for the ListPrivateDnsZoneGroups API service call. -type PrivateDNSZoneGroupListResult struct { - autorest.Response `json:"-"` - // Value - A list of private dns zone group resources in a private endpoint. - Value *[]PrivateDNSZoneGroup `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateDNSZoneGroupListResult. -func (pdzglr PrivateDNSZoneGroupListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pdzglr.Value != nil { - objectMap["value"] = pdzglr.Value - } - return json.Marshal(objectMap) -} - -// PrivateDNSZoneGroupListResultIterator provides access to a complete listing of PrivateDNSZoneGroup -// values. -type PrivateDNSZoneGroupListResultIterator struct { - i int - page PrivateDNSZoneGroupListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *PrivateDNSZoneGroupListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateDNSZoneGroupListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PrivateDNSZoneGroupListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PrivateDNSZoneGroupListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter PrivateDNSZoneGroupListResultIterator) Response() PrivateDNSZoneGroupListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter PrivateDNSZoneGroupListResultIterator) Value() PrivateDNSZoneGroup { - if !iter.page.NotDone() { - return PrivateDNSZoneGroup{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PrivateDNSZoneGroupListResultIterator type. -func NewPrivateDNSZoneGroupListResultIterator(page PrivateDNSZoneGroupListResultPage) PrivateDNSZoneGroupListResultIterator { - return PrivateDNSZoneGroupListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (pdzglr PrivateDNSZoneGroupListResult) IsEmpty() bool { - return pdzglr.Value == nil || len(*pdzglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (pdzglr PrivateDNSZoneGroupListResult) hasNextLink() bool { - return pdzglr.NextLink != nil && len(*pdzglr.NextLink) != 0 -} - -// privateDNSZoneGroupListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (pdzglr PrivateDNSZoneGroupListResult) privateDNSZoneGroupListResultPreparer(ctx context.Context) (*http.Request, error) { - if !pdzglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(pdzglr.NextLink))) -} - -// PrivateDNSZoneGroupListResultPage contains a page of PrivateDNSZoneGroup values. -type PrivateDNSZoneGroupListResultPage struct { - fn func(context.Context, PrivateDNSZoneGroupListResult) (PrivateDNSZoneGroupListResult, error) - pdzglr PrivateDNSZoneGroupListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PrivateDNSZoneGroupListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateDNSZoneGroupListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.pdzglr) - if err != nil { - return err - } - page.pdzglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PrivateDNSZoneGroupListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PrivateDNSZoneGroupListResultPage) NotDone() bool { - return !page.pdzglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PrivateDNSZoneGroupListResultPage) Response() PrivateDNSZoneGroupListResult { - return page.pdzglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PrivateDNSZoneGroupListResultPage) Values() []PrivateDNSZoneGroup { - if page.pdzglr.IsEmpty() { - return nil - } - return *page.pdzglr.Value -} - -// Creates a new instance of the PrivateDNSZoneGroupListResultPage type. -func NewPrivateDNSZoneGroupListResultPage(cur PrivateDNSZoneGroupListResult, getNextPage func(context.Context, PrivateDNSZoneGroupListResult) (PrivateDNSZoneGroupListResult, error)) PrivateDNSZoneGroupListResultPage { - return PrivateDNSZoneGroupListResultPage{ - fn: getNextPage, - pdzglr: cur, - } -} - -// PrivateDNSZoneGroupPropertiesFormat properties of the private dns zone group. -type PrivateDNSZoneGroupPropertiesFormat struct { - // ProvisioningState - READ-ONLY; The provisioning state of the private dns zone group resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // PrivateDNSZoneConfigs - A collection of private dns zone configurations of the private dns zone group. - PrivateDNSZoneConfigs *[]PrivateDNSZoneConfig `json:"privateDnsZoneConfigs,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateDNSZoneGroupPropertiesFormat. -func (pdzgpf PrivateDNSZoneGroupPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pdzgpf.PrivateDNSZoneConfigs != nil { - objectMap["privateDnsZoneConfigs"] = pdzgpf.PrivateDNSZoneConfigs - } - return json.Marshal(objectMap) -} - -// PrivateDNSZoneGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PrivateDNSZoneGroupsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PrivateDNSZoneGroupsClient) (PrivateDNSZoneGroup, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PrivateDNSZoneGroupsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PrivateDNSZoneGroupsCreateOrUpdateFuture.Result. -func (future *PrivateDNSZoneGroupsCreateOrUpdateFuture) result(client PrivateDNSZoneGroupsClient) (pdzg PrivateDNSZoneGroup, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pdzg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PrivateDNSZoneGroupsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pdzg.Response.Response, err = future.GetResult(sender); err == nil && pdzg.Response.Response.StatusCode != http.StatusNoContent { - pdzg, err = client.CreateOrUpdateResponder(pdzg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsCreateOrUpdateFuture", "Result", pdzg.Response.Response, "Failure responding to request") - } - } - return -} - -// PrivateDNSZoneGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PrivateDNSZoneGroupsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PrivateDNSZoneGroupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PrivateDNSZoneGroupsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PrivateDNSZoneGroupsDeleteFuture.Result. -func (future *PrivateDNSZoneGroupsDeleteFuture) result(client PrivateDNSZoneGroupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PrivateDNSZoneGroupsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// PrivateDNSZonePropertiesFormat properties of the private dns zone configuration resource. -type PrivateDNSZonePropertiesFormat struct { - // PrivateDNSZoneID - The resource id of the private dns zone. - PrivateDNSZoneID *string `json:"privateDnsZoneId,omitempty"` - // RecordSets - READ-ONLY; A collection of information regarding a recordSet, holding information to identify private resources. - RecordSets *[]RecordSet `json:"recordSets,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateDNSZonePropertiesFormat. -func (pdzpf PrivateDNSZonePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pdzpf.PrivateDNSZoneID != nil { - objectMap["privateDnsZoneId"] = pdzpf.PrivateDNSZoneID - } - return json.Marshal(objectMap) -} - -// PrivateEndpoint private endpoint resource. -type PrivateEndpoint struct { - autorest.Response `json:"-"` - // ExtendedLocation - The extended location of the load balancer. - ExtendedLocation *ExtendedLocation `json:"extendedLocation,omitempty"` - // PrivateEndpointProperties - Properties of the private endpoint. - *PrivateEndpointProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for PrivateEndpoint. -func (peVar PrivateEndpoint) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if peVar.ExtendedLocation != nil { - objectMap["extendedLocation"] = peVar.ExtendedLocation - } - if peVar.PrivateEndpointProperties != nil { - objectMap["properties"] = peVar.PrivateEndpointProperties - } - if peVar.ID != nil { - objectMap["id"] = peVar.ID - } - if peVar.Location != nil { - objectMap["location"] = peVar.Location - } - if peVar.Tags != nil { - objectMap["tags"] = peVar.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PrivateEndpoint struct. -func (peVar *PrivateEndpoint) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "extendedLocation": - if v != nil { - var extendedLocation ExtendedLocation - err = json.Unmarshal(*v, &extendedLocation) - if err != nil { - return err - } - peVar.ExtendedLocation = &extendedLocation - } - case "properties": - if v != nil { - var privateEndpointProperties PrivateEndpointProperties - err = json.Unmarshal(*v, &privateEndpointProperties) - if err != nil { - return err - } - peVar.PrivateEndpointProperties = &privateEndpointProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - peVar.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - peVar.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - peVar.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - peVar.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - peVar.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - peVar.Tags = tags - } - } - } - - return nil -} - -// PrivateEndpointConnection privateEndpointConnection resource. -type PrivateEndpointConnection struct { - autorest.Response `json:"-"` - // PrivateEndpointConnectionProperties - Properties of the private end point connection. - *PrivateEndpointConnectionProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateEndpointConnection. -func (pec PrivateEndpointConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pec.PrivateEndpointConnectionProperties != nil { - objectMap["properties"] = pec.PrivateEndpointConnectionProperties - } - if pec.Name != nil { - objectMap["name"] = pec.Name - } - if pec.ID != nil { - objectMap["id"] = pec.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PrivateEndpointConnection struct. -func (pec *PrivateEndpointConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var privateEndpointConnectionProperties PrivateEndpointConnectionProperties - err = json.Unmarshal(*v, &privateEndpointConnectionProperties) - if err != nil { - return err - } - pec.PrivateEndpointConnectionProperties = &privateEndpointConnectionProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pec.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - pec.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pec.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pec.ID = &ID - } - } - } - - return nil -} - -// PrivateEndpointConnectionListResult response for the ListPrivateEndpointConnection API service call. -type PrivateEndpointConnectionListResult struct { - autorest.Response `json:"-"` - // Value - A list of PrivateEndpointConnection resources for a specific private link service. - Value *[]PrivateEndpointConnection `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateEndpointConnectionListResult. -func (peclr PrivateEndpointConnectionListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if peclr.Value != nil { - objectMap["value"] = peclr.Value - } - return json.Marshal(objectMap) -} - -// PrivateEndpointConnectionListResultIterator provides access to a complete listing of -// PrivateEndpointConnection values. -type PrivateEndpointConnectionListResultIterator struct { - i int - page PrivateEndpointConnectionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *PrivateEndpointConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PrivateEndpointConnectionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PrivateEndpointConnectionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter PrivateEndpointConnectionListResultIterator) Response() PrivateEndpointConnectionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter PrivateEndpointConnectionListResultIterator) Value() PrivateEndpointConnection { - if !iter.page.NotDone() { - return PrivateEndpointConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PrivateEndpointConnectionListResultIterator type. -func NewPrivateEndpointConnectionListResultIterator(page PrivateEndpointConnectionListResultPage) PrivateEndpointConnectionListResultIterator { - return PrivateEndpointConnectionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (peclr PrivateEndpointConnectionListResult) IsEmpty() bool { - return peclr.Value == nil || len(*peclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (peclr PrivateEndpointConnectionListResult) hasNextLink() bool { - return peclr.NextLink != nil && len(*peclr.NextLink) != 0 -} - -// privateEndpointConnectionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (peclr PrivateEndpointConnectionListResult) privateEndpointConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !peclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(peclr.NextLink))) -} - -// PrivateEndpointConnectionListResultPage contains a page of PrivateEndpointConnection values. -type PrivateEndpointConnectionListResultPage struct { - fn func(context.Context, PrivateEndpointConnectionListResult) (PrivateEndpointConnectionListResult, error) - peclr PrivateEndpointConnectionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PrivateEndpointConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.peclr) - if err != nil { - return err - } - page.peclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PrivateEndpointConnectionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PrivateEndpointConnectionListResultPage) NotDone() bool { - return !page.peclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PrivateEndpointConnectionListResultPage) Response() PrivateEndpointConnectionListResult { - return page.peclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PrivateEndpointConnectionListResultPage) Values() []PrivateEndpointConnection { - if page.peclr.IsEmpty() { - return nil - } - return *page.peclr.Value -} - -// Creates a new instance of the PrivateEndpointConnectionListResultPage type. -func NewPrivateEndpointConnectionListResultPage(cur PrivateEndpointConnectionListResult, getNextPage func(context.Context, PrivateEndpointConnectionListResult) (PrivateEndpointConnectionListResult, error)) PrivateEndpointConnectionListResultPage { - return PrivateEndpointConnectionListResultPage{ - fn: getNextPage, - peclr: cur, - } -} - -// PrivateEndpointConnectionProperties properties of the PrivateEndpointConnectProperties. -type PrivateEndpointConnectionProperties struct { - // PrivateEndpoint - READ-ONLY; The resource of private end point. - PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` - // PrivateLinkServiceConnectionState - A collection of information about the state of the connection between service consumer and provider. - PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState `json:"privateLinkServiceConnectionState,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the private endpoint connection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // LinkIdentifier - READ-ONLY; The consumer link id. - LinkIdentifier *string `json:"linkIdentifier,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateEndpointConnectionProperties. -func (pecp PrivateEndpointConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pecp.PrivateLinkServiceConnectionState != nil { - objectMap["privateLinkServiceConnectionState"] = pecp.PrivateLinkServiceConnectionState - } - return json.Marshal(objectMap) -} - -// PrivateEndpointIPConfiguration an IP Configuration of the private endpoint. -type PrivateEndpointIPConfiguration struct { - // PrivateEndpointIPConfigurationProperties - Properties of private endpoint IP configurations. - *PrivateEndpointIPConfigurationProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateEndpointIPConfiguration. -func (peic PrivateEndpointIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if peic.PrivateEndpointIPConfigurationProperties != nil { - objectMap["properties"] = peic.PrivateEndpointIPConfigurationProperties - } - if peic.Name != nil { - objectMap["name"] = peic.Name - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PrivateEndpointIPConfiguration struct. -func (peic *PrivateEndpointIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var privateEndpointIPConfigurationProperties PrivateEndpointIPConfigurationProperties - err = json.Unmarshal(*v, &privateEndpointIPConfigurationProperties) - if err != nil { - return err - } - peic.PrivateEndpointIPConfigurationProperties = &privateEndpointIPConfigurationProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - peic.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - peic.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - peic.Etag = &etag - } - } - } - - return nil -} - -// PrivateEndpointIPConfigurationProperties properties of an IP Configuration of the private endpoint. -type PrivateEndpointIPConfigurationProperties struct { - // GroupID - The ID of a group obtained from the remote resource that this private endpoint should connect to. - GroupID *string `json:"groupId,omitempty"` - // MemberName - The member name of a group obtained from the remote resource that this private endpoint should connect to. - MemberName *string `json:"memberName,omitempty"` - // PrivateIPAddress - A private ip address obtained from the private endpoint's subnet. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` -} - -// PrivateEndpointListResult response for the ListPrivateEndpoints API service call. -type PrivateEndpointListResult struct { - autorest.Response `json:"-"` - // Value - A list of private endpoint resources in a resource group. - Value *[]PrivateEndpoint `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateEndpointListResult. -func (pelr PrivateEndpointListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pelr.Value != nil { - objectMap["value"] = pelr.Value - } - return json.Marshal(objectMap) -} - -// PrivateEndpointListResultIterator provides access to a complete listing of PrivateEndpoint values. -type PrivateEndpointListResultIterator struct { - i int - page PrivateEndpointListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *PrivateEndpointListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PrivateEndpointListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PrivateEndpointListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter PrivateEndpointListResultIterator) Response() PrivateEndpointListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter PrivateEndpointListResultIterator) Value() PrivateEndpoint { - if !iter.page.NotDone() { - return PrivateEndpoint{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PrivateEndpointListResultIterator type. -func NewPrivateEndpointListResultIterator(page PrivateEndpointListResultPage) PrivateEndpointListResultIterator { - return PrivateEndpointListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (pelr PrivateEndpointListResult) IsEmpty() bool { - return pelr.Value == nil || len(*pelr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (pelr PrivateEndpointListResult) hasNextLink() bool { - return pelr.NextLink != nil && len(*pelr.NextLink) != 0 -} - -// privateEndpointListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (pelr PrivateEndpointListResult) privateEndpointListResultPreparer(ctx context.Context) (*http.Request, error) { - if !pelr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(pelr.NextLink))) -} - -// PrivateEndpointListResultPage contains a page of PrivateEndpoint values. -type PrivateEndpointListResultPage struct { - fn func(context.Context, PrivateEndpointListResult) (PrivateEndpointListResult, error) - pelr PrivateEndpointListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PrivateEndpointListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.pelr) - if err != nil { - return err - } - page.pelr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PrivateEndpointListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PrivateEndpointListResultPage) NotDone() bool { - return !page.pelr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PrivateEndpointListResultPage) Response() PrivateEndpointListResult { - return page.pelr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PrivateEndpointListResultPage) Values() []PrivateEndpoint { - if page.pelr.IsEmpty() { - return nil - } - return *page.pelr.Value -} - -// Creates a new instance of the PrivateEndpointListResultPage type. -func NewPrivateEndpointListResultPage(cur PrivateEndpointListResult, getNextPage func(context.Context, PrivateEndpointListResult) (PrivateEndpointListResult, error)) PrivateEndpointListResultPage { - return PrivateEndpointListResultPage{ - fn: getNextPage, - pelr: cur, - } -} - -// PrivateEndpointProperties properties of the private endpoint. -type PrivateEndpointProperties struct { - // Subnet - The ID of the subnet from which the private IP will be allocated. - Subnet *Subnet `json:"subnet,omitempty"` - // NetworkInterfaces - READ-ONLY; An array of references to the network interfaces created for this private endpoint. - NetworkInterfaces *[]Interface `json:"networkInterfaces,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the private endpoint resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // PrivateLinkServiceConnections - A grouping of information about the connection to the remote resource. - PrivateLinkServiceConnections *[]PrivateLinkServiceConnection `json:"privateLinkServiceConnections,omitempty"` - // ManualPrivateLinkServiceConnections - A grouping of information about the connection to the remote resource. Used when the network admin does not have access to approve connections to the remote resource. - ManualPrivateLinkServiceConnections *[]PrivateLinkServiceConnection `json:"manualPrivateLinkServiceConnections,omitempty"` - // CustomDNSConfigs - An array of custom dns configurations. - CustomDNSConfigs *[]CustomDNSConfigPropertiesFormat `json:"customDnsConfigs,omitempty"` - // ApplicationSecurityGroups - Application security groups in which the private endpoint IP configuration is included. - ApplicationSecurityGroups *[]ApplicationSecurityGroup `json:"applicationSecurityGroups,omitempty"` - // IPConfigurations - A list of IP configurations of the private endpoint. This will be used to map to the First Party Service's endpoints. - IPConfigurations *[]PrivateEndpointIPConfiguration `json:"ipConfigurations,omitempty"` - // CustomNetworkInterfaceName - The custom name of the network interface attached to the private endpoint. - CustomNetworkInterfaceName *string `json:"customNetworkInterfaceName,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateEndpointProperties. -func (pep PrivateEndpointProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pep.Subnet != nil { - objectMap["subnet"] = pep.Subnet - } - if pep.PrivateLinkServiceConnections != nil { - objectMap["privateLinkServiceConnections"] = pep.PrivateLinkServiceConnections - } - if pep.ManualPrivateLinkServiceConnections != nil { - objectMap["manualPrivateLinkServiceConnections"] = pep.ManualPrivateLinkServiceConnections - } - if pep.CustomDNSConfigs != nil { - objectMap["customDnsConfigs"] = pep.CustomDNSConfigs - } - if pep.ApplicationSecurityGroups != nil { - objectMap["applicationSecurityGroups"] = pep.ApplicationSecurityGroups - } - if pep.IPConfigurations != nil { - objectMap["ipConfigurations"] = pep.IPConfigurations - } - if pep.CustomNetworkInterfaceName != nil { - objectMap["customNetworkInterfaceName"] = pep.CustomNetworkInterfaceName - } - return json.Marshal(objectMap) -} - -// PrivateEndpointsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PrivateEndpointsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PrivateEndpointsClient) (PrivateEndpoint, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PrivateEndpointsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PrivateEndpointsCreateOrUpdateFuture.Result. -func (future *PrivateEndpointsCreateOrUpdateFuture) result(client PrivateEndpointsClient) (peVar PrivateEndpoint, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - peVar.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PrivateEndpointsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if peVar.Response.Response, err = future.GetResult(sender); err == nil && peVar.Response.Response.StatusCode != http.StatusNoContent { - peVar, err = client.CreateOrUpdateResponder(peVar.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsCreateOrUpdateFuture", "Result", peVar.Response.Response, "Failure responding to request") - } - } - return -} - -// PrivateEndpointsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PrivateEndpointsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PrivateEndpointsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PrivateEndpointsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PrivateEndpointsDeleteFuture.Result. -func (future *PrivateEndpointsDeleteFuture) result(client PrivateEndpointsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PrivateEndpointsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// PrivateLinkService private link service resource. -type PrivateLinkService struct { - autorest.Response `json:"-"` - // ExtendedLocation - The extended location of the load balancer. - ExtendedLocation *ExtendedLocation `json:"extendedLocation,omitempty"` - // PrivateLinkServiceProperties - Properties of the private link service. - *PrivateLinkServiceProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for PrivateLinkService. -func (pls PrivateLinkService) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pls.ExtendedLocation != nil { - objectMap["extendedLocation"] = pls.ExtendedLocation - } - if pls.PrivateLinkServiceProperties != nil { - objectMap["properties"] = pls.PrivateLinkServiceProperties - } - if pls.ID != nil { - objectMap["id"] = pls.ID - } - if pls.Location != nil { - objectMap["location"] = pls.Location - } - if pls.Tags != nil { - objectMap["tags"] = pls.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PrivateLinkService struct. -func (pls *PrivateLinkService) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "extendedLocation": - if v != nil { - var extendedLocation ExtendedLocation - err = json.Unmarshal(*v, &extendedLocation) - if err != nil { - return err - } - pls.ExtendedLocation = &extendedLocation - } - case "properties": - if v != nil { - var privateLinkServiceProperties PrivateLinkServiceProperties - err = json.Unmarshal(*v, &privateLinkServiceProperties) - if err != nil { - return err - } - pls.PrivateLinkServiceProperties = &privateLinkServiceProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pls.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pls.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pls.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - pls.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - pls.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - pls.Tags = tags - } - } - } - - return nil -} - -// PrivateLinkServiceConnection privateLinkServiceConnection resource. -type PrivateLinkServiceConnection struct { - // PrivateLinkServiceConnectionProperties - Properties of the private link service connection. - *PrivateLinkServiceConnectionProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; The resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateLinkServiceConnection. -func (plsc PrivateLinkServiceConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if plsc.PrivateLinkServiceConnectionProperties != nil { - objectMap["properties"] = plsc.PrivateLinkServiceConnectionProperties - } - if plsc.Name != nil { - objectMap["name"] = plsc.Name - } - if plsc.ID != nil { - objectMap["id"] = plsc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PrivateLinkServiceConnection struct. -func (plsc *PrivateLinkServiceConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var privateLinkServiceConnectionProperties PrivateLinkServiceConnectionProperties - err = json.Unmarshal(*v, &privateLinkServiceConnectionProperties) - if err != nil { - return err - } - plsc.PrivateLinkServiceConnectionProperties = &privateLinkServiceConnectionProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - plsc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - plsc.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - plsc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - plsc.ID = &ID - } - } - } - - return nil -} - -// PrivateLinkServiceConnectionProperties properties of the PrivateLinkServiceConnection. -type PrivateLinkServiceConnectionProperties struct { - // ProvisioningState - READ-ONLY; The provisioning state of the private link service connection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // PrivateLinkServiceID - The resource id of private link service. - PrivateLinkServiceID *string `json:"privateLinkServiceId,omitempty"` - // GroupIds - The ID(s) of the group(s) obtained from the remote resource that this private endpoint should connect to. - GroupIds *[]string `json:"groupIds,omitempty"` - // RequestMessage - A message passed to the owner of the remote resource with this connection request. Restricted to 140 chars. - RequestMessage *string `json:"requestMessage,omitempty"` - // PrivateLinkServiceConnectionState - A collection of read-only information about the state of the connection to the remote resource. - PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState `json:"privateLinkServiceConnectionState,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateLinkServiceConnectionProperties. -func (plscp PrivateLinkServiceConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if plscp.PrivateLinkServiceID != nil { - objectMap["privateLinkServiceId"] = plscp.PrivateLinkServiceID - } - if plscp.GroupIds != nil { - objectMap["groupIds"] = plscp.GroupIds - } - if plscp.RequestMessage != nil { - objectMap["requestMessage"] = plscp.RequestMessage - } - if plscp.PrivateLinkServiceConnectionState != nil { - objectMap["privateLinkServiceConnectionState"] = plscp.PrivateLinkServiceConnectionState - } - return json.Marshal(objectMap) -} - -// PrivateLinkServiceConnectionState a collection of information about the state of the connection between -// service consumer and provider. -type PrivateLinkServiceConnectionState struct { - // Status - Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. - Status *string `json:"status,omitempty"` - // Description - The reason for approval/rejection of the connection. - Description *string `json:"description,omitempty"` - // ActionsRequired - A message indicating if changes on the service provider require any updates on the consumer. - ActionsRequired *string `json:"actionsRequired,omitempty"` -} - -// PrivateLinkServiceIPConfiguration the private link service ip configuration. -type PrivateLinkServiceIPConfiguration struct { - // PrivateLinkServiceIPConfigurationProperties - Properties of the private link service ip configuration. - *PrivateLinkServiceIPConfigurationProperties `json:"properties,omitempty"` - // Name - The name of private link service ip configuration. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; The resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateLinkServiceIPConfiguration. -func (plsic PrivateLinkServiceIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if plsic.PrivateLinkServiceIPConfigurationProperties != nil { - objectMap["properties"] = plsic.PrivateLinkServiceIPConfigurationProperties - } - if plsic.Name != nil { - objectMap["name"] = plsic.Name - } - if plsic.ID != nil { - objectMap["id"] = plsic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PrivateLinkServiceIPConfiguration struct. -func (plsic *PrivateLinkServiceIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var privateLinkServiceIPConfigurationProperties PrivateLinkServiceIPConfigurationProperties - err = json.Unmarshal(*v, &privateLinkServiceIPConfigurationProperties) - if err != nil { - return err - } - plsic.PrivateLinkServiceIPConfigurationProperties = &privateLinkServiceIPConfigurationProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - plsic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - plsic.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - plsic.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - plsic.ID = &ID - } - } - } - - return nil -} - -// PrivateLinkServiceIPConfigurationProperties properties of private link service IP configuration. -type PrivateLinkServiceIPConfigurationProperties struct { - // PrivateIPAddress - The private IP address of the IP configuration. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // PrivateIPAllocationMethod - The private IP address allocation method. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` - // Subnet - The reference to the subnet resource. - Subnet *Subnet `json:"subnet,omitempty"` - // Primary - Whether the ip configuration is primary or not. - Primary *bool `json:"primary,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the private link service IP configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // PrivateIPAddressVersion - Whether the specific IP configuration is IPv4 or IPv6. Default is IPv4. Possible values include: 'IPv4', 'IPv6' - PrivateIPAddressVersion IPVersion `json:"privateIPAddressVersion,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateLinkServiceIPConfigurationProperties. -func (plsicp PrivateLinkServiceIPConfigurationProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if plsicp.PrivateIPAddress != nil { - objectMap["privateIPAddress"] = plsicp.PrivateIPAddress - } - if plsicp.PrivateIPAllocationMethod != "" { - objectMap["privateIPAllocationMethod"] = plsicp.PrivateIPAllocationMethod - } - if plsicp.Subnet != nil { - objectMap["subnet"] = plsicp.Subnet - } - if plsicp.Primary != nil { - objectMap["primary"] = plsicp.Primary - } - if plsicp.PrivateIPAddressVersion != "" { - objectMap["privateIPAddressVersion"] = plsicp.PrivateIPAddressVersion - } - return json.Marshal(objectMap) -} - -// PrivateLinkServiceListResult response for the ListPrivateLinkService API service call. -type PrivateLinkServiceListResult struct { - autorest.Response `json:"-"` - // Value - A list of PrivateLinkService resources in a resource group. - Value *[]PrivateLinkService `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateLinkServiceListResult. -func (plslr PrivateLinkServiceListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if plslr.Value != nil { - objectMap["value"] = plslr.Value - } - return json.Marshal(objectMap) -} - -// PrivateLinkServiceListResultIterator provides access to a complete listing of PrivateLinkService values. -type PrivateLinkServiceListResultIterator struct { - i int - page PrivateLinkServiceListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *PrivateLinkServiceListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServiceListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PrivateLinkServiceListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PrivateLinkServiceListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter PrivateLinkServiceListResultIterator) Response() PrivateLinkServiceListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter PrivateLinkServiceListResultIterator) Value() PrivateLinkService { - if !iter.page.NotDone() { - return PrivateLinkService{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PrivateLinkServiceListResultIterator type. -func NewPrivateLinkServiceListResultIterator(page PrivateLinkServiceListResultPage) PrivateLinkServiceListResultIterator { - return PrivateLinkServiceListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (plslr PrivateLinkServiceListResult) IsEmpty() bool { - return plslr.Value == nil || len(*plslr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (plslr PrivateLinkServiceListResult) hasNextLink() bool { - return plslr.NextLink != nil && len(*plslr.NextLink) != 0 -} - -// privateLinkServiceListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (plslr PrivateLinkServiceListResult) privateLinkServiceListResultPreparer(ctx context.Context) (*http.Request, error) { - if !plslr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(plslr.NextLink))) -} - -// PrivateLinkServiceListResultPage contains a page of PrivateLinkService values. -type PrivateLinkServiceListResultPage struct { - fn func(context.Context, PrivateLinkServiceListResult) (PrivateLinkServiceListResult, error) - plslr PrivateLinkServiceListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PrivateLinkServiceListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServiceListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.plslr) - if err != nil { - return err - } - page.plslr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PrivateLinkServiceListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PrivateLinkServiceListResultPage) NotDone() bool { - return !page.plslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PrivateLinkServiceListResultPage) Response() PrivateLinkServiceListResult { - return page.plslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PrivateLinkServiceListResultPage) Values() []PrivateLinkService { - if page.plslr.IsEmpty() { - return nil - } - return *page.plslr.Value -} - -// Creates a new instance of the PrivateLinkServiceListResultPage type. -func NewPrivateLinkServiceListResultPage(cur PrivateLinkServiceListResult, getNextPage func(context.Context, PrivateLinkServiceListResult) (PrivateLinkServiceListResult, error)) PrivateLinkServiceListResultPage { - return PrivateLinkServiceListResultPage{ - fn: getNextPage, - plslr: cur, - } -} - -// PrivateLinkServiceProperties properties of the private link service. -type PrivateLinkServiceProperties struct { - // LoadBalancerFrontendIPConfigurations - An array of references to the load balancer IP configurations. - LoadBalancerFrontendIPConfigurations *[]FrontendIPConfiguration `json:"loadBalancerFrontendIpConfigurations,omitempty"` - // IPConfigurations - An array of private link service IP configurations. - IPConfigurations *[]PrivateLinkServiceIPConfiguration `json:"ipConfigurations,omitempty"` - // NetworkInterfaces - READ-ONLY; An array of references to the network interfaces created for this private link service. - NetworkInterfaces *[]Interface `json:"networkInterfaces,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the private link service resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // PrivateEndpointConnections - READ-ONLY; An array of list about connections to the private endpoint. - PrivateEndpointConnections *[]PrivateEndpointConnection `json:"privateEndpointConnections,omitempty"` - // Visibility - The visibility list of the private link service. - Visibility *PrivateLinkServicePropertiesVisibility `json:"visibility,omitempty"` - // AutoApproval - The auto-approval list of the private link service. - AutoApproval *PrivateLinkServicePropertiesAutoApproval `json:"autoApproval,omitempty"` - // Fqdns - The list of Fqdn. - Fqdns *[]string `json:"fqdns,omitempty"` - // Alias - READ-ONLY; The alias of the private link service. - Alias *string `json:"alias,omitempty"` - // EnableProxyProtocol - Whether the private link service is enabled for proxy protocol or not. - EnableProxyProtocol *bool `json:"enableProxyProtocol,omitempty"` -} - -// MarshalJSON is the custom marshaler for PrivateLinkServiceProperties. -func (plsp PrivateLinkServiceProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if plsp.LoadBalancerFrontendIPConfigurations != nil { - objectMap["loadBalancerFrontendIpConfigurations"] = plsp.LoadBalancerFrontendIPConfigurations - } - if plsp.IPConfigurations != nil { - objectMap["ipConfigurations"] = plsp.IPConfigurations - } - if plsp.Visibility != nil { - objectMap["visibility"] = plsp.Visibility - } - if plsp.AutoApproval != nil { - objectMap["autoApproval"] = plsp.AutoApproval - } - if plsp.Fqdns != nil { - objectMap["fqdns"] = plsp.Fqdns - } - if plsp.EnableProxyProtocol != nil { - objectMap["enableProxyProtocol"] = plsp.EnableProxyProtocol - } - return json.Marshal(objectMap) -} - -// PrivateLinkServicePropertiesAutoApproval the auto-approval list of the private link service. -type PrivateLinkServicePropertiesAutoApproval struct { - // Subscriptions - The list of subscriptions. - Subscriptions *[]string `json:"subscriptions,omitempty"` -} - -// PrivateLinkServicePropertiesVisibility the visibility list of the private link service. -type PrivateLinkServicePropertiesVisibility struct { - // Subscriptions - The list of subscriptions. - Subscriptions *[]string `json:"subscriptions,omitempty"` -} - -// PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupFuture an abstraction for monitoring -// and retrieving the results of a long-running operation. -type PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PrivateLinkServicesClient) (PrivateLinkServiceVisibility, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupFuture.Result. -func (future *PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupFuture) result(client PrivateLinkServicesClient) (plsv PrivateLinkServiceVisibility, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - plsv.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if plsv.Response.Response, err = future.GetResult(sender); err == nil && plsv.Response.Response.StatusCode != http.StatusNoContent { - plsv, err = client.CheckPrivateLinkServiceVisibilityByResourceGroupResponder(plsv.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupFuture", "Result", plsv.Response.Response, "Failure responding to request") - } - } - return -} - -// PrivateLinkServicesCheckPrivateLinkServiceVisibilityFuture an abstraction for monitoring and retrieving -// the results of a long-running operation. -type PrivateLinkServicesCheckPrivateLinkServiceVisibilityFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PrivateLinkServicesClient) (PrivateLinkServiceVisibility, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PrivateLinkServicesCheckPrivateLinkServiceVisibilityFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PrivateLinkServicesCheckPrivateLinkServiceVisibilityFuture.Result. -func (future *PrivateLinkServicesCheckPrivateLinkServiceVisibilityFuture) result(client PrivateLinkServicesClient) (plsv PrivateLinkServiceVisibility, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesCheckPrivateLinkServiceVisibilityFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - plsv.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PrivateLinkServicesCheckPrivateLinkServiceVisibilityFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if plsv.Response.Response, err = future.GetResult(sender); err == nil && plsv.Response.Response.StatusCode != http.StatusNoContent { - plsv, err = client.CheckPrivateLinkServiceVisibilityResponder(plsv.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesCheckPrivateLinkServiceVisibilityFuture", "Result", plsv.Response.Response, "Failure responding to request") - } - } - return -} - -// PrivateLinkServicesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PrivateLinkServicesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PrivateLinkServicesClient) (PrivateLinkService, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PrivateLinkServicesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PrivateLinkServicesCreateOrUpdateFuture.Result. -func (future *PrivateLinkServicesCreateOrUpdateFuture) result(client PrivateLinkServicesClient) (pls PrivateLinkService, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pls.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PrivateLinkServicesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pls.Response.Response, err = future.GetResult(sender); err == nil && pls.Response.Response.StatusCode != http.StatusNoContent { - pls, err = client.CreateOrUpdateResponder(pls.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesCreateOrUpdateFuture", "Result", pls.Response.Response, "Failure responding to request") - } - } - return -} - -// PrivateLinkServicesDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PrivateLinkServicesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PrivateLinkServicesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PrivateLinkServicesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PrivateLinkServicesDeleteFuture.Result. -func (future *PrivateLinkServicesDeleteFuture) result(client PrivateLinkServicesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PrivateLinkServicesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// PrivateLinkServicesDeletePrivateEndpointConnectionFuture an abstraction for monitoring and retrieving -// the results of a long-running operation. -type PrivateLinkServicesDeletePrivateEndpointConnectionFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PrivateLinkServicesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PrivateLinkServicesDeletePrivateEndpointConnectionFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PrivateLinkServicesDeletePrivateEndpointConnectionFuture.Result. -func (future *PrivateLinkServicesDeletePrivateEndpointConnectionFuture) result(client PrivateLinkServicesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesDeletePrivateEndpointConnectionFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PrivateLinkServicesDeletePrivateEndpointConnectionFuture") - return - } - ar.Response = future.Response() - return -} - -// PrivateLinkServiceVisibility response for the CheckPrivateLinkServiceVisibility API service call. -type PrivateLinkServiceVisibility struct { - autorest.Response `json:"-"` - // Visible - Private Link Service Visibility (True/False). - Visible *bool `json:"visible,omitempty"` -} - -// Probe a load balancer probe. -type Probe struct { - autorest.Response `json:"-"` - // ProbePropertiesFormat - Properties of load balancer probe. - *ProbePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within the set of probes used by the load balancer. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for Probe. -func (p Probe) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if p.ProbePropertiesFormat != nil { - objectMap["properties"] = p.ProbePropertiesFormat - } - if p.Name != nil { - objectMap["name"] = p.Name - } - if p.ID != nil { - objectMap["id"] = p.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Probe struct. -func (p *Probe) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var probePropertiesFormat ProbePropertiesFormat - err = json.Unmarshal(*v, &probePropertiesFormat) - if err != nil { - return err - } - p.ProbePropertiesFormat = &probePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - p.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - p.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - p.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - p.ID = &ID - } - } - } - - return nil -} - -// ProbePropertiesFormat load balancer probe resource. -type ProbePropertiesFormat struct { - // LoadBalancingRules - READ-ONLY; The load balancer rules that use this probe. - LoadBalancingRules *[]SubResource `json:"loadBalancingRules,omitempty"` - // Protocol - The protocol of the end point. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' or 'Https' is specified, a 200 OK response from the specifies URI is required for the probe to be successful. Possible values include: 'ProbeProtocolHTTP', 'ProbeProtocolTCP', 'ProbeProtocolHTTPS' - Protocol ProbeProtocol `json:"protocol,omitempty"` - // Port - The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - Port *int32 `json:"port,omitempty"` - // IntervalInSeconds - The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - IntervalInSeconds *int32 `json:"intervalInSeconds,omitempty"` - // NumberOfProbes - The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - NumberOfProbes *int32 `json:"numberOfProbes,omitempty"` - // ProbeThreshold - The number of consecutive successful or failed probes in order to allow or deny traffic from being delivered to this endpoint. After failing the number of consecutive probes equal to this value, the endpoint will be taken out of rotation and require the same number of successful consecutive probes to be placed back in rotation. - ProbeThreshold *int32 `json:"probeThreshold,omitempty"` - // RequestPath - The URI used for requesting health status from the VM. Path is required if a protocol is set to http. Otherwise, it is not allowed. There is no default value. - RequestPath *string `json:"requestPath,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the probe resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ProbePropertiesFormat. -func (ppf ProbePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ppf.Protocol != "" { - objectMap["protocol"] = ppf.Protocol - } - if ppf.Port != nil { - objectMap["port"] = ppf.Port - } - if ppf.IntervalInSeconds != nil { - objectMap["intervalInSeconds"] = ppf.IntervalInSeconds - } - if ppf.NumberOfProbes != nil { - objectMap["numberOfProbes"] = ppf.NumberOfProbes - } - if ppf.ProbeThreshold != nil { - objectMap["probeThreshold"] = ppf.ProbeThreshold - } - if ppf.RequestPath != nil { - objectMap["requestPath"] = ppf.RequestPath - } - return json.Marshal(objectMap) -} - -// Profile network profile resource. -type Profile struct { - autorest.Response `json:"-"` - // ProfilePropertiesFormat - Network profile properties. - *ProfilePropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Profile. -func (p Profile) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if p.ProfilePropertiesFormat != nil { - objectMap["properties"] = p.ProfilePropertiesFormat - } - if p.ID != nil { - objectMap["id"] = p.ID - } - if p.Location != nil { - objectMap["location"] = p.Location - } - if p.Tags != nil { - objectMap["tags"] = p.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Profile struct. -func (p *Profile) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var profilePropertiesFormat ProfilePropertiesFormat - err = json.Unmarshal(*v, &profilePropertiesFormat) - if err != nil { - return err - } - p.ProfilePropertiesFormat = &profilePropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - p.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - p.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - p.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - p.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - p.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - p.Tags = tags - } - } - } - - return nil -} - -// ProfileListResult response for ListNetworkProfiles API service call. -type ProfileListResult struct { - autorest.Response `json:"-"` - // Value - A list of network profiles that exist in a resource group. - Value *[]Profile `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ProfileListResultIterator provides access to a complete listing of Profile values. -type ProfileListResultIterator struct { - i int - page ProfileListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ProfileListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfileListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ProfileListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ProfileListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ProfileListResultIterator) Response() ProfileListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ProfileListResultIterator) Value() Profile { - if !iter.page.NotDone() { - return Profile{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ProfileListResultIterator type. -func NewProfileListResultIterator(page ProfileListResultPage) ProfileListResultIterator { - return ProfileListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (plr ProfileListResult) IsEmpty() bool { - return plr.Value == nil || len(*plr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (plr ProfileListResult) hasNextLink() bool { - return plr.NextLink != nil && len(*plr.NextLink) != 0 -} - -// profileListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (plr ProfileListResult) profileListResultPreparer(ctx context.Context) (*http.Request, error) { - if !plr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(plr.NextLink))) -} - -// ProfileListResultPage contains a page of Profile values. -type ProfileListResultPage struct { - fn func(context.Context, ProfileListResult) (ProfileListResult, error) - plr ProfileListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ProfileListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfileListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.plr) - if err != nil { - return err - } - page.plr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ProfileListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ProfileListResultPage) NotDone() bool { - return !page.plr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ProfileListResultPage) Response() ProfileListResult { - return page.plr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ProfileListResultPage) Values() []Profile { - if page.plr.IsEmpty() { - return nil - } - return *page.plr.Value -} - -// Creates a new instance of the ProfileListResultPage type. -func NewProfileListResultPage(cur ProfileListResult, getNextPage func(context.Context, ProfileListResult) (ProfileListResult, error)) ProfileListResultPage { - return ProfileListResultPage{ - fn: getNextPage, - plr: cur, - } -} - -// ProfilePropertiesFormat network profile properties. -type ProfilePropertiesFormat struct { - // ContainerNetworkInterfaces - READ-ONLY; List of child container network interfaces. - ContainerNetworkInterfaces *[]ContainerNetworkInterface `json:"containerNetworkInterfaces,omitempty"` - // ContainerNetworkInterfaceConfigurations - List of chid container network interface configurations. - ContainerNetworkInterfaceConfigurations *[]ContainerNetworkInterfaceConfiguration `json:"containerNetworkInterfaceConfigurations,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the network profile resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the network profile resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ProfilePropertiesFormat. -func (ppf ProfilePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ppf.ContainerNetworkInterfaceConfigurations != nil { - objectMap["containerNetworkInterfaceConfigurations"] = ppf.ContainerNetworkInterfaceConfigurations - } - return json.Marshal(objectMap) -} - -// ProfilesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type ProfilesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ProfilesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ProfilesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ProfilesDeleteFuture.Result. -func (future *ProfilesDeleteFuture) result(client ProfilesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ProfilesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// PropagatedRouteTable the list of RouteTables to advertise the routes to. -type PropagatedRouteTable struct { - // Labels - The list of labels. - Labels *[]string `json:"labels,omitempty"` - // Ids - The list of resource ids of all the RouteTables. - Ids *[]SubResource `json:"ids,omitempty"` -} - -// ProtocolConfiguration configuration of the protocol. -type ProtocolConfiguration struct { - // HTTPConfiguration - HTTP configuration of the connectivity check. - HTTPConfiguration *HTTPConfiguration `json:"HTTPConfiguration,omitempty"` -} - -// PublicIPAddress public IP address resource. -type PublicIPAddress struct { - autorest.Response `json:"-"` - // ExtendedLocation - The extended location of the public ip address. - ExtendedLocation *ExtendedLocation `json:"extendedLocation,omitempty"` - // Sku - The public IP address SKU. - Sku *PublicIPAddressSku `json:"sku,omitempty"` - // PublicIPAddressPropertiesFormat - Public IP address properties. - *PublicIPAddressPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Zones - A list of availability zones denoting the IP allocated for the resource needs to come from. - Zones *[]string `json:"zones,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for PublicIPAddress. -func (pia PublicIPAddress) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pia.ExtendedLocation != nil { - objectMap["extendedLocation"] = pia.ExtendedLocation - } - if pia.Sku != nil { - objectMap["sku"] = pia.Sku - } - if pia.PublicIPAddressPropertiesFormat != nil { - objectMap["properties"] = pia.PublicIPAddressPropertiesFormat - } - if pia.Zones != nil { - objectMap["zones"] = pia.Zones - } - if pia.ID != nil { - objectMap["id"] = pia.ID - } - if pia.Location != nil { - objectMap["location"] = pia.Location - } - if pia.Tags != nil { - objectMap["tags"] = pia.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PublicIPAddress struct. -func (pia *PublicIPAddress) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "extendedLocation": - if v != nil { - var extendedLocation ExtendedLocation - err = json.Unmarshal(*v, &extendedLocation) - if err != nil { - return err - } - pia.ExtendedLocation = &extendedLocation - } - case "sku": - if v != nil { - var sku PublicIPAddressSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - pia.Sku = &sku - } - case "properties": - if v != nil { - var publicIPAddressPropertiesFormat PublicIPAddressPropertiesFormat - err = json.Unmarshal(*v, &publicIPAddressPropertiesFormat) - if err != nil { - return err - } - pia.PublicIPAddressPropertiesFormat = &publicIPAddressPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pia.Etag = &etag - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - pia.Zones = &zones - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pia.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pia.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - pia.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - pia.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - pia.Tags = tags - } - } - } - - return nil -} - -// PublicIPAddressDNSSettings contains FQDN of the DNS record associated with the public IP address. -type PublicIPAddressDNSSettings struct { - // DomainNameLabel - The domain name label. The concatenation of the domain name label and the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. - DomainNameLabel *string `json:"domainNameLabel,omitempty"` - // Fqdn - The Fully Qualified Domain Name of the A DNS record associated with the public IP. This is the concatenation of the domainNameLabel and the regionalized DNS zone. - Fqdn *string `json:"fqdn,omitempty"` - // ReverseFqdn - The reverse FQDN. A user-visible, fully qualified domain name that resolves to this public IP address. If the reverseFqdn is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. - ReverseFqdn *string `json:"reverseFqdn,omitempty"` -} - -// PublicIPAddressesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PublicIPAddressesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PublicIPAddressesClient) (PublicIPAddress, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PublicIPAddressesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PublicIPAddressesCreateOrUpdateFuture.Result. -func (future *PublicIPAddressesCreateOrUpdateFuture) result(client PublicIPAddressesClient) (pia PublicIPAddress, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pia.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PublicIPAddressesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pia.Response.Response, err = future.GetResult(sender); err == nil && pia.Response.Response.StatusCode != http.StatusNoContent { - pia, err = client.CreateOrUpdateResponder(pia.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesCreateOrUpdateFuture", "Result", pia.Response.Response, "Failure responding to request") - } - } - return -} - -// PublicIPAddressesDdosProtectionStatusFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type PublicIPAddressesDdosProtectionStatusFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PublicIPAddressesClient) (PublicIPDdosProtectionStatusResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PublicIPAddressesDdosProtectionStatusFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PublicIPAddressesDdosProtectionStatusFuture.Result. -func (future *PublicIPAddressesDdosProtectionStatusFuture) result(client PublicIPAddressesClient) (pidpsr PublicIPDdosProtectionStatusResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesDdosProtectionStatusFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pidpsr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PublicIPAddressesDdosProtectionStatusFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pidpsr.Response.Response, err = future.GetResult(sender); err == nil && pidpsr.Response.Response.StatusCode != http.StatusNoContent { - pidpsr, err = client.DdosProtectionStatusResponder(pidpsr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesDdosProtectionStatusFuture", "Result", pidpsr.Response.Response, "Failure responding to request") - } - } - return -} - -// PublicIPAddressesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PublicIPAddressesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PublicIPAddressesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PublicIPAddressesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PublicIPAddressesDeleteFuture.Result. -func (future *PublicIPAddressesDeleteFuture) result(client PublicIPAddressesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PublicIPAddressesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// PublicIPAddressListResult response for ListPublicIpAddresses API service call. -type PublicIPAddressListResult struct { - autorest.Response `json:"-"` - // Value - A list of public IP addresses that exists in a resource group. - Value *[]PublicIPAddress `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// PublicIPAddressListResultIterator provides access to a complete listing of PublicIPAddress values. -type PublicIPAddressListResultIterator struct { - i int - page PublicIPAddressListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *PublicIPAddressListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PublicIPAddressListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PublicIPAddressListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter PublicIPAddressListResultIterator) Response() PublicIPAddressListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter PublicIPAddressListResultIterator) Value() PublicIPAddress { - if !iter.page.NotDone() { - return PublicIPAddress{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PublicIPAddressListResultIterator type. -func NewPublicIPAddressListResultIterator(page PublicIPAddressListResultPage) PublicIPAddressListResultIterator { - return PublicIPAddressListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (pialr PublicIPAddressListResult) IsEmpty() bool { - return pialr.Value == nil || len(*pialr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (pialr PublicIPAddressListResult) hasNextLink() bool { - return pialr.NextLink != nil && len(*pialr.NextLink) != 0 -} - -// publicIPAddressListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (pialr PublicIPAddressListResult) publicIPAddressListResultPreparer(ctx context.Context) (*http.Request, error) { - if !pialr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(pialr.NextLink))) -} - -// PublicIPAddressListResultPage contains a page of PublicIPAddress values. -type PublicIPAddressListResultPage struct { - fn func(context.Context, PublicIPAddressListResult) (PublicIPAddressListResult, error) - pialr PublicIPAddressListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PublicIPAddressListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.pialr) - if err != nil { - return err - } - page.pialr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PublicIPAddressListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PublicIPAddressListResultPage) NotDone() bool { - return !page.pialr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PublicIPAddressListResultPage) Response() PublicIPAddressListResult { - return page.pialr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PublicIPAddressListResultPage) Values() []PublicIPAddress { - if page.pialr.IsEmpty() { - return nil - } - return *page.pialr.Value -} - -// Creates a new instance of the PublicIPAddressListResultPage type. -func NewPublicIPAddressListResultPage(cur PublicIPAddressListResult, getNextPage func(context.Context, PublicIPAddressListResult) (PublicIPAddressListResult, error)) PublicIPAddressListResultPage { - return PublicIPAddressListResultPage{ - fn: getNextPage, - pialr: cur, - } -} - -// PublicIPAddressPropertiesFormat public IP address properties. -type PublicIPAddressPropertiesFormat struct { - // PublicIPAllocationMethod - The public IP address allocation method. Possible values include: 'Static', 'Dynamic' - PublicIPAllocationMethod IPAllocationMethod `json:"publicIPAllocationMethod,omitempty"` - // PublicIPAddressVersion - The public IP address version. Possible values include: 'IPv4', 'IPv6' - PublicIPAddressVersion IPVersion `json:"publicIPAddressVersion,omitempty"` - // IPConfiguration - READ-ONLY; The IP configuration associated with the public IP address. - IPConfiguration *IPConfiguration `json:"ipConfiguration,omitempty"` - // DNSSettings - The FQDN of the DNS record associated with the public IP address. - DNSSettings *PublicIPAddressDNSSettings `json:"dnsSettings,omitempty"` - // DdosSettings - The DDoS protection custom policy associated with the public IP address. - DdosSettings *DdosSettings `json:"ddosSettings,omitempty"` - // IPTags - The list of tags associated with the public IP address. - IPTags *[]IPTag `json:"ipTags,omitempty"` - // IPAddress - The IP address associated with the public IP address resource. - IPAddress *string `json:"ipAddress,omitempty"` - // PublicIPPrefix - The Public IP Prefix this Public IP Address should be allocated from. - PublicIPPrefix *SubResource `json:"publicIPPrefix,omitempty"` - // IdleTimeoutInMinutes - The idle timeout of the public IP address. - IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the public IP address resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the public IP address resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ServicePublicIPAddress - The service public IP address of the public IP address resource. - ServicePublicIPAddress *PublicIPAddress `json:"servicePublicIPAddress,omitempty"` - // NatGateway - The NatGateway for the Public IP address. - NatGateway *NatGateway `json:"natGateway,omitempty"` - // MigrationPhase - Migration phase of Public IP Address. Possible values include: 'PublicIPAddressMigrationPhaseNone', 'PublicIPAddressMigrationPhasePrepare', 'PublicIPAddressMigrationPhaseCommit', 'PublicIPAddressMigrationPhaseAbort', 'PublicIPAddressMigrationPhaseCommitted' - MigrationPhase PublicIPAddressMigrationPhase `json:"migrationPhase,omitempty"` - // LinkedPublicIPAddress - The linked public IP address of the public IP address resource. - LinkedPublicIPAddress *PublicIPAddress `json:"linkedPublicIPAddress,omitempty"` - // DeleteOption - Specify what happens to the public IP address when the VM using it is deleted. Possible values include: 'Delete', 'Detach' - DeleteOption DeleteOptions `json:"deleteOption,omitempty"` -} - -// MarshalJSON is the custom marshaler for PublicIPAddressPropertiesFormat. -func (piapf PublicIPAddressPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if piapf.PublicIPAllocationMethod != "" { - objectMap["publicIPAllocationMethod"] = piapf.PublicIPAllocationMethod - } - if piapf.PublicIPAddressVersion != "" { - objectMap["publicIPAddressVersion"] = piapf.PublicIPAddressVersion - } - if piapf.DNSSettings != nil { - objectMap["dnsSettings"] = piapf.DNSSettings - } - if piapf.DdosSettings != nil { - objectMap["ddosSettings"] = piapf.DdosSettings - } - if piapf.IPTags != nil { - objectMap["ipTags"] = piapf.IPTags - } - if piapf.IPAddress != nil { - objectMap["ipAddress"] = piapf.IPAddress - } - if piapf.PublicIPPrefix != nil { - objectMap["publicIPPrefix"] = piapf.PublicIPPrefix - } - if piapf.IdleTimeoutInMinutes != nil { - objectMap["idleTimeoutInMinutes"] = piapf.IdleTimeoutInMinutes - } - if piapf.ServicePublicIPAddress != nil { - objectMap["servicePublicIPAddress"] = piapf.ServicePublicIPAddress - } - if piapf.NatGateway != nil { - objectMap["natGateway"] = piapf.NatGateway - } - if piapf.MigrationPhase != "" { - objectMap["migrationPhase"] = piapf.MigrationPhase - } - if piapf.LinkedPublicIPAddress != nil { - objectMap["linkedPublicIPAddress"] = piapf.LinkedPublicIPAddress - } - if piapf.DeleteOption != "" { - objectMap["deleteOption"] = piapf.DeleteOption - } - return json.Marshal(objectMap) -} - -// PublicIPAddressSku SKU of a public IP address. -type PublicIPAddressSku struct { - // Name - Name of a public IP address SKU. Possible values include: 'PublicIPAddressSkuNameBasic', 'PublicIPAddressSkuNameStandard' - Name PublicIPAddressSkuName `json:"name,omitempty"` - // Tier - Tier of a public IP address SKU. Possible values include: 'PublicIPAddressSkuTierRegional', 'PublicIPAddressSkuTierGlobal' - Tier PublicIPAddressSkuTier `json:"tier,omitempty"` -} - -// PublicIPDdosProtectionStatusResult response for GetPublicIpAddressDdosProtectionStatusOperation API -// service call. -type PublicIPDdosProtectionStatusResult struct { - autorest.Response `json:"-"` - // PublicIPAddressID - Public IP ARM resource ID - PublicIPAddressID *string `json:"publicIpAddressId,omitempty"` - // PublicIPAddress - IP Address of the Public IP Resource - PublicIPAddress *string `json:"publicIpAddress,omitempty"` - // IsWorkloadProtected - Value indicating whether the IP address is DDoS workload protected or not. Possible values include: 'IsWorkloadProtectedFalse', 'IsWorkloadProtectedTrue' - IsWorkloadProtected IsWorkloadProtected `json:"isWorkloadProtected,omitempty"` - // DdosProtectionPlanID - DDoS protection plan Resource Id of a if IP address is protected through a plan. - DdosProtectionPlanID *string `json:"ddosProtectionPlanId,omitempty"` -} - -// PublicIPPrefix public IP prefix resource. -type PublicIPPrefix struct { - autorest.Response `json:"-"` - // ExtendedLocation - The extended location of the public ip address. - ExtendedLocation *ExtendedLocation `json:"extendedLocation,omitempty"` - // Sku - The public IP prefix SKU. - Sku *PublicIPPrefixSku `json:"sku,omitempty"` - // PublicIPPrefixPropertiesFormat - Public IP prefix properties. - *PublicIPPrefixPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Zones - A list of availability zones denoting the IP allocated for the resource needs to come from. - Zones *[]string `json:"zones,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for PublicIPPrefix. -func (pip PublicIPPrefix) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pip.ExtendedLocation != nil { - objectMap["extendedLocation"] = pip.ExtendedLocation - } - if pip.Sku != nil { - objectMap["sku"] = pip.Sku - } - if pip.PublicIPPrefixPropertiesFormat != nil { - objectMap["properties"] = pip.PublicIPPrefixPropertiesFormat - } - if pip.Zones != nil { - objectMap["zones"] = pip.Zones - } - if pip.ID != nil { - objectMap["id"] = pip.ID - } - if pip.Location != nil { - objectMap["location"] = pip.Location - } - if pip.Tags != nil { - objectMap["tags"] = pip.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for PublicIPPrefix struct. -func (pip *PublicIPPrefix) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "extendedLocation": - if v != nil { - var extendedLocation ExtendedLocation - err = json.Unmarshal(*v, &extendedLocation) - if err != nil { - return err - } - pip.ExtendedLocation = &extendedLocation - } - case "sku": - if v != nil { - var sku PublicIPPrefixSku - err = json.Unmarshal(*v, &sku) - if err != nil { - return err - } - pip.Sku = &sku - } - case "properties": - if v != nil { - var publicIPPrefixPropertiesFormat PublicIPPrefixPropertiesFormat - err = json.Unmarshal(*v, &publicIPPrefixPropertiesFormat) - if err != nil { - return err - } - pip.PublicIPPrefixPropertiesFormat = &publicIPPrefixPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - pip.Etag = &etag - } - case "zones": - if v != nil { - var zones []string - err = json.Unmarshal(*v, &zones) - if err != nil { - return err - } - pip.Zones = &zones - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - pip.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - pip.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - pip.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - pip.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - pip.Tags = tags - } - } - } - - return nil -} - -// PublicIPPrefixesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PublicIPPrefixesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PublicIPPrefixesClient) (PublicIPPrefix, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PublicIPPrefixesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PublicIPPrefixesCreateOrUpdateFuture.Result. -func (future *PublicIPPrefixesCreateOrUpdateFuture) result(client PublicIPPrefixesClient) (pip PublicIPPrefix, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - pip.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PublicIPPrefixesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if pip.Response.Response, err = future.GetResult(sender); err == nil && pip.Response.Response.StatusCode != http.StatusNoContent { - pip, err = client.CreateOrUpdateResponder(pip.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesCreateOrUpdateFuture", "Result", pip.Response.Response, "Failure responding to request") - } - } - return -} - -// PublicIPPrefixesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PublicIPPrefixesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(PublicIPPrefixesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PublicIPPrefixesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PublicIPPrefixesDeleteFuture.Result. -func (future *PublicIPPrefixesDeleteFuture) result(client PublicIPPrefixesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PublicIPPrefixesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// PublicIPPrefixListResult response for ListPublicIpPrefixes API service call. -type PublicIPPrefixListResult struct { - autorest.Response `json:"-"` - // Value - A list of public IP prefixes that exists in a resource group. - Value *[]PublicIPPrefix `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// PublicIPPrefixListResultIterator provides access to a complete listing of PublicIPPrefix values. -type PublicIPPrefixListResultIterator struct { - i int - page PublicIPPrefixListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *PublicIPPrefixListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *PublicIPPrefixListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter PublicIPPrefixListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter PublicIPPrefixListResultIterator) Response() PublicIPPrefixListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter PublicIPPrefixListResultIterator) Value() PublicIPPrefix { - if !iter.page.NotDone() { - return PublicIPPrefix{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the PublicIPPrefixListResultIterator type. -func NewPublicIPPrefixListResultIterator(page PublicIPPrefixListResultPage) PublicIPPrefixListResultIterator { - return PublicIPPrefixListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (piplr PublicIPPrefixListResult) IsEmpty() bool { - return piplr.Value == nil || len(*piplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (piplr PublicIPPrefixListResult) hasNextLink() bool { - return piplr.NextLink != nil && len(*piplr.NextLink) != 0 -} - -// publicIPPrefixListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (piplr PublicIPPrefixListResult) publicIPPrefixListResultPreparer(ctx context.Context) (*http.Request, error) { - if !piplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(piplr.NextLink))) -} - -// PublicIPPrefixListResultPage contains a page of PublicIPPrefix values. -type PublicIPPrefixListResultPage struct { - fn func(context.Context, PublicIPPrefixListResult) (PublicIPPrefixListResult, error) - piplr PublicIPPrefixListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PublicIPPrefixListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.piplr) - if err != nil { - return err - } - page.piplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PublicIPPrefixListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PublicIPPrefixListResultPage) NotDone() bool { - return !page.piplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PublicIPPrefixListResultPage) Response() PublicIPPrefixListResult { - return page.piplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PublicIPPrefixListResultPage) Values() []PublicIPPrefix { - if page.piplr.IsEmpty() { - return nil - } - return *page.piplr.Value -} - -// Creates a new instance of the PublicIPPrefixListResultPage type. -func NewPublicIPPrefixListResultPage(cur PublicIPPrefixListResult, getNextPage func(context.Context, PublicIPPrefixListResult) (PublicIPPrefixListResult, error)) PublicIPPrefixListResultPage { - return PublicIPPrefixListResultPage{ - fn: getNextPage, - piplr: cur, - } -} - -// PublicIPPrefixPropertiesFormat public IP prefix properties. -type PublicIPPrefixPropertiesFormat struct { - // PublicIPAddressVersion - The public IP address version. Possible values include: 'IPv4', 'IPv6' - PublicIPAddressVersion IPVersion `json:"publicIPAddressVersion,omitempty"` - // IPTags - The list of tags associated with the public IP prefix. - IPTags *[]IPTag `json:"ipTags,omitempty"` - // PrefixLength - The Length of the Public IP Prefix. - PrefixLength *int32 `json:"prefixLength,omitempty"` - // IPPrefix - READ-ONLY; The allocated Prefix. - IPPrefix *string `json:"ipPrefix,omitempty"` - // PublicIPAddresses - READ-ONLY; The list of all referenced PublicIPAddresses. - PublicIPAddresses *[]ReferencedPublicIPAddress `json:"publicIPAddresses,omitempty"` - // LoadBalancerFrontendIPConfiguration - READ-ONLY; The reference to load balancer frontend IP configuration associated with the public IP prefix. - LoadBalancerFrontendIPConfiguration *SubResource `json:"loadBalancerFrontendIpConfiguration,omitempty"` - // CustomIPPrefix - The customIpPrefix that this prefix is associated with. - CustomIPPrefix *SubResource `json:"customIPPrefix,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the public IP prefix resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the public IP prefix resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // NatGateway - NatGateway of Public IP Prefix. - NatGateway *NatGateway `json:"natGateway,omitempty"` -} - -// MarshalJSON is the custom marshaler for PublicIPPrefixPropertiesFormat. -func (pippf PublicIPPrefixPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if pippf.PublicIPAddressVersion != "" { - objectMap["publicIPAddressVersion"] = pippf.PublicIPAddressVersion - } - if pippf.IPTags != nil { - objectMap["ipTags"] = pippf.IPTags - } - if pippf.PrefixLength != nil { - objectMap["prefixLength"] = pippf.PrefixLength - } - if pippf.CustomIPPrefix != nil { - objectMap["customIPPrefix"] = pippf.CustomIPPrefix - } - if pippf.NatGateway != nil { - objectMap["natGateway"] = pippf.NatGateway - } - return json.Marshal(objectMap) -} - -// PublicIPPrefixSku SKU of a public IP prefix. -type PublicIPPrefixSku struct { - // Name - Name of a public IP prefix SKU. Possible values include: 'PublicIPPrefixSkuNameStandard' - Name PublicIPPrefixSkuName `json:"name,omitempty"` - // Tier - Tier of a public IP prefix SKU. Possible values include: 'PublicIPPrefixSkuTierRegional', 'PublicIPPrefixSkuTierGlobal' - Tier PublicIPPrefixSkuTier `json:"tier,omitempty"` -} - -// PutBastionShareableLinkAllFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type PutBastionShareableLinkAllFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BaseClient) (BastionShareableLinkListResultPage, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PutBastionShareableLinkAllFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PutBastionShareableLinkAllFuture.Result. -func (future *PutBastionShareableLinkAllFuture) result(client BaseClient) (bsllrp BastionShareableLinkListResultPage, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PutBastionShareableLinkAllFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - bsllrp.bsllr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PutBastionShareableLinkAllFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if bsllrp.bsllr.Response.Response, err = future.GetResult(sender); err == nil && bsllrp.bsllr.Response.Response.StatusCode != http.StatusNoContent { - bsllrp, err = client.PutBastionShareableLinkResponder(bsllrp.bsllr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PutBastionShareableLinkAllFuture", "Result", bsllrp.bsllr.Response.Response, "Failure responding to request") - } - } - return -} - -// PutBastionShareableLinkFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type PutBastionShareableLinkFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(BaseClient) (BastionShareableLinkListResultPage, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *PutBastionShareableLinkFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for PutBastionShareableLinkFuture.Result. -func (future *PutBastionShareableLinkFuture) result(client BaseClient) (bsllrp BastionShareableLinkListResultPage, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PutBastionShareableLinkFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - bsllrp.bsllr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.PutBastionShareableLinkFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if bsllrp.bsllr.Response.Response, err = future.GetResult(sender); err == nil && bsllrp.bsllr.Response.Response.StatusCode != http.StatusNoContent { - bsllrp, err = client.PutBastionShareableLinkResponder(bsllrp.bsllr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PutBastionShareableLinkFuture", "Result", bsllrp.bsllr.Response.Response, "Failure responding to request") - } - } - return -} - -// QosDefinition quality of Service defines the traffic configuration between endpoints. Mandatory to have -// one marking. -type QosDefinition struct { - // Markings - List of markings to be used in the configuration. - Markings *[]int32 `json:"markings,omitempty"` - // SourceIPRanges - Source IP ranges. - SourceIPRanges *[]QosIPRange `json:"sourceIpRanges,omitempty"` - // DestinationIPRanges - Destination IP ranges. - DestinationIPRanges *[]QosIPRange `json:"destinationIpRanges,omitempty"` - // SourcePortRanges - Sources port ranges. - SourcePortRanges *[]QosPortRange `json:"sourcePortRanges,omitempty"` - // DestinationPortRanges - Destination port ranges. - DestinationPortRanges *[]QosPortRange `json:"destinationPortRanges,omitempty"` - // Protocol - RNM supported protocol types. Possible values include: 'ProtocolTypeDoNotUse', 'ProtocolTypeIcmp', 'ProtocolTypeTCP', 'ProtocolTypeUDP', 'ProtocolTypeGre', 'ProtocolTypeEsp', 'ProtocolTypeAh', 'ProtocolTypeVxlan', 'ProtocolTypeAll' - Protocol ProtocolType `json:"protocol,omitempty"` -} - -// QosIPRange qos Traffic Profiler IP Range properties. -type QosIPRange struct { - // StartIP - Start IP Address. - StartIP *string `json:"startIP,omitempty"` - // EndIP - End IP Address. - EndIP *string `json:"endIP,omitempty"` -} - -// QosPortRange qos Traffic Profiler Port range properties. -type QosPortRange struct { - // Start - Qos Port Range start. - Start *int32 `json:"start,omitempty"` - // End - Qos Port Range end. - End *int32 `json:"end,omitempty"` -} - -// QueryInboundNatRulePortMappingRequest the request for a QueryInboundNatRulePortMapping API. Either -// IpConfiguration or IpAddress should be set -type QueryInboundNatRulePortMappingRequest struct { - // IPConfiguration - NetworkInterfaceIPConfiguration set in load balancer backend address. - IPConfiguration *SubResource `json:"ipConfiguration,omitempty"` - // IPAddress - IP address set in load balancer backend address. - IPAddress *string `json:"ipAddress,omitempty"` -} - -// QueryRequestOptions query Request Options -type QueryRequestOptions struct { - // SkipToken - When present, the value can be passed to a subsequent query call (together with the same query and scopes used in the current request) to retrieve the next page of data. - SkipToken *string `json:"skipToken,omitempty"` -} - -// QueryResults query result -type QueryResults struct { - autorest.Response `json:"-"` - // MatchingRecordsCount - Number of total records matching the query. - MatchingRecordsCount *int64 `json:"matchingRecordsCount,omitempty"` - // Signatures - Array containing the results of the query - Signatures *[]SingleQueryResult `json:"signatures,omitempty"` -} - -// QueryTroubleshootingParameters parameters that define the resource to query the troubleshooting result. -type QueryTroubleshootingParameters struct { - // TargetResourceID - The target resource ID to query the troubleshooting result. - TargetResourceID *string `json:"targetResourceId,omitempty"` -} - -// RadiusServer radius Server Settings. -type RadiusServer struct { - // RadiusServerAddress - The address of this radius server. - RadiusServerAddress *string `json:"radiusServerAddress,omitempty"` - // RadiusServerScore - The initial score assigned to this radius server. - RadiusServerScore *int64 `json:"radiusServerScore,omitempty"` - // RadiusServerSecret - The secret used for this radius server. - RadiusServerSecret *string `json:"radiusServerSecret,omitempty"` -} - -// RecordSet a collective group of information about the record set information. -type RecordSet struct { - // RecordType - Resource record type. - RecordType *string `json:"recordType,omitempty"` - // RecordSetName - Recordset name. - RecordSetName *string `json:"recordSetName,omitempty"` - // Fqdn - Fqdn that resolves to private endpoint ip address. - Fqdn *string `json:"fqdn,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the recordset. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // TTL - Recordset time to live. - TTL *int32 `json:"ttl,omitempty"` - // IPAddresses - The private ip address of the private endpoint. - IPAddresses *[]string `json:"ipAddresses,omitempty"` -} - -// MarshalJSON is the custom marshaler for RecordSet. -func (rs RecordSet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rs.RecordType != nil { - objectMap["recordType"] = rs.RecordType - } - if rs.RecordSetName != nil { - objectMap["recordSetName"] = rs.RecordSetName - } - if rs.Fqdn != nil { - objectMap["fqdn"] = rs.Fqdn - } - if rs.TTL != nil { - objectMap["ttl"] = rs.TTL - } - if rs.IPAddresses != nil { - objectMap["ipAddresses"] = rs.IPAddresses - } - return json.Marshal(objectMap) -} - -// ReferencedPublicIPAddress reference to a public IP address. -type ReferencedPublicIPAddress struct { - // ID - The PublicIPAddress Reference. - ID *string `json:"id,omitempty"` -} - -// Resource common resource representation. -type Resource struct { - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Resource. -func (r Resource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if r.ID != nil { - objectMap["id"] = r.ID - } - if r.Location != nil { - objectMap["location"] = r.Location - } - if r.Tags != nil { - objectMap["tags"] = r.Tags - } - return json.Marshal(objectMap) -} - -// ResourceNavigationLink resourceNavigationLink resource. -type ResourceNavigationLink struct { - // ResourceNavigationLinkFormat - Resource navigation link properties format. - *ResourceNavigationLinkFormat `json:"properties,omitempty"` - // Name - Name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ResourceNavigationLink. -func (rnl ResourceNavigationLink) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rnl.ResourceNavigationLinkFormat != nil { - objectMap["properties"] = rnl.ResourceNavigationLinkFormat - } - if rnl.Name != nil { - objectMap["name"] = rnl.Name - } - if rnl.ID != nil { - objectMap["id"] = rnl.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ResourceNavigationLink struct. -func (rnl *ResourceNavigationLink) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var resourceNavigationLinkFormat ResourceNavigationLinkFormat - err = json.Unmarshal(*v, &resourceNavigationLinkFormat) - if err != nil { - return err - } - rnl.ResourceNavigationLinkFormat = &resourceNavigationLinkFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rnl.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - rnl.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - rnl.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rnl.ID = &ID - } - } - } - - return nil -} - -// ResourceNavigationLinkFormat properties of ResourceNavigationLink. -type ResourceNavigationLinkFormat struct { - // LinkedResourceType - Resource type of the linked resource. - LinkedResourceType *string `json:"linkedResourceType,omitempty"` - // Link - Link to the external resource. - Link *string `json:"link,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource navigation link resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ResourceNavigationLinkFormat. -func (rnlf ResourceNavigationLinkFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rnlf.LinkedResourceType != nil { - objectMap["linkedResourceType"] = rnlf.LinkedResourceType - } - if rnlf.Link != nil { - objectMap["link"] = rnlf.Link - } - return json.Marshal(objectMap) -} - -// ResourceNavigationLinksListResult response for ResourceNavigationLinks_List operation. -type ResourceNavigationLinksListResult struct { - autorest.Response `json:"-"` - // Value - The resource navigation links in a subnet. - Value *[]ResourceNavigationLink `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ResourceNavigationLinksListResult. -func (rnllr ResourceNavigationLinksListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rnllr.Value != nil { - objectMap["value"] = rnllr.Value - } - return json.Marshal(objectMap) -} - -// ResourceSet the base resource set for visibility and auto-approval. -type ResourceSet struct { - // Subscriptions - The list of subscriptions. - Subscriptions *[]string `json:"subscriptions,omitempty"` -} - -// RetentionPolicyParameters parameters that define the retention policy for flow log. -type RetentionPolicyParameters struct { - // Days - Number of days to retain flow log records. - Days *int32 `json:"days,omitempty"` - // Enabled - Flag to enable/disable retention. - Enabled *bool `json:"enabled,omitempty"` -} - -// Route route resource. -type Route struct { - autorest.Response `json:"-"` - // RoutePropertiesFormat - Properties of the route. - *RoutePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - The type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for Route. -func (r Route) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if r.RoutePropertiesFormat != nil { - objectMap["properties"] = r.RoutePropertiesFormat - } - if r.Name != nil { - objectMap["name"] = r.Name - } - if r.Type != nil { - objectMap["type"] = r.Type - } - if r.ID != nil { - objectMap["id"] = r.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Route struct. -func (r *Route) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routePropertiesFormat RoutePropertiesFormat - err = json.Unmarshal(*v, &routePropertiesFormat) - if err != nil { - return err - } - r.RoutePropertiesFormat = &routePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - r.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - r.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - r.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - r.ID = &ID - } - } - } - - return nil -} - -// RouteFilter route Filter Resource. -type RouteFilter struct { - autorest.Response `json:"-"` - // RouteFilterPropertiesFormat - Properties of the route filter. - *RouteFilterPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for RouteFilter. -func (rf RouteFilter) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rf.RouteFilterPropertiesFormat != nil { - objectMap["properties"] = rf.RouteFilterPropertiesFormat - } - if rf.ID != nil { - objectMap["id"] = rf.ID - } - if rf.Location != nil { - objectMap["location"] = rf.Location - } - if rf.Tags != nil { - objectMap["tags"] = rf.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for RouteFilter struct. -func (rf *RouteFilter) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routeFilterPropertiesFormat RouteFilterPropertiesFormat - err = json.Unmarshal(*v, &routeFilterPropertiesFormat) - if err != nil { - return err - } - rf.RouteFilterPropertiesFormat = &routeFilterPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - rf.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rf.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rf.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - rf.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - rf.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - rf.Tags = tags - } - } - } - - return nil -} - -// RouteFilterListResult response for the ListRouteFilters API service call. -type RouteFilterListResult struct { - autorest.Response `json:"-"` - // Value - A list of route filters in a resource group. - Value *[]RouteFilter `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RouteFilterListResultIterator provides access to a complete listing of RouteFilter values. -type RouteFilterListResultIterator struct { - i int - page RouteFilterListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RouteFilterListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RouteFilterListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RouteFilterListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RouteFilterListResultIterator) Response() RouteFilterListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RouteFilterListResultIterator) Value() RouteFilter { - if !iter.page.NotDone() { - return RouteFilter{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the RouteFilterListResultIterator type. -func NewRouteFilterListResultIterator(page RouteFilterListResultPage) RouteFilterListResultIterator { - return RouteFilterListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rflr RouteFilterListResult) IsEmpty() bool { - return rflr.Value == nil || len(*rflr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rflr RouteFilterListResult) hasNextLink() bool { - return rflr.NextLink != nil && len(*rflr.NextLink) != 0 -} - -// routeFilterListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rflr RouteFilterListResult) routeFilterListResultPreparer(ctx context.Context) (*http.Request, error) { - if !rflr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rflr.NextLink))) -} - -// RouteFilterListResultPage contains a page of RouteFilter values. -type RouteFilterListResultPage struct { - fn func(context.Context, RouteFilterListResult) (RouteFilterListResult, error) - rflr RouteFilterListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RouteFilterListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rflr) - if err != nil { - return err - } - page.rflr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RouteFilterListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RouteFilterListResultPage) NotDone() bool { - return !page.rflr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RouteFilterListResultPage) Response() RouteFilterListResult { - return page.rflr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RouteFilterListResultPage) Values() []RouteFilter { - if page.rflr.IsEmpty() { - return nil - } - return *page.rflr.Value -} - -// Creates a new instance of the RouteFilterListResultPage type. -func NewRouteFilterListResultPage(cur RouteFilterListResult, getNextPage func(context.Context, RouteFilterListResult) (RouteFilterListResult, error)) RouteFilterListResultPage { - return RouteFilterListResultPage{ - fn: getNextPage, - rflr: cur, - } -} - -// RouteFilterPropertiesFormat route Filter Resource. -type RouteFilterPropertiesFormat struct { - // Rules - Collection of RouteFilterRules contained within a route filter. - Rules *[]RouteFilterRule `json:"rules,omitempty"` - // Peerings - READ-ONLY; A collection of references to express route circuit peerings. - Peerings *[]ExpressRouteCircuitPeering `json:"peerings,omitempty"` - // Ipv6Peerings - READ-ONLY; A collection of references to express route circuit ipv6 peerings. - Ipv6Peerings *[]ExpressRouteCircuitPeering `json:"ipv6Peerings,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the route filter resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for RouteFilterPropertiesFormat. -func (rfpf RouteFilterPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rfpf.Rules != nil { - objectMap["rules"] = rfpf.Rules - } - return json.Marshal(objectMap) -} - -// RouteFilterRule route Filter Rule Resource. -type RouteFilterRule struct { - autorest.Response `json:"-"` - // RouteFilterRulePropertiesFormat - Properties of the route filter rule. - *RouteFilterRulePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for RouteFilterRule. -func (rfr RouteFilterRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rfr.RouteFilterRulePropertiesFormat != nil { - objectMap["properties"] = rfr.RouteFilterRulePropertiesFormat - } - if rfr.Name != nil { - objectMap["name"] = rfr.Name - } - if rfr.Location != nil { - objectMap["location"] = rfr.Location - } - if rfr.ID != nil { - objectMap["id"] = rfr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for RouteFilterRule struct. -func (rfr *RouteFilterRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routeFilterRulePropertiesFormat RouteFilterRulePropertiesFormat - err = json.Unmarshal(*v, &routeFilterRulePropertiesFormat) - if err != nil { - return err - } - rfr.RouteFilterRulePropertiesFormat = &routeFilterRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rfr.Name = &name - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - rfr.Location = &location - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - rfr.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rfr.ID = &ID - } - } - } - - return nil -} - -// RouteFilterRuleListResult response for the ListRouteFilterRules API service call. -type RouteFilterRuleListResult struct { - autorest.Response `json:"-"` - // Value - A list of RouteFilterRules in a resource group. - Value *[]RouteFilterRule `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RouteFilterRuleListResultIterator provides access to a complete listing of RouteFilterRule values. -type RouteFilterRuleListResultIterator struct { - i int - page RouteFilterRuleListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RouteFilterRuleListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRuleListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RouteFilterRuleListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RouteFilterRuleListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RouteFilterRuleListResultIterator) Response() RouteFilterRuleListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RouteFilterRuleListResultIterator) Value() RouteFilterRule { - if !iter.page.NotDone() { - return RouteFilterRule{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the RouteFilterRuleListResultIterator type. -func NewRouteFilterRuleListResultIterator(page RouteFilterRuleListResultPage) RouteFilterRuleListResultIterator { - return RouteFilterRuleListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rfrlr RouteFilterRuleListResult) IsEmpty() bool { - return rfrlr.Value == nil || len(*rfrlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rfrlr RouteFilterRuleListResult) hasNextLink() bool { - return rfrlr.NextLink != nil && len(*rfrlr.NextLink) != 0 -} - -// routeFilterRuleListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rfrlr RouteFilterRuleListResult) routeFilterRuleListResultPreparer(ctx context.Context) (*http.Request, error) { - if !rfrlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rfrlr.NextLink))) -} - -// RouteFilterRuleListResultPage contains a page of RouteFilterRule values. -type RouteFilterRuleListResultPage struct { - fn func(context.Context, RouteFilterRuleListResult) (RouteFilterRuleListResult, error) - rfrlr RouteFilterRuleListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RouteFilterRuleListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRuleListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rfrlr) - if err != nil { - return err - } - page.rfrlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RouteFilterRuleListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RouteFilterRuleListResultPage) NotDone() bool { - return !page.rfrlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RouteFilterRuleListResultPage) Response() RouteFilterRuleListResult { - return page.rfrlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RouteFilterRuleListResultPage) Values() []RouteFilterRule { - if page.rfrlr.IsEmpty() { - return nil - } - return *page.rfrlr.Value -} - -// Creates a new instance of the RouteFilterRuleListResultPage type. -func NewRouteFilterRuleListResultPage(cur RouteFilterRuleListResult, getNextPage func(context.Context, RouteFilterRuleListResult) (RouteFilterRuleListResult, error)) RouteFilterRuleListResultPage { - return RouteFilterRuleListResultPage{ - fn: getNextPage, - rfrlr: cur, - } -} - -// RouteFilterRulePropertiesFormat route Filter Rule Resource. -type RouteFilterRulePropertiesFormat struct { - // Access - The access type of the rule. Possible values include: 'Allow', 'Deny' - Access Access `json:"access,omitempty"` - // RouteFilterRuleType - The rule type of the rule. - RouteFilterRuleType *string `json:"routeFilterRuleType,omitempty"` - // Communities - The collection for bgp community values to filter on. e.g. ['12076:5010','12076:5020']. - Communities *[]string `json:"communities,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the route filter rule resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for RouteFilterRulePropertiesFormat. -func (rfrpf RouteFilterRulePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rfrpf.Access != "" { - objectMap["access"] = rfrpf.Access - } - if rfrpf.RouteFilterRuleType != nil { - objectMap["routeFilterRuleType"] = rfrpf.RouteFilterRuleType - } - if rfrpf.Communities != nil { - objectMap["communities"] = rfrpf.Communities - } - return json.Marshal(objectMap) -} - -// RouteFilterRulesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type RouteFilterRulesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteFilterRulesClient) (RouteFilterRule, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteFilterRulesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteFilterRulesCreateOrUpdateFuture.Result. -func (future *RouteFilterRulesCreateOrUpdateFuture) result(client RouteFilterRulesClient) (rfr RouteFilterRule, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - rfr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteFilterRulesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if rfr.Response.Response, err = future.GetResult(sender); err == nil && rfr.Response.Response.StatusCode != http.StatusNoContent { - rfr, err = client.CreateOrUpdateResponder(rfr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesCreateOrUpdateFuture", "Result", rfr.Response.Response, "Failure responding to request") - } - } - return -} - -// RouteFilterRulesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RouteFilterRulesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteFilterRulesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteFilterRulesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteFilterRulesDeleteFuture.Result. -func (future *RouteFilterRulesDeleteFuture) result(client RouteFilterRulesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteFilterRulesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// RouteFiltersCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type RouteFiltersCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteFiltersClient) (RouteFilter, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteFiltersCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteFiltersCreateOrUpdateFuture.Result. -func (future *RouteFiltersCreateOrUpdateFuture) result(client RouteFiltersClient) (rf RouteFilter, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - rf.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteFiltersCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if rf.Response.Response, err = future.GetResult(sender); err == nil && rf.Response.Response.StatusCode != http.StatusNoContent { - rf, err = client.CreateOrUpdateResponder(rf.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersCreateOrUpdateFuture", "Result", rf.Response.Response, "Failure responding to request") - } - } - return -} - -// RouteFiltersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RouteFiltersDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteFiltersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteFiltersDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteFiltersDeleteFuture.Result. -func (future *RouteFiltersDeleteFuture) result(client RouteFiltersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteFiltersDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// RouteListResult response for the ListRoute API service call. -type RouteListResult struct { - autorest.Response `json:"-"` - // Value - A list of routes in a resource group. - Value *[]Route `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RouteListResultIterator provides access to a complete listing of Route values. -type RouteListResultIterator struct { - i int - page RouteListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RouteListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RouteListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RouteListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RouteListResultIterator) Response() RouteListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RouteListResultIterator) Value() Route { - if !iter.page.NotDone() { - return Route{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the RouteListResultIterator type. -func NewRouteListResultIterator(page RouteListResultPage) RouteListResultIterator { - return RouteListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rlr RouteListResult) IsEmpty() bool { - return rlr.Value == nil || len(*rlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rlr RouteListResult) hasNextLink() bool { - return rlr.NextLink != nil && len(*rlr.NextLink) != 0 -} - -// routeListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rlr RouteListResult) routeListResultPreparer(ctx context.Context) (*http.Request, error) { - if !rlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rlr.NextLink))) -} - -// RouteListResultPage contains a page of Route values. -type RouteListResultPage struct { - fn func(context.Context, RouteListResult) (RouteListResult, error) - rlr RouteListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RouteListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rlr) - if err != nil { - return err - } - page.rlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RouteListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RouteListResultPage) NotDone() bool { - return !page.rlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RouteListResultPage) Response() RouteListResult { - return page.rlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RouteListResultPage) Values() []Route { - if page.rlr.IsEmpty() { - return nil - } - return *page.rlr.Value -} - -// Creates a new instance of the RouteListResultPage type. -func NewRouteListResultPage(cur RouteListResult, getNextPage func(context.Context, RouteListResult) (RouteListResult, error)) RouteListResultPage { - return RouteListResultPage{ - fn: getNextPage, - rlr: cur, - } -} - -// RouteMap the RouteMap child resource of a Virtual hub. -type RouteMap struct { - autorest.Response `json:"-"` - // RouteMapProperties - Properties of the RouteMap resource. - *RouteMapProperties `json:"properties,omitempty"` - // Name - READ-ONLY; The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for RouteMap. -func (rm RouteMap) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rm.RouteMapProperties != nil { - objectMap["properties"] = rm.RouteMapProperties - } - if rm.ID != nil { - objectMap["id"] = rm.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for RouteMap struct. -func (rm *RouteMap) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routeMapProperties RouteMapProperties - err = json.Unmarshal(*v, &routeMapProperties) - if err != nil { - return err - } - rm.RouteMapProperties = &routeMapProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rm.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - rm.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - rm.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rm.ID = &ID - } - } - } - - return nil -} - -// RouteMapProperties properties of RouteMap resource -type RouteMapProperties struct { - // AssociatedInboundConnections - List of connections which have this RoutMap associated for inbound traffic. - AssociatedInboundConnections *[]string `json:"associatedInboundConnections,omitempty"` - // AssociatedOutboundConnections - List of connections which have this RoutMap associated for outbound traffic. - AssociatedOutboundConnections *[]string `json:"associatedOutboundConnections,omitempty"` - // Rules - List of RouteMap rules to be applied. - Rules *[]RouteMapRule `json:"rules,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the RouteMap resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for RouteMapProperties. -func (rmp RouteMapProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rmp.AssociatedInboundConnections != nil { - objectMap["associatedInboundConnections"] = rmp.AssociatedInboundConnections - } - if rmp.AssociatedOutboundConnections != nil { - objectMap["associatedOutboundConnections"] = rmp.AssociatedOutboundConnections - } - if rmp.Rules != nil { - objectMap["rules"] = rmp.Rules - } - return json.Marshal(objectMap) -} - -// RouteMapRule a RouteMap Rule. -type RouteMapRule struct { - // Name - The unique name for the rule. - Name *string `json:"name,omitempty"` - // MatchCriteria - List of matching criterion which will be applied to traffic. - MatchCriteria *[]Criterion `json:"matchCriteria,omitempty"` - // Actions - List of actions which will be applied on a match. - Actions *[]Action `json:"actions,omitempty"` - // NextStepIfMatched - Next step after rule is evaluated. Current supported behaviors are 'Continue'(to next rule) and 'Terminate'. Possible values include: 'NextStepUnknown', 'NextStepContinue', 'NextStepTerminate' - NextStepIfMatched NextStep `json:"nextStepIfMatched,omitempty"` -} - -// RouteMapsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RouteMapsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteMapsClient) (RouteMap, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteMapsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteMapsCreateOrUpdateFuture.Result. -func (future *RouteMapsCreateOrUpdateFuture) result(client RouteMapsClient) (rm RouteMap, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteMapsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - rm.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteMapsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if rm.Response.Response, err = future.GetResult(sender); err == nil && rm.Response.Response.StatusCode != http.StatusNoContent { - rm, err = client.CreateOrUpdateResponder(rm.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteMapsCreateOrUpdateFuture", "Result", rm.Response.Response, "Failure responding to request") - } - } - return -} - -// RouteMapsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RouteMapsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteMapsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteMapsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteMapsDeleteFuture.Result. -func (future *RouteMapsDeleteFuture) result(client RouteMapsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteMapsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteMapsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// RoutePropertiesFormat route resource. -type RoutePropertiesFormat struct { - // AddressPrefix - The destination CIDR to which the route applies. - AddressPrefix *string `json:"addressPrefix,omitempty"` - // NextHopType - The type of Azure hop the packet should be sent to. Possible values include: 'RouteNextHopTypeVirtualNetworkGateway', 'RouteNextHopTypeVnetLocal', 'RouteNextHopTypeInternet', 'RouteNextHopTypeVirtualAppliance', 'RouteNextHopTypeNone' - NextHopType RouteNextHopType `json:"nextHopType,omitempty"` - // NextHopIPAddress - The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is VirtualAppliance. - NextHopIPAddress *string `json:"nextHopIpAddress,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the route resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // HasBgpOverride - A value indicating whether this route overrides overlapping BGP routes regardless of LPM. - HasBgpOverride *bool `json:"hasBgpOverride,omitempty"` -} - -// MarshalJSON is the custom marshaler for RoutePropertiesFormat. -func (rpf RoutePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rpf.AddressPrefix != nil { - objectMap["addressPrefix"] = rpf.AddressPrefix - } - if rpf.NextHopType != "" { - objectMap["nextHopType"] = rpf.NextHopType - } - if rpf.NextHopIPAddress != nil { - objectMap["nextHopIpAddress"] = rpf.NextHopIPAddress - } - if rpf.HasBgpOverride != nil { - objectMap["hasBgpOverride"] = rpf.HasBgpOverride - } - return json.Marshal(objectMap) -} - -// RoutesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RoutesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RoutesClient) (Route, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RoutesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RoutesCreateOrUpdateFuture.Result. -func (future *RoutesCreateOrUpdateFuture) result(client RoutesClient) (r Route, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - r.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RoutesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if r.Response.Response, err = future.GetResult(sender); err == nil && r.Response.Response.StatusCode != http.StatusNoContent { - r, err = client.CreateOrUpdateResponder(r.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesCreateOrUpdateFuture", "Result", r.Response.Response, "Failure responding to request") - } - } - return -} - -// RoutesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type RoutesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RoutesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RoutesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RoutesDeleteFuture.Result. -func (future *RoutesDeleteFuture) result(client RoutesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RoutesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// RouteTable route table resource. -type RouteTable struct { - autorest.Response `json:"-"` - // RouteTablePropertiesFormat - Properties of the route table. - *RouteTablePropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for RouteTable. -func (rt RouteTable) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rt.RouteTablePropertiesFormat != nil { - objectMap["properties"] = rt.RouteTablePropertiesFormat - } - if rt.ID != nil { - objectMap["id"] = rt.ID - } - if rt.Location != nil { - objectMap["location"] = rt.Location - } - if rt.Tags != nil { - objectMap["tags"] = rt.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for RouteTable struct. -func (rt *RouteTable) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routeTablePropertiesFormat RouteTablePropertiesFormat - err = json.Unmarshal(*v, &routeTablePropertiesFormat) - if err != nil { - return err - } - rt.RouteTablePropertiesFormat = &routeTablePropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - rt.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rt.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rt.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - rt.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - rt.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - rt.Tags = tags - } - } - } - - return nil -} - -// RouteTableListResult response for the ListRouteTable API service call. -type RouteTableListResult struct { - autorest.Response `json:"-"` - // Value - A list of route tables in a resource group. - Value *[]RouteTable `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RouteTableListResultIterator provides access to a complete listing of RouteTable values. -type RouteTableListResultIterator struct { - i int - page RouteTableListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RouteTableListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTableListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *RouteTableListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RouteTableListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RouteTableListResultIterator) Response() RouteTableListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RouteTableListResultIterator) Value() RouteTable { - if !iter.page.NotDone() { - return RouteTable{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the RouteTableListResultIterator type. -func NewRouteTableListResultIterator(page RouteTableListResultPage) RouteTableListResultIterator { - return RouteTableListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (rtlr RouteTableListResult) IsEmpty() bool { - return rtlr.Value == nil || len(*rtlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (rtlr RouteTableListResult) hasNextLink() bool { - return rtlr.NextLink != nil && len(*rtlr.NextLink) != 0 -} - -// routeTableListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rtlr RouteTableListResult) routeTableListResultPreparer(ctx context.Context) (*http.Request, error) { - if !rtlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rtlr.NextLink))) -} - -// RouteTableListResultPage contains a page of RouteTable values. -type RouteTableListResultPage struct { - fn func(context.Context, RouteTableListResult) (RouteTableListResult, error) - rtlr RouteTableListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RouteTableListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTableListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.rtlr) - if err != nil { - return err - } - page.rtlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *RouteTableListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RouteTableListResultPage) NotDone() bool { - return !page.rtlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RouteTableListResultPage) Response() RouteTableListResult { - return page.rtlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RouteTableListResultPage) Values() []RouteTable { - if page.rtlr.IsEmpty() { - return nil - } - return *page.rtlr.Value -} - -// Creates a new instance of the RouteTableListResultPage type. -func NewRouteTableListResultPage(cur RouteTableListResult, getNextPage func(context.Context, RouteTableListResult) (RouteTableListResult, error)) RouteTableListResultPage { - return RouteTableListResultPage{ - fn: getNextPage, - rtlr: cur, - } -} - -// RouteTablePropertiesFormat route Table resource. -type RouteTablePropertiesFormat struct { - // Routes - Collection of routes contained within a route table. - Routes *[]Route `json:"routes,omitempty"` - // Subnets - READ-ONLY; A collection of references to subnets. - Subnets *[]Subnet `json:"subnets,omitempty"` - // DisableBgpRoutePropagation - Whether to disable the routes learned by BGP on that route table. True means disable. - DisableBgpRoutePropagation *bool `json:"disableBgpRoutePropagation,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the route table resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the route table. - ResourceGUID *string `json:"resourceGuid,omitempty"` -} - -// MarshalJSON is the custom marshaler for RouteTablePropertiesFormat. -func (rtpf RouteTablePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rtpf.Routes != nil { - objectMap["routes"] = rtpf.Routes - } - if rtpf.DisableBgpRoutePropagation != nil { - objectMap["disableBgpRoutePropagation"] = rtpf.DisableBgpRoutePropagation - } - return json.Marshal(objectMap) -} - -// RouteTablesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type RouteTablesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteTablesClient) (RouteTable, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteTablesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteTablesCreateOrUpdateFuture.Result. -func (future *RouteTablesCreateOrUpdateFuture) result(client RouteTablesClient) (rt RouteTable, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - rt.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteTablesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if rt.Response.Response, err = future.GetResult(sender); err == nil && rt.Response.Response.StatusCode != http.StatusNoContent { - rt, err = client.CreateOrUpdateResponder(rt.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesCreateOrUpdateFuture", "Result", rt.Response.Response, "Failure responding to request") - } - } - return -} - -// RouteTablesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RouteTablesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RouteTablesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RouteTablesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RouteTablesDeleteFuture.Result. -func (future *RouteTablesDeleteFuture) result(client RouteTablesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RouteTablesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// RoutingConfiguration routing Configuration indicating the associated and propagated route tables for -// this connection. -type RoutingConfiguration struct { - // AssociatedRouteTable - The resource id RouteTable associated with this RoutingConfiguration. - AssociatedRouteTable *SubResource `json:"associatedRouteTable,omitempty"` - // PropagatedRouteTables - The list of RouteTables to advertise the routes to. - PropagatedRouteTables *PropagatedRouteTable `json:"propagatedRouteTables,omitempty"` - // VnetRoutes - List of routes that control routing from VirtualHub into a virtual network connection. - VnetRoutes *VnetRoute `json:"vnetRoutes,omitempty"` - // InboundRouteMap - The resource id of the RouteMap associated with this RoutingConfiguration for inbound learned routes. - InboundRouteMap *SubResource `json:"inboundRouteMap,omitempty"` - // OutboundRouteMap - The resource id of theRouteMap associated with this RoutingConfiguration for outbound advertised routes. - OutboundRouteMap *SubResource `json:"outboundRouteMap,omitempty"` -} - -// RoutingIntent the routing intent child resource of a Virtual hub. -type RoutingIntent struct { - autorest.Response `json:"-"` - // RoutingIntentProperties - Properties of the RoutingIntent resource. - *RoutingIntentProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for RoutingIntent. -func (ri RoutingIntent) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ri.RoutingIntentProperties != nil { - objectMap["properties"] = ri.RoutingIntentProperties - } - if ri.Name != nil { - objectMap["name"] = ri.Name - } - if ri.ID != nil { - objectMap["id"] = ri.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for RoutingIntent struct. -func (ri *RoutingIntent) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var routingIntentProperties RoutingIntentProperties - err = json.Unmarshal(*v, &routingIntentProperties) - if err != nil { - return err - } - ri.RoutingIntentProperties = &routingIntentProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - ri.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - ri.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - ri.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - ri.ID = &ID - } - } - } - - return nil -} - -// RoutingIntentCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type RoutingIntentCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RoutingIntentClient) (RoutingIntent, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RoutingIntentCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RoutingIntentCreateOrUpdateFuture.Result. -func (future *RoutingIntentCreateOrUpdateFuture) result(client RoutingIntentClient) (ri RoutingIntent, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutingIntentCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ri.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RoutingIntentCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ri.Response.Response, err = future.GetResult(sender); err == nil && ri.Response.Response.StatusCode != http.StatusNoContent { - ri, err = client.CreateOrUpdateResponder(ri.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutingIntentCreateOrUpdateFuture", "Result", ri.Response.Response, "Failure responding to request") - } - } - return -} - -// RoutingIntentDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type RoutingIntentDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(RoutingIntentClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *RoutingIntentDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for RoutingIntentDeleteFuture.Result. -func (future *RoutingIntentDeleteFuture) result(client RoutingIntentClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutingIntentDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.RoutingIntentDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// RoutingIntentProperties the properties of a RoutingIntent resource. -type RoutingIntentProperties struct { - // RoutingPolicies - List of routing policies. - RoutingPolicies *[]RoutingPolicy `json:"routingPolicies,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the RoutingIntent resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for RoutingIntentProperties. -func (rip RoutingIntentProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rip.RoutingPolicies != nil { - objectMap["routingPolicies"] = rip.RoutingPolicies - } - return json.Marshal(objectMap) -} - -// RoutingPolicy the routing policy object used in a RoutingIntent resource. -type RoutingPolicy struct { - // Name - The unique name for the routing policy. - Name *string `json:"name,omitempty"` - // Destinations - List of all destinations which this routing policy is applicable to (for example: Internet, PrivateTraffic). - Destinations *[]string `json:"destinations,omitempty"` - // NextHop - The next hop resource id on which this routing policy is applicable to. - NextHop *string `json:"nextHop,omitempty"` -} - -// Rule rule of type network. -type Rule struct { - // IPProtocols - Array of FirewallPolicyRuleNetworkProtocols. - IPProtocols *[]FirewallPolicyRuleNetworkProtocol `json:"ipProtocols,omitempty"` - // SourceAddresses - List of source IP addresses for this rule. - SourceAddresses *[]string `json:"sourceAddresses,omitempty"` - // DestinationAddresses - List of destination IP addresses or Service Tags. - DestinationAddresses *[]string `json:"destinationAddresses,omitempty"` - // DestinationPorts - List of destination ports. - DestinationPorts *[]string `json:"destinationPorts,omitempty"` - // SourceIPGroups - List of source IpGroups for this rule. - SourceIPGroups *[]string `json:"sourceIpGroups,omitempty"` - // DestinationIPGroups - List of destination IpGroups for this rule. - DestinationIPGroups *[]string `json:"destinationIpGroups,omitempty"` - // DestinationFqdns - List of destination FQDNs. - DestinationFqdns *[]string `json:"destinationFqdns,omitempty"` - // Name - Name of the rule. - Name *string `json:"name,omitempty"` - // Description - Description of the rule. - Description *string `json:"description,omitempty"` - // RuleType - Possible values include: 'RuleTypeFirewallPolicyRule', 'RuleTypeApplicationRule', 'RuleTypeNatRule', 'RuleTypeNetworkRule' - RuleType RuleType `json:"ruleType,omitempty"` -} - -// MarshalJSON is the custom marshaler for Rule. -func (r Rule) MarshalJSON() ([]byte, error) { - r.RuleType = RuleTypeNetworkRule - objectMap := make(map[string]interface{}) - if r.IPProtocols != nil { - objectMap["ipProtocols"] = r.IPProtocols - } - if r.SourceAddresses != nil { - objectMap["sourceAddresses"] = r.SourceAddresses - } - if r.DestinationAddresses != nil { - objectMap["destinationAddresses"] = r.DestinationAddresses - } - if r.DestinationPorts != nil { - objectMap["destinationPorts"] = r.DestinationPorts - } - if r.SourceIPGroups != nil { - objectMap["sourceIpGroups"] = r.SourceIPGroups - } - if r.DestinationIPGroups != nil { - objectMap["destinationIpGroups"] = r.DestinationIPGroups - } - if r.DestinationFqdns != nil { - objectMap["destinationFqdns"] = r.DestinationFqdns - } - if r.Name != nil { - objectMap["name"] = r.Name - } - if r.Description != nil { - objectMap["description"] = r.Description - } - if r.RuleType != "" { - objectMap["ruleType"] = r.RuleType - } - return json.Marshal(objectMap) -} - -// AsApplicationRule is the BasicFirewallPolicyRule implementation for Rule. -func (r Rule) AsApplicationRule() (*ApplicationRule, bool) { - return nil, false -} - -// AsNatRule is the BasicFirewallPolicyRule implementation for Rule. -func (r Rule) AsNatRule() (*NatRule, bool) { - return nil, false -} - -// AsRule is the BasicFirewallPolicyRule implementation for Rule. -func (r Rule) AsRule() (*Rule, bool) { - return &r, true -} - -// AsFirewallPolicyRule is the BasicFirewallPolicyRule implementation for Rule. -func (r Rule) AsFirewallPolicyRule() (*FirewallPolicyRule, bool) { - return nil, false -} - -// AsBasicFirewallPolicyRule is the BasicFirewallPolicyRule implementation for Rule. -func (r Rule) AsBasicFirewallPolicyRule() (BasicFirewallPolicyRule, bool) { - return &r, true -} - -// ScopeConnection the Scope Connections resource -type ScopeConnection struct { - autorest.Response `json:"-"` - // ScopeConnectionProperties - The scope connection properties - *ScopeConnectionProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system metadata related to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for ScopeConnection. -func (sc ScopeConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sc.ScopeConnectionProperties != nil { - objectMap["properties"] = sc.ScopeConnectionProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ScopeConnection struct. -func (sc *ScopeConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var scopeConnectionProperties ScopeConnectionProperties - err = json.Unmarshal(*v, &scopeConnectionProperties) - if err != nil { - return err - } - sc.ScopeConnectionProperties = &scopeConnectionProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - sc.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sc.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sc.Etag = &etag - } - } - } - - return nil -} - -// ScopeConnectionListResult list of scope connections. -type ScopeConnectionListResult struct { - autorest.Response `json:"-"` - // Value - List of scope connections. - Value *[]ScopeConnection `json:"value,omitempty"` - // NextLink - Gets the URL to get the next page of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ScopeConnectionListResultIterator provides access to a complete listing of ScopeConnection values. -type ScopeConnectionListResultIterator struct { - i int - page ScopeConnectionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ScopeConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ScopeConnectionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ScopeConnectionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ScopeConnectionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ScopeConnectionListResultIterator) Response() ScopeConnectionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ScopeConnectionListResultIterator) Value() ScopeConnection { - if !iter.page.NotDone() { - return ScopeConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ScopeConnectionListResultIterator type. -func NewScopeConnectionListResultIterator(page ScopeConnectionListResultPage) ScopeConnectionListResultIterator { - return ScopeConnectionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (sclr ScopeConnectionListResult) IsEmpty() bool { - return sclr.Value == nil || len(*sclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (sclr ScopeConnectionListResult) hasNextLink() bool { - return sclr.NextLink != nil && len(*sclr.NextLink) != 0 -} - -// scopeConnectionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (sclr ScopeConnectionListResult) scopeConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !sclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(sclr.NextLink))) -} - -// ScopeConnectionListResultPage contains a page of ScopeConnection values. -type ScopeConnectionListResultPage struct { - fn func(context.Context, ScopeConnectionListResult) (ScopeConnectionListResult, error) - sclr ScopeConnectionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ScopeConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ScopeConnectionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.sclr) - if err != nil { - return err - } - page.sclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ScopeConnectionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ScopeConnectionListResultPage) NotDone() bool { - return !page.sclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ScopeConnectionListResultPage) Response() ScopeConnectionListResult { - return page.sclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ScopeConnectionListResultPage) Values() []ScopeConnection { - if page.sclr.IsEmpty() { - return nil - } - return *page.sclr.Value -} - -// Creates a new instance of the ScopeConnectionListResultPage type. -func NewScopeConnectionListResultPage(cur ScopeConnectionListResult, getNextPage func(context.Context, ScopeConnectionListResult) (ScopeConnectionListResult, error)) ScopeConnectionListResultPage { - return ScopeConnectionListResultPage{ - fn: getNextPage, - sclr: cur, - } -} - -// ScopeConnectionProperties scope connection. -type ScopeConnectionProperties struct { - // TenantID - Tenant ID. - TenantID *string `json:"tenantId,omitempty"` - // ResourceID - Resource ID. - ResourceID *string `json:"resourceId,omitempty"` - // ConnectionState - Connection State. Possible values include: 'ScopeConnectionStateConnected', 'ScopeConnectionStatePending', 'ScopeConnectionStateConflict', 'ScopeConnectionStateRevoked', 'ScopeConnectionStateRejected' - ConnectionState ScopeConnectionState `json:"connectionState,omitempty"` - // Description - A description of the scope connection. - Description *string `json:"description,omitempty"` -} - -// SecurityAdminConfiguration defines the security admin configuration -type SecurityAdminConfiguration struct { - autorest.Response `json:"-"` - // SecurityAdminConfigurationPropertiesFormat - Indicates the properties for the network manager security admin configuration. - *SecurityAdminConfigurationPropertiesFormat `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system metadata related to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecurityAdminConfiguration. -func (sac SecurityAdminConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sac.SecurityAdminConfigurationPropertiesFormat != nil { - objectMap["properties"] = sac.SecurityAdminConfigurationPropertiesFormat - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SecurityAdminConfiguration struct. -func (sac *SecurityAdminConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var securityAdminConfigurationPropertiesFormat SecurityAdminConfigurationPropertiesFormat - err = json.Unmarshal(*v, &securityAdminConfigurationPropertiesFormat) - if err != nil { - return err - } - sac.SecurityAdminConfigurationPropertiesFormat = &securityAdminConfigurationPropertiesFormat - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - sac.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sac.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sac.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sac.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sac.Etag = &etag - } - } - } - - return nil -} - -// SecurityAdminConfigurationListResult a list of network manager security admin configurations -type SecurityAdminConfigurationListResult struct { - autorest.Response `json:"-"` - // Value - Gets a page of security admin configurations - Value *[]SecurityAdminConfiguration `json:"value,omitempty"` - // NextLink - Gets the URL to get the next page of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// SecurityAdminConfigurationListResultIterator provides access to a complete listing of -// SecurityAdminConfiguration values. -type SecurityAdminConfigurationListResultIterator struct { - i int - page SecurityAdminConfigurationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *SecurityAdminConfigurationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityAdminConfigurationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SecurityAdminConfigurationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter SecurityAdminConfigurationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter SecurityAdminConfigurationListResultIterator) Response() SecurityAdminConfigurationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter SecurityAdminConfigurationListResultIterator) Value() SecurityAdminConfiguration { - if !iter.page.NotDone() { - return SecurityAdminConfiguration{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the SecurityAdminConfigurationListResultIterator type. -func NewSecurityAdminConfigurationListResultIterator(page SecurityAdminConfigurationListResultPage) SecurityAdminConfigurationListResultIterator { - return SecurityAdminConfigurationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (saclr SecurityAdminConfigurationListResult) IsEmpty() bool { - return saclr.Value == nil || len(*saclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (saclr SecurityAdminConfigurationListResult) hasNextLink() bool { - return saclr.NextLink != nil && len(*saclr.NextLink) != 0 -} - -// securityAdminConfigurationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (saclr SecurityAdminConfigurationListResult) securityAdminConfigurationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !saclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(saclr.NextLink))) -} - -// SecurityAdminConfigurationListResultPage contains a page of SecurityAdminConfiguration values. -type SecurityAdminConfigurationListResultPage struct { - fn func(context.Context, SecurityAdminConfigurationListResult) (SecurityAdminConfigurationListResult, error) - saclr SecurityAdminConfigurationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SecurityAdminConfigurationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityAdminConfigurationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.saclr) - if err != nil { - return err - } - page.saclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SecurityAdminConfigurationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page SecurityAdminConfigurationListResultPage) NotDone() bool { - return !page.saclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page SecurityAdminConfigurationListResultPage) Response() SecurityAdminConfigurationListResult { - return page.saclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page SecurityAdminConfigurationListResultPage) Values() []SecurityAdminConfiguration { - if page.saclr.IsEmpty() { - return nil - } - return *page.saclr.Value -} - -// Creates a new instance of the SecurityAdminConfigurationListResultPage type. -func NewSecurityAdminConfigurationListResultPage(cur SecurityAdminConfigurationListResult, getNextPage func(context.Context, SecurityAdminConfigurationListResult) (SecurityAdminConfigurationListResult, error)) SecurityAdminConfigurationListResultPage { - return SecurityAdminConfigurationListResultPage{ - fn: getNextPage, - saclr: cur, - } -} - -// SecurityAdminConfigurationPropertiesFormat defines the security admin configuration properties. -type SecurityAdminConfigurationPropertiesFormat struct { - // Description - A description of the security configuration. - Description *string `json:"description,omitempty"` - // ApplyOnNetworkIntentPolicyBasedServices - Enum list of network intent policy based services. - ApplyOnNetworkIntentPolicyBasedServices *[]IntentPolicyBasedService `json:"applyOnNetworkIntentPolicyBasedServices,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecurityAdminConfigurationPropertiesFormat. -func (sacpf SecurityAdminConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sacpf.Description != nil { - objectMap["description"] = sacpf.Description - } - if sacpf.ApplyOnNetworkIntentPolicyBasedServices != nil { - objectMap["applyOnNetworkIntentPolicyBasedServices"] = sacpf.ApplyOnNetworkIntentPolicyBasedServices - } - return json.Marshal(objectMap) -} - -// SecurityAdminConfigurationsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type SecurityAdminConfigurationsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SecurityAdminConfigurationsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SecurityAdminConfigurationsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SecurityAdminConfigurationsDeleteFuture.Result. -func (future *SecurityAdminConfigurationsDeleteFuture) result(client SecurityAdminConfigurationsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityAdminConfigurationsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SecurityAdminConfigurationsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// SecurityGroup networkSecurityGroup resource. -type SecurityGroup struct { - autorest.Response `json:"-"` - // SecurityGroupPropertiesFormat - Properties of the network security group. - *SecurityGroupPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for SecurityGroup. -func (sg SecurityGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sg.SecurityGroupPropertiesFormat != nil { - objectMap["properties"] = sg.SecurityGroupPropertiesFormat - } - if sg.ID != nil { - objectMap["id"] = sg.ID - } - if sg.Location != nil { - objectMap["location"] = sg.Location - } - if sg.Tags != nil { - objectMap["tags"] = sg.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SecurityGroup struct. -func (sg *SecurityGroup) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var securityGroupPropertiesFormat SecurityGroupPropertiesFormat - err = json.Unmarshal(*v, &securityGroupPropertiesFormat) - if err != nil { - return err - } - sg.SecurityGroupPropertiesFormat = &securityGroupPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sg.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sg.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sg.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - sg.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - sg.Tags = tags - } - } - } - - return nil -} - -// SecurityGroupListResult response for ListNetworkSecurityGroups API service call. -type SecurityGroupListResult struct { - autorest.Response `json:"-"` - // Value - A list of NetworkSecurityGroup resources. - Value *[]SecurityGroup `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// SecurityGroupListResultIterator provides access to a complete listing of SecurityGroup values. -type SecurityGroupListResultIterator struct { - i int - page SecurityGroupListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *SecurityGroupListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SecurityGroupListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter SecurityGroupListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter SecurityGroupListResultIterator) Response() SecurityGroupListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter SecurityGroupListResultIterator) Value() SecurityGroup { - if !iter.page.NotDone() { - return SecurityGroup{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the SecurityGroupListResultIterator type. -func NewSecurityGroupListResultIterator(page SecurityGroupListResultPage) SecurityGroupListResultIterator { - return SecurityGroupListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (sglr SecurityGroupListResult) IsEmpty() bool { - return sglr.Value == nil || len(*sglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (sglr SecurityGroupListResult) hasNextLink() bool { - return sglr.NextLink != nil && len(*sglr.NextLink) != 0 -} - -// securityGroupListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (sglr SecurityGroupListResult) securityGroupListResultPreparer(ctx context.Context) (*http.Request, error) { - if !sglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(sglr.NextLink))) -} - -// SecurityGroupListResultPage contains a page of SecurityGroup values. -type SecurityGroupListResultPage struct { - fn func(context.Context, SecurityGroupListResult) (SecurityGroupListResult, error) - sglr SecurityGroupListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SecurityGroupListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.sglr) - if err != nil { - return err - } - page.sglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SecurityGroupListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page SecurityGroupListResultPage) NotDone() bool { - return !page.sglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page SecurityGroupListResultPage) Response() SecurityGroupListResult { - return page.sglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page SecurityGroupListResultPage) Values() []SecurityGroup { - if page.sglr.IsEmpty() { - return nil - } - return *page.sglr.Value -} - -// Creates a new instance of the SecurityGroupListResultPage type. -func NewSecurityGroupListResultPage(cur SecurityGroupListResult, getNextPage func(context.Context, SecurityGroupListResult) (SecurityGroupListResult, error)) SecurityGroupListResultPage { - return SecurityGroupListResultPage{ - fn: getNextPage, - sglr: cur, - } -} - -// SecurityGroupNetworkInterface network interface and all its associated security rules. -type SecurityGroupNetworkInterface struct { - // ID - ID of the network interface. - ID *string `json:"id,omitempty"` - // SecurityRuleAssociations - All security rules associated with the network interface. - SecurityRuleAssociations *SecurityRuleAssociations `json:"securityRuleAssociations,omitempty"` -} - -// SecurityGroupPropertiesFormat network Security Group resource. -type SecurityGroupPropertiesFormat struct { - // FlushConnection - When enabled, flows created from Network Security Group connections will be re-evaluated when rules are updates. Initial enablement will trigger re-evaluation. - FlushConnection *bool `json:"flushConnection,omitempty"` - // SecurityRules - A collection of security rules of the network security group. - SecurityRules *[]SecurityRule `json:"securityRules,omitempty"` - // DefaultSecurityRules - READ-ONLY; The default security rules of network security group. - DefaultSecurityRules *[]SecurityRule `json:"defaultSecurityRules,omitempty"` - // NetworkInterfaces - READ-ONLY; A collection of references to network interfaces. - NetworkInterfaces *[]Interface `json:"networkInterfaces,omitempty"` - // Subnets - READ-ONLY; A collection of references to subnets. - Subnets *[]Subnet `json:"subnets,omitempty"` - // FlowLogs - READ-ONLY; A collection of references to flow log resources. - FlowLogs *[]FlowLog `json:"flowLogs,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the network security group resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the network security group resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecurityGroupPropertiesFormat. -func (sgpf SecurityGroupPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sgpf.FlushConnection != nil { - objectMap["flushConnection"] = sgpf.FlushConnection - } - if sgpf.SecurityRules != nil { - objectMap["securityRules"] = sgpf.SecurityRules - } - return json.Marshal(objectMap) -} - -// SecurityGroupResult network configuration diagnostic result corresponded provided traffic query. -type SecurityGroupResult struct { - // SecurityRuleAccessResult - The network traffic is allowed or denied. Possible values include: 'SecurityRuleAccessAllow', 'SecurityRuleAccessDeny' - SecurityRuleAccessResult SecurityRuleAccess `json:"securityRuleAccessResult,omitempty"` - // EvaluatedNetworkSecurityGroups - READ-ONLY; List of results network security groups diagnostic. - EvaluatedNetworkSecurityGroups *[]EvaluatedNetworkSecurityGroup `json:"evaluatedNetworkSecurityGroups,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecurityGroupResult. -func (sgr SecurityGroupResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sgr.SecurityRuleAccessResult != "" { - objectMap["securityRuleAccessResult"] = sgr.SecurityRuleAccessResult - } - return json.Marshal(objectMap) -} - -// SecurityGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type SecurityGroupsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SecurityGroupsClient) (SecurityGroup, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SecurityGroupsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SecurityGroupsCreateOrUpdateFuture.Result. -func (future *SecurityGroupsCreateOrUpdateFuture) result(client SecurityGroupsClient) (sg SecurityGroup, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SecurityGroupsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sg.Response.Response, err = future.GetResult(sender); err == nil && sg.Response.Response.StatusCode != http.StatusNoContent { - sg, err = client.CreateOrUpdateResponder(sg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsCreateOrUpdateFuture", "Result", sg.Response.Response, "Failure responding to request") - } - } - return -} - -// SecurityGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SecurityGroupsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SecurityGroupsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SecurityGroupsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SecurityGroupsDeleteFuture.Result. -func (future *SecurityGroupsDeleteFuture) result(client SecurityGroupsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SecurityGroupsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// SecurityGroupViewParameters parameters that define the VM to check security groups for. -type SecurityGroupViewParameters struct { - // TargetResourceID - ID of the target VM. - TargetResourceID *string `json:"targetResourceId,omitempty"` -} - -// SecurityGroupViewResult the information about security rules applied to the specified VM. -type SecurityGroupViewResult struct { - autorest.Response `json:"-"` - // NetworkInterfaces - List of network interfaces on the specified VM. - NetworkInterfaces *[]SecurityGroupNetworkInterface `json:"networkInterfaces,omitempty"` -} - -// SecurityPartnerProvider security Partner Provider resource. -type SecurityPartnerProvider struct { - autorest.Response `json:"-"` - // SecurityPartnerProviderPropertiesFormat - Properties of the Security Partner Provider. - *SecurityPartnerProviderPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for SecurityPartnerProvider. -func (spp SecurityPartnerProvider) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if spp.SecurityPartnerProviderPropertiesFormat != nil { - objectMap["properties"] = spp.SecurityPartnerProviderPropertiesFormat - } - if spp.ID != nil { - objectMap["id"] = spp.ID - } - if spp.Location != nil { - objectMap["location"] = spp.Location - } - if spp.Tags != nil { - objectMap["tags"] = spp.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SecurityPartnerProvider struct. -func (spp *SecurityPartnerProvider) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var securityPartnerProviderPropertiesFormat SecurityPartnerProviderPropertiesFormat - err = json.Unmarshal(*v, &securityPartnerProviderPropertiesFormat) - if err != nil { - return err - } - spp.SecurityPartnerProviderPropertiesFormat = &securityPartnerProviderPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - spp.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - spp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - spp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - spp.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - spp.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - spp.Tags = tags - } - } - } - - return nil -} - -// SecurityPartnerProviderListResult response for ListSecurityPartnerProviders API service call. -type SecurityPartnerProviderListResult struct { - autorest.Response `json:"-"` - // Value - List of Security Partner Providers in a resource group. - Value *[]SecurityPartnerProvider `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// SecurityPartnerProviderListResultIterator provides access to a complete listing of -// SecurityPartnerProvider values. -type SecurityPartnerProviderListResultIterator struct { - i int - page SecurityPartnerProviderListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *SecurityPartnerProviderListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityPartnerProviderListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SecurityPartnerProviderListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter SecurityPartnerProviderListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter SecurityPartnerProviderListResultIterator) Response() SecurityPartnerProviderListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter SecurityPartnerProviderListResultIterator) Value() SecurityPartnerProvider { - if !iter.page.NotDone() { - return SecurityPartnerProvider{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the SecurityPartnerProviderListResultIterator type. -func NewSecurityPartnerProviderListResultIterator(page SecurityPartnerProviderListResultPage) SecurityPartnerProviderListResultIterator { - return SecurityPartnerProviderListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (spplr SecurityPartnerProviderListResult) IsEmpty() bool { - return spplr.Value == nil || len(*spplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (spplr SecurityPartnerProviderListResult) hasNextLink() bool { - return spplr.NextLink != nil && len(*spplr.NextLink) != 0 -} - -// securityPartnerProviderListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (spplr SecurityPartnerProviderListResult) securityPartnerProviderListResultPreparer(ctx context.Context) (*http.Request, error) { - if !spplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(spplr.NextLink))) -} - -// SecurityPartnerProviderListResultPage contains a page of SecurityPartnerProvider values. -type SecurityPartnerProviderListResultPage struct { - fn func(context.Context, SecurityPartnerProviderListResult) (SecurityPartnerProviderListResult, error) - spplr SecurityPartnerProviderListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SecurityPartnerProviderListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityPartnerProviderListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.spplr) - if err != nil { - return err - } - page.spplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SecurityPartnerProviderListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page SecurityPartnerProviderListResultPage) NotDone() bool { - return !page.spplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page SecurityPartnerProviderListResultPage) Response() SecurityPartnerProviderListResult { - return page.spplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page SecurityPartnerProviderListResultPage) Values() []SecurityPartnerProvider { - if page.spplr.IsEmpty() { - return nil - } - return *page.spplr.Value -} - -// Creates a new instance of the SecurityPartnerProviderListResultPage type. -func NewSecurityPartnerProviderListResultPage(cur SecurityPartnerProviderListResult, getNextPage func(context.Context, SecurityPartnerProviderListResult) (SecurityPartnerProviderListResult, error)) SecurityPartnerProviderListResultPage { - return SecurityPartnerProviderListResultPage{ - fn: getNextPage, - spplr: cur, - } -} - -// SecurityPartnerProviderPropertiesFormat properties of the Security Partner Provider. -type SecurityPartnerProviderPropertiesFormat struct { - // ProvisioningState - READ-ONLY; The provisioning state of the Security Partner Provider resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // SecurityProviderName - The security provider name. Possible values include: 'ZScaler', 'IBoss', 'Checkpoint' - SecurityProviderName SecurityProviderName `json:"securityProviderName,omitempty"` - // ConnectionStatus - READ-ONLY; The connection status with the Security Partner Provider. Possible values include: 'SecurityPartnerProviderConnectionStatusUnknown', 'SecurityPartnerProviderConnectionStatusPartiallyConnected', 'SecurityPartnerProviderConnectionStatusConnected', 'SecurityPartnerProviderConnectionStatusNotConnected' - ConnectionStatus SecurityPartnerProviderConnectionStatus `json:"connectionStatus,omitempty"` - // VirtualHub - The virtualHub to which the Security Partner Provider belongs. - VirtualHub *SubResource `json:"virtualHub,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecurityPartnerProviderPropertiesFormat. -func (spppf SecurityPartnerProviderPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if spppf.SecurityProviderName != "" { - objectMap["securityProviderName"] = spppf.SecurityProviderName - } - if spppf.VirtualHub != nil { - objectMap["virtualHub"] = spppf.VirtualHub - } - return json.Marshal(objectMap) -} - -// SecurityPartnerProvidersCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type SecurityPartnerProvidersCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SecurityPartnerProvidersClient) (SecurityPartnerProvider, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SecurityPartnerProvidersCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SecurityPartnerProvidersCreateOrUpdateFuture.Result. -func (future *SecurityPartnerProvidersCreateOrUpdateFuture) result(client SecurityPartnerProvidersClient) (spp SecurityPartnerProvider, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - spp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SecurityPartnerProvidersCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if spp.Response.Response, err = future.GetResult(sender); err == nil && spp.Response.Response.StatusCode != http.StatusNoContent { - spp, err = client.CreateOrUpdateResponder(spp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersCreateOrUpdateFuture", "Result", spp.Response.Response, "Failure responding to request") - } - } - return -} - -// SecurityPartnerProvidersDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type SecurityPartnerProvidersDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SecurityPartnerProvidersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SecurityPartnerProvidersDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SecurityPartnerProvidersDeleteFuture.Result. -func (future *SecurityPartnerProvidersDeleteFuture) result(client SecurityPartnerProvidersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SecurityPartnerProvidersDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// SecurityRule network security rule. -type SecurityRule struct { - autorest.Response `json:"-"` - // SecurityRulePropertiesFormat - Properties of the security rule. - *SecurityRulePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - The type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecurityRule. -func (sr SecurityRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sr.SecurityRulePropertiesFormat != nil { - objectMap["properties"] = sr.SecurityRulePropertiesFormat - } - if sr.Name != nil { - objectMap["name"] = sr.Name - } - if sr.Type != nil { - objectMap["type"] = sr.Type - } - if sr.ID != nil { - objectMap["id"] = sr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for SecurityRule struct. -func (sr *SecurityRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var securityRulePropertiesFormat SecurityRulePropertiesFormat - err = json.Unmarshal(*v, &securityRulePropertiesFormat) - if err != nil { - return err - } - sr.SecurityRulePropertiesFormat = &securityRulePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sr.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sr.ID = &ID - } - } - } - - return nil -} - -// SecurityRuleAssociations all security rules associated with the network interface. -type SecurityRuleAssociations struct { - // NetworkInterfaceAssociation - Network interface and it's custom security rules. - NetworkInterfaceAssociation *InterfaceAssociation `json:"networkInterfaceAssociation,omitempty"` - // SubnetAssociation - Subnet and it's custom security rules. - SubnetAssociation *SubnetAssociation `json:"subnetAssociation,omitempty"` - // DefaultSecurityRules - Collection of default security rules of the network security group. - DefaultSecurityRules *[]SecurityRule `json:"defaultSecurityRules,omitempty"` - // EffectiveSecurityRules - Collection of effective security rules. - EffectiveSecurityRules *[]EffectiveNetworkSecurityRule `json:"effectiveSecurityRules,omitempty"` -} - -// SecurityRuleListResult response for ListSecurityRule API service call. Retrieves all security rules that -// belongs to a network security group. -type SecurityRuleListResult struct { - autorest.Response `json:"-"` - // Value - The security rules in a network security group. - Value *[]SecurityRule `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// SecurityRuleListResultIterator provides access to a complete listing of SecurityRule values. -type SecurityRuleListResultIterator struct { - i int - page SecurityRuleListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *SecurityRuleListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRuleListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SecurityRuleListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter SecurityRuleListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter SecurityRuleListResultIterator) Response() SecurityRuleListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter SecurityRuleListResultIterator) Value() SecurityRule { - if !iter.page.NotDone() { - return SecurityRule{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the SecurityRuleListResultIterator type. -func NewSecurityRuleListResultIterator(page SecurityRuleListResultPage) SecurityRuleListResultIterator { - return SecurityRuleListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (srlr SecurityRuleListResult) IsEmpty() bool { - return srlr.Value == nil || len(*srlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (srlr SecurityRuleListResult) hasNextLink() bool { - return srlr.NextLink != nil && len(*srlr.NextLink) != 0 -} - -// securityRuleListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (srlr SecurityRuleListResult) securityRuleListResultPreparer(ctx context.Context) (*http.Request, error) { - if !srlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(srlr.NextLink))) -} - -// SecurityRuleListResultPage contains a page of SecurityRule values. -type SecurityRuleListResultPage struct { - fn func(context.Context, SecurityRuleListResult) (SecurityRuleListResult, error) - srlr SecurityRuleListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SecurityRuleListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRuleListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.srlr) - if err != nil { - return err - } - page.srlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SecurityRuleListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page SecurityRuleListResultPage) NotDone() bool { - return !page.srlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page SecurityRuleListResultPage) Response() SecurityRuleListResult { - return page.srlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page SecurityRuleListResultPage) Values() []SecurityRule { - if page.srlr.IsEmpty() { - return nil - } - return *page.srlr.Value -} - -// Creates a new instance of the SecurityRuleListResultPage type. -func NewSecurityRuleListResultPage(cur SecurityRuleListResult, getNextPage func(context.Context, SecurityRuleListResult) (SecurityRuleListResult, error)) SecurityRuleListResultPage { - return SecurityRuleListResultPage{ - fn: getNextPage, - srlr: cur, - } -} - -// SecurityRulePropertiesFormat security rule resource. -type SecurityRulePropertiesFormat struct { - // Description - A description for this rule. Restricted to 140 chars. - Description *string `json:"description,omitempty"` - // Protocol - Network protocol this rule applies to. Possible values include: 'SecurityRuleProtocolTCP', 'SecurityRuleProtocolUDP', 'SecurityRuleProtocolIcmp', 'SecurityRuleProtocolEsp', 'SecurityRuleProtocolAsterisk', 'SecurityRuleProtocolAh' - Protocol SecurityRuleProtocol `json:"protocol,omitempty"` - // SourcePortRange - The source port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. - SourcePortRange *string `json:"sourcePortRange,omitempty"` - // DestinationPortRange - The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. - DestinationPortRange *string `json:"destinationPortRange,omitempty"` - // SourceAddressPrefix - The CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. - SourceAddressPrefix *string `json:"sourceAddressPrefix,omitempty"` - // SourceAddressPrefixes - The CIDR or source IP ranges. - SourceAddressPrefixes *[]string `json:"sourceAddressPrefixes,omitempty"` - // SourceApplicationSecurityGroups - The application security group specified as source. - SourceApplicationSecurityGroups *[]ApplicationSecurityGroup `json:"sourceApplicationSecurityGroups,omitempty"` - // DestinationAddressPrefix - The destination address prefix. CIDR or destination IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. - DestinationAddressPrefix *string `json:"destinationAddressPrefix,omitempty"` - // DestinationAddressPrefixes - The destination address prefixes. CIDR or destination IP ranges. - DestinationAddressPrefixes *[]string `json:"destinationAddressPrefixes,omitempty"` - // DestinationApplicationSecurityGroups - The application security group specified as destination. - DestinationApplicationSecurityGroups *[]ApplicationSecurityGroup `json:"destinationApplicationSecurityGroups,omitempty"` - // SourcePortRanges - The source port ranges. - SourcePortRanges *[]string `json:"sourcePortRanges,omitempty"` - // DestinationPortRanges - The destination port ranges. - DestinationPortRanges *[]string `json:"destinationPortRanges,omitempty"` - // Access - The network traffic is allowed or denied. Possible values include: 'SecurityRuleAccessAllow', 'SecurityRuleAccessDeny' - Access SecurityRuleAccess `json:"access,omitempty"` - // Priority - The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each rule in the collection. The lower the priority number, the higher the priority of the rule. - Priority *int32 `json:"priority,omitempty"` - // Direction - The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic. Possible values include: 'SecurityRuleDirectionInbound', 'SecurityRuleDirectionOutbound' - Direction SecurityRuleDirection `json:"direction,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the security rule resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecurityRulePropertiesFormat. -func (srpf SecurityRulePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if srpf.Description != nil { - objectMap["description"] = srpf.Description - } - if srpf.Protocol != "" { - objectMap["protocol"] = srpf.Protocol - } - if srpf.SourcePortRange != nil { - objectMap["sourcePortRange"] = srpf.SourcePortRange - } - if srpf.DestinationPortRange != nil { - objectMap["destinationPortRange"] = srpf.DestinationPortRange - } - if srpf.SourceAddressPrefix != nil { - objectMap["sourceAddressPrefix"] = srpf.SourceAddressPrefix - } - if srpf.SourceAddressPrefixes != nil { - objectMap["sourceAddressPrefixes"] = srpf.SourceAddressPrefixes - } - if srpf.SourceApplicationSecurityGroups != nil { - objectMap["sourceApplicationSecurityGroups"] = srpf.SourceApplicationSecurityGroups - } - if srpf.DestinationAddressPrefix != nil { - objectMap["destinationAddressPrefix"] = srpf.DestinationAddressPrefix - } - if srpf.DestinationAddressPrefixes != nil { - objectMap["destinationAddressPrefixes"] = srpf.DestinationAddressPrefixes - } - if srpf.DestinationApplicationSecurityGroups != nil { - objectMap["destinationApplicationSecurityGroups"] = srpf.DestinationApplicationSecurityGroups - } - if srpf.SourcePortRanges != nil { - objectMap["sourcePortRanges"] = srpf.SourcePortRanges - } - if srpf.DestinationPortRanges != nil { - objectMap["destinationPortRanges"] = srpf.DestinationPortRanges - } - if srpf.Access != "" { - objectMap["access"] = srpf.Access - } - if srpf.Priority != nil { - objectMap["priority"] = srpf.Priority - } - if srpf.Direction != "" { - objectMap["direction"] = srpf.Direction - } - return json.Marshal(objectMap) -} - -// SecurityRulesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type SecurityRulesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SecurityRulesClient) (SecurityRule, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SecurityRulesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SecurityRulesCreateOrUpdateFuture.Result. -func (future *SecurityRulesCreateOrUpdateFuture) result(client SecurityRulesClient) (sr SecurityRule, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SecurityRulesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sr.Response.Response, err = future.GetResult(sender); err == nil && sr.Response.Response.StatusCode != http.StatusNoContent { - sr, err = client.CreateOrUpdateResponder(sr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesCreateOrUpdateFuture", "Result", sr.Response.Response, "Failure responding to request") - } - } - return -} - -// SecurityRulesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SecurityRulesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SecurityRulesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SecurityRulesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SecurityRulesDeleteFuture.Result. -func (future *SecurityRulesDeleteFuture) result(client SecurityRulesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SecurityRulesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// SecurityRulesEvaluationResult network security rules evaluation result. -type SecurityRulesEvaluationResult struct { - // Name - Name of the network security rule. - Name *string `json:"name,omitempty"` - // ProtocolMatched - Value indicating whether protocol is matched. - ProtocolMatched *bool `json:"protocolMatched,omitempty"` - // SourceMatched - Value indicating whether source is matched. - SourceMatched *bool `json:"sourceMatched,omitempty"` - // SourcePortMatched - Value indicating whether source port is matched. - SourcePortMatched *bool `json:"sourcePortMatched,omitempty"` - // DestinationMatched - Value indicating whether destination is matched. - DestinationMatched *bool `json:"destinationMatched,omitempty"` - // DestinationPortMatched - Value indicating whether destination port is matched. - DestinationPortMatched *bool `json:"destinationPortMatched,omitempty"` -} - -// ServiceAssociationLink serviceAssociationLink resource. -type ServiceAssociationLink struct { - // ServiceAssociationLinkPropertiesFormat - Resource navigation link properties format. - *ServiceAssociationLinkPropertiesFormat `json:"properties,omitempty"` - // Name - Name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceAssociationLink. -func (sal ServiceAssociationLink) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sal.ServiceAssociationLinkPropertiesFormat != nil { - objectMap["properties"] = sal.ServiceAssociationLinkPropertiesFormat - } - if sal.Name != nil { - objectMap["name"] = sal.Name - } - if sal.ID != nil { - objectMap["id"] = sal.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ServiceAssociationLink struct. -func (sal *ServiceAssociationLink) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var serviceAssociationLinkPropertiesFormat ServiceAssociationLinkPropertiesFormat - err = json.Unmarshal(*v, &serviceAssociationLinkPropertiesFormat) - if err != nil { - return err - } - sal.ServiceAssociationLinkPropertiesFormat = &serviceAssociationLinkPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sal.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sal.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sal.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sal.ID = &ID - } - } - } - - return nil -} - -// ServiceAssociationLinkPropertiesFormat properties of ServiceAssociationLink. -type ServiceAssociationLinkPropertiesFormat struct { - // LinkedResourceType - Resource type of the linked resource. - LinkedResourceType *string `json:"linkedResourceType,omitempty"` - // Link - Link to the external resource. - Link *string `json:"link,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the service association link resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // AllowDelete - If true, the resource can be deleted. - AllowDelete *bool `json:"allowDelete,omitempty"` - // Locations - A list of locations. - Locations *[]string `json:"locations,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceAssociationLinkPropertiesFormat. -func (salpf ServiceAssociationLinkPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if salpf.LinkedResourceType != nil { - objectMap["linkedResourceType"] = salpf.LinkedResourceType - } - if salpf.Link != nil { - objectMap["link"] = salpf.Link - } - if salpf.AllowDelete != nil { - objectMap["allowDelete"] = salpf.AllowDelete - } - if salpf.Locations != nil { - objectMap["locations"] = salpf.Locations - } - return json.Marshal(objectMap) -} - -// ServiceAssociationLinksListResult response for ServiceAssociationLinks_List operation. -type ServiceAssociationLinksListResult struct { - autorest.Response `json:"-"` - // Value - The service association links in a subnet. - Value *[]ServiceAssociationLink `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceAssociationLinksListResult. -func (sallr ServiceAssociationLinksListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sallr.Value != nil { - objectMap["value"] = sallr.Value - } - return json.Marshal(objectMap) -} - -// ServiceDelegationPropertiesFormat properties of a service delegation. -type ServiceDelegationPropertiesFormat struct { - // ServiceName - The name of the service to whom the subnet should be delegated (e.g. Microsoft.Sql/servers). - ServiceName *string `json:"serviceName,omitempty"` - // Actions - READ-ONLY; The actions permitted to the service upon delegation. - Actions *[]string `json:"actions,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the service delegation resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceDelegationPropertiesFormat. -func (sdpf ServiceDelegationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sdpf.ServiceName != nil { - objectMap["serviceName"] = sdpf.ServiceName - } - return json.Marshal(objectMap) -} - -// ServiceEndpointPoliciesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type ServiceEndpointPoliciesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServiceEndpointPoliciesClient) (ServiceEndpointPolicy, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServiceEndpointPoliciesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServiceEndpointPoliciesCreateOrUpdateFuture.Result. -func (future *ServiceEndpointPoliciesCreateOrUpdateFuture) result(client ServiceEndpointPoliciesClient) (sep ServiceEndpointPolicy, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sep.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ServiceEndpointPoliciesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sep.Response.Response, err = future.GetResult(sender); err == nil && sep.Response.Response.StatusCode != http.StatusNoContent { - sep, err = client.CreateOrUpdateResponder(sep.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesCreateOrUpdateFuture", "Result", sep.Response.Response, "Failure responding to request") - } - } - return -} - -// ServiceEndpointPoliciesDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type ServiceEndpointPoliciesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServiceEndpointPoliciesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServiceEndpointPoliciesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServiceEndpointPoliciesDeleteFuture.Result. -func (future *ServiceEndpointPoliciesDeleteFuture) result(client ServiceEndpointPoliciesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ServiceEndpointPoliciesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ServiceEndpointPolicy service End point policy resource. -type ServiceEndpointPolicy struct { - autorest.Response `json:"-"` - // ServiceEndpointPolicyPropertiesFormat - Properties of the service end point policy. - *ServiceEndpointPolicyPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Kind - READ-ONLY; Kind of service endpoint policy. This is metadata used for the Azure portal experience. - Kind *string `json:"kind,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ServiceEndpointPolicy. -func (sep ServiceEndpointPolicy) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sep.ServiceEndpointPolicyPropertiesFormat != nil { - objectMap["properties"] = sep.ServiceEndpointPolicyPropertiesFormat - } - if sep.ID != nil { - objectMap["id"] = sep.ID - } - if sep.Location != nil { - objectMap["location"] = sep.Location - } - if sep.Tags != nil { - objectMap["tags"] = sep.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ServiceEndpointPolicy struct. -func (sep *ServiceEndpointPolicy) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var serviceEndpointPolicyPropertiesFormat ServiceEndpointPolicyPropertiesFormat - err = json.Unmarshal(*v, &serviceEndpointPolicyPropertiesFormat) - if err != nil { - return err - } - sep.ServiceEndpointPolicyPropertiesFormat = &serviceEndpointPolicyPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sep.Etag = &etag - } - case "kind": - if v != nil { - var kind string - err = json.Unmarshal(*v, &kind) - if err != nil { - return err - } - sep.Kind = &kind - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sep.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sep.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sep.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - sep.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - sep.Tags = tags - } - } - } - - return nil -} - -// ServiceEndpointPolicyDefinition service Endpoint policy definitions. -type ServiceEndpointPolicyDefinition struct { - autorest.Response `json:"-"` - // ServiceEndpointPolicyDefinitionPropertiesFormat - Properties of the service endpoint policy definition. - *ServiceEndpointPolicyDefinitionPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - The type of the resource. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceEndpointPolicyDefinition. -func (sepd ServiceEndpointPolicyDefinition) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sepd.ServiceEndpointPolicyDefinitionPropertiesFormat != nil { - objectMap["properties"] = sepd.ServiceEndpointPolicyDefinitionPropertiesFormat - } - if sepd.Name != nil { - objectMap["name"] = sepd.Name - } - if sepd.Type != nil { - objectMap["type"] = sepd.Type - } - if sepd.ID != nil { - objectMap["id"] = sepd.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for ServiceEndpointPolicyDefinition struct. -func (sepd *ServiceEndpointPolicyDefinition) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var serviceEndpointPolicyDefinitionPropertiesFormat ServiceEndpointPolicyDefinitionPropertiesFormat - err = json.Unmarshal(*v, &serviceEndpointPolicyDefinitionPropertiesFormat) - if err != nil { - return err - } - sepd.ServiceEndpointPolicyDefinitionPropertiesFormat = &serviceEndpointPolicyDefinitionPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sepd.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sepd.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sepd.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sepd.ID = &ID - } - } - } - - return nil -} - -// ServiceEndpointPolicyDefinitionListResult response for ListServiceEndpointPolicyDefinition API service -// call. Retrieves all service endpoint policy definition that belongs to a service endpoint policy. -type ServiceEndpointPolicyDefinitionListResult struct { - autorest.Response `json:"-"` - // Value - The service endpoint policy definition in a service endpoint policy. - Value *[]ServiceEndpointPolicyDefinition `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ServiceEndpointPolicyDefinitionListResultIterator provides access to a complete listing of -// ServiceEndpointPolicyDefinition values. -type ServiceEndpointPolicyDefinitionListResultIterator struct { - i int - page ServiceEndpointPolicyDefinitionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ServiceEndpointPolicyDefinitionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ServiceEndpointPolicyDefinitionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ServiceEndpointPolicyDefinitionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ServiceEndpointPolicyDefinitionListResultIterator) Response() ServiceEndpointPolicyDefinitionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ServiceEndpointPolicyDefinitionListResultIterator) Value() ServiceEndpointPolicyDefinition { - if !iter.page.NotDone() { - return ServiceEndpointPolicyDefinition{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ServiceEndpointPolicyDefinitionListResultIterator type. -func NewServiceEndpointPolicyDefinitionListResultIterator(page ServiceEndpointPolicyDefinitionListResultPage) ServiceEndpointPolicyDefinitionListResultIterator { - return ServiceEndpointPolicyDefinitionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (sepdlr ServiceEndpointPolicyDefinitionListResult) IsEmpty() bool { - return sepdlr.Value == nil || len(*sepdlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (sepdlr ServiceEndpointPolicyDefinitionListResult) hasNextLink() bool { - return sepdlr.NextLink != nil && len(*sepdlr.NextLink) != 0 -} - -// serviceEndpointPolicyDefinitionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (sepdlr ServiceEndpointPolicyDefinitionListResult) serviceEndpointPolicyDefinitionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !sepdlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(sepdlr.NextLink))) -} - -// ServiceEndpointPolicyDefinitionListResultPage contains a page of ServiceEndpointPolicyDefinition values. -type ServiceEndpointPolicyDefinitionListResultPage struct { - fn func(context.Context, ServiceEndpointPolicyDefinitionListResult) (ServiceEndpointPolicyDefinitionListResult, error) - sepdlr ServiceEndpointPolicyDefinitionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ServiceEndpointPolicyDefinitionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.sepdlr) - if err != nil { - return err - } - page.sepdlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ServiceEndpointPolicyDefinitionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ServiceEndpointPolicyDefinitionListResultPage) NotDone() bool { - return !page.sepdlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ServiceEndpointPolicyDefinitionListResultPage) Response() ServiceEndpointPolicyDefinitionListResult { - return page.sepdlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ServiceEndpointPolicyDefinitionListResultPage) Values() []ServiceEndpointPolicyDefinition { - if page.sepdlr.IsEmpty() { - return nil - } - return *page.sepdlr.Value -} - -// Creates a new instance of the ServiceEndpointPolicyDefinitionListResultPage type. -func NewServiceEndpointPolicyDefinitionListResultPage(cur ServiceEndpointPolicyDefinitionListResult, getNextPage func(context.Context, ServiceEndpointPolicyDefinitionListResult) (ServiceEndpointPolicyDefinitionListResult, error)) ServiceEndpointPolicyDefinitionListResultPage { - return ServiceEndpointPolicyDefinitionListResultPage{ - fn: getNextPage, - sepdlr: cur, - } -} - -// ServiceEndpointPolicyDefinitionPropertiesFormat service Endpoint policy definition resource. -type ServiceEndpointPolicyDefinitionPropertiesFormat struct { - // Description - A description for this rule. Restricted to 140 chars. - Description *string `json:"description,omitempty"` - // Service - Service endpoint name. - Service *string `json:"service,omitempty"` - // ServiceResources - A list of service resources. - ServiceResources *[]string `json:"serviceResources,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the service endpoint policy definition resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceEndpointPolicyDefinitionPropertiesFormat. -func (sepdpf ServiceEndpointPolicyDefinitionPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sepdpf.Description != nil { - objectMap["description"] = sepdpf.Description - } - if sepdpf.Service != nil { - objectMap["service"] = sepdpf.Service - } - if sepdpf.ServiceResources != nil { - objectMap["serviceResources"] = sepdpf.ServiceResources - } - return json.Marshal(objectMap) -} - -// ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServiceEndpointPolicyDefinitionsClient) (ServiceEndpointPolicyDefinition, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture.Result. -func (future *ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture) result(client ServiceEndpointPolicyDefinitionsClient) (sepd ServiceEndpointPolicyDefinition, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sepd.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sepd.Response.Response, err = future.GetResult(sender); err == nil && sepd.Response.Response.StatusCode != http.StatusNoContent { - sepd, err = client.CreateOrUpdateResponder(sepd.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture", "Result", sepd.Response.Response, "Failure responding to request") - } - } - return -} - -// ServiceEndpointPolicyDefinitionsDeleteFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type ServiceEndpointPolicyDefinitionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(ServiceEndpointPolicyDefinitionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *ServiceEndpointPolicyDefinitionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for ServiceEndpointPolicyDefinitionsDeleteFuture.Result. -func (future *ServiceEndpointPolicyDefinitionsDeleteFuture) result(client ServiceEndpointPolicyDefinitionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.ServiceEndpointPolicyDefinitionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ServiceEndpointPolicyListResult response for ListServiceEndpointPolicies API service call. -type ServiceEndpointPolicyListResult struct { - autorest.Response `json:"-"` - // Value - A list of ServiceEndpointPolicy resources. - Value *[]ServiceEndpointPolicy `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceEndpointPolicyListResult. -func (seplr ServiceEndpointPolicyListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if seplr.Value != nil { - objectMap["value"] = seplr.Value - } - return json.Marshal(objectMap) -} - -// ServiceEndpointPolicyListResultIterator provides access to a complete listing of ServiceEndpointPolicy -// values. -type ServiceEndpointPolicyListResultIterator struct { - i int - page ServiceEndpointPolicyListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ServiceEndpointPolicyListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ServiceEndpointPolicyListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ServiceEndpointPolicyListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ServiceEndpointPolicyListResultIterator) Response() ServiceEndpointPolicyListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ServiceEndpointPolicyListResultIterator) Value() ServiceEndpointPolicy { - if !iter.page.NotDone() { - return ServiceEndpointPolicy{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ServiceEndpointPolicyListResultIterator type. -func NewServiceEndpointPolicyListResultIterator(page ServiceEndpointPolicyListResultPage) ServiceEndpointPolicyListResultIterator { - return ServiceEndpointPolicyListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (seplr ServiceEndpointPolicyListResult) IsEmpty() bool { - return seplr.Value == nil || len(*seplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (seplr ServiceEndpointPolicyListResult) hasNextLink() bool { - return seplr.NextLink != nil && len(*seplr.NextLink) != 0 -} - -// serviceEndpointPolicyListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (seplr ServiceEndpointPolicyListResult) serviceEndpointPolicyListResultPreparer(ctx context.Context) (*http.Request, error) { - if !seplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(seplr.NextLink))) -} - -// ServiceEndpointPolicyListResultPage contains a page of ServiceEndpointPolicy values. -type ServiceEndpointPolicyListResultPage struct { - fn func(context.Context, ServiceEndpointPolicyListResult) (ServiceEndpointPolicyListResult, error) - seplr ServiceEndpointPolicyListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ServiceEndpointPolicyListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.seplr) - if err != nil { - return err - } - page.seplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ServiceEndpointPolicyListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ServiceEndpointPolicyListResultPage) NotDone() bool { - return !page.seplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ServiceEndpointPolicyListResultPage) Response() ServiceEndpointPolicyListResult { - return page.seplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ServiceEndpointPolicyListResultPage) Values() []ServiceEndpointPolicy { - if page.seplr.IsEmpty() { - return nil - } - return *page.seplr.Value -} - -// Creates a new instance of the ServiceEndpointPolicyListResultPage type. -func NewServiceEndpointPolicyListResultPage(cur ServiceEndpointPolicyListResult, getNextPage func(context.Context, ServiceEndpointPolicyListResult) (ServiceEndpointPolicyListResult, error)) ServiceEndpointPolicyListResultPage { - return ServiceEndpointPolicyListResultPage{ - fn: getNextPage, - seplr: cur, - } -} - -// ServiceEndpointPolicyPropertiesFormat service Endpoint Policy resource. -type ServiceEndpointPolicyPropertiesFormat struct { - // ServiceEndpointPolicyDefinitions - A collection of service endpoint policy definitions of the service endpoint policy. - ServiceEndpointPolicyDefinitions *[]ServiceEndpointPolicyDefinition `json:"serviceEndpointPolicyDefinitions,omitempty"` - // Subnets - READ-ONLY; A collection of references to subnets. - Subnets *[]Subnet `json:"subnets,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the service endpoint policy resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the service endpoint policy resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ServiceAlias - The alias indicating if the policy belongs to a service - ServiceAlias *string `json:"serviceAlias,omitempty"` - // ContextualServiceEndpointPolicies - A collection of contextual service endpoint policy. - ContextualServiceEndpointPolicies *[]string `json:"contextualServiceEndpointPolicies,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceEndpointPolicyPropertiesFormat. -func (seppf ServiceEndpointPolicyPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if seppf.ServiceEndpointPolicyDefinitions != nil { - objectMap["serviceEndpointPolicyDefinitions"] = seppf.ServiceEndpointPolicyDefinitions - } - if seppf.ServiceAlias != nil { - objectMap["serviceAlias"] = seppf.ServiceAlias - } - if seppf.ContextualServiceEndpointPolicies != nil { - objectMap["contextualServiceEndpointPolicies"] = seppf.ContextualServiceEndpointPolicies - } - return json.Marshal(objectMap) -} - -// ServiceEndpointPropertiesFormat the service endpoint properties. -type ServiceEndpointPropertiesFormat struct { - // Service - The type of the endpoint service. - Service *string `json:"service,omitempty"` - // Locations - A list of locations. - Locations *[]string `json:"locations,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the service endpoint resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceEndpointPropertiesFormat. -func (sepf ServiceEndpointPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sepf.Service != nil { - objectMap["service"] = sepf.Service - } - if sepf.Locations != nil { - objectMap["locations"] = sepf.Locations - } - return json.Marshal(objectMap) -} - -// ServiceTagInformation the service tag information. -type ServiceTagInformation struct { - // Properties - READ-ONLY; Properties of the service tag information. - Properties *ServiceTagInformationPropertiesFormat `json:"properties,omitempty"` - // Name - READ-ONLY; The name of service tag. - Name *string `json:"name,omitempty"` - // ID - READ-ONLY; The ID of service tag. - ID *string `json:"id,omitempty"` - // ServiceTagChangeNumber - READ-ONLY; The iteration number of service tag object for region. - ServiceTagChangeNumber *string `json:"serviceTagChangeNumber,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceTagInformation. -func (sti ServiceTagInformation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ServiceTagInformationListResult response for Get ServiceTagInformation API service call. Retrieves the -// list of service tag information resources. -type ServiceTagInformationListResult struct { - autorest.Response `json:"-"` - // Value - The list of service tag information resources. - Value *[]ServiceTagInformation `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceTagInformationListResult. -func (stilr ServiceTagInformationListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if stilr.Value != nil { - objectMap["value"] = stilr.Value - } - return json.Marshal(objectMap) -} - -// ServiceTagInformationListResultIterator provides access to a complete listing of ServiceTagInformation -// values. -type ServiceTagInformationListResultIterator struct { - i int - page ServiceTagInformationListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ServiceTagInformationListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceTagInformationListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *ServiceTagInformationListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ServiceTagInformationListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ServiceTagInformationListResultIterator) Response() ServiceTagInformationListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ServiceTagInformationListResultIterator) Value() ServiceTagInformation { - if !iter.page.NotDone() { - return ServiceTagInformation{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the ServiceTagInformationListResultIterator type. -func NewServiceTagInformationListResultIterator(page ServiceTagInformationListResultPage) ServiceTagInformationListResultIterator { - return ServiceTagInformationListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (stilr ServiceTagInformationListResult) IsEmpty() bool { - return stilr.Value == nil || len(*stilr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (stilr ServiceTagInformationListResult) hasNextLink() bool { - return stilr.NextLink != nil && len(*stilr.NextLink) != 0 -} - -// serviceTagInformationListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (stilr ServiceTagInformationListResult) serviceTagInformationListResultPreparer(ctx context.Context) (*http.Request, error) { - if !stilr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(stilr.NextLink))) -} - -// ServiceTagInformationListResultPage contains a page of ServiceTagInformation values. -type ServiceTagInformationListResultPage struct { - fn func(context.Context, ServiceTagInformationListResult) (ServiceTagInformationListResult, error) - stilr ServiceTagInformationListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ServiceTagInformationListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceTagInformationListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.stilr) - if err != nil { - return err - } - page.stilr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *ServiceTagInformationListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ServiceTagInformationListResultPage) NotDone() bool { - return !page.stilr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ServiceTagInformationListResultPage) Response() ServiceTagInformationListResult { - return page.stilr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ServiceTagInformationListResultPage) Values() []ServiceTagInformation { - if page.stilr.IsEmpty() { - return nil - } - return *page.stilr.Value -} - -// Creates a new instance of the ServiceTagInformationListResultPage type. -func NewServiceTagInformationListResultPage(cur ServiceTagInformationListResult, getNextPage func(context.Context, ServiceTagInformationListResult) (ServiceTagInformationListResult, error)) ServiceTagInformationListResultPage { - return ServiceTagInformationListResultPage{ - fn: getNextPage, - stilr: cur, - } -} - -// ServiceTagInformationPropertiesFormat properties of the service tag information. -type ServiceTagInformationPropertiesFormat struct { - // ChangeNumber - READ-ONLY; The iteration number of service tag. - ChangeNumber *string `json:"changeNumber,omitempty"` - // Region - READ-ONLY; The region of service tag. - Region *string `json:"region,omitempty"` - // SystemService - READ-ONLY; The name of system service. - SystemService *string `json:"systemService,omitempty"` - // AddressPrefixes - READ-ONLY; The list of IP address prefixes. - AddressPrefixes *[]string `json:"addressPrefixes,omitempty"` - // State - READ-ONLY; The state of the service tag. - State *string `json:"state,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceTagInformationPropertiesFormat. -func (stipf ServiceTagInformationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// ServiceTagsListResult response for the ListServiceTags API service call. -type ServiceTagsListResult struct { - autorest.Response `json:"-"` - // Name - READ-ONLY; The name of the cloud. - Name *string `json:"name,omitempty"` - // ID - READ-ONLY; The ID of the cloud. - ID *string `json:"id,omitempty"` - // Type - READ-ONLY; The azure resource type. - Type *string `json:"type,omitempty"` - // ChangeNumber - READ-ONLY; The iteration number. - ChangeNumber *string `json:"changeNumber,omitempty"` - // Cloud - READ-ONLY; The name of the cloud. - Cloud *string `json:"cloud,omitempty"` - // Values - READ-ONLY; The list of service tag information resources. - Values *[]ServiceTagInformation `json:"values,omitempty"` - // NextLink - READ-ONLY; The URL to get next page of service tag information resources. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for ServiceTagsListResult. -func (stlr ServiceTagsListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// SessionIds list of session IDs. -type SessionIds struct { - // SessionIds - List of session IDs. - SessionIds *[]string `json:"sessionIds,omitempty"` -} - -// SignatureOverridesFilterValuesQuery describes the filter values possibles for a given column -type SignatureOverridesFilterValuesQuery struct { - // FilterName - Describes the name of the column which values will be returned - FilterName *string `json:"filterName,omitempty"` -} - -// SignatureOverridesFilterValuesResponse describes the list of all possible values for a specific filter -// value -type SignatureOverridesFilterValuesResponse struct { - autorest.Response `json:"-"` - // FilterValues - Describes the possible values - FilterValues *[]string `json:"filterValues,omitempty"` -} - -// SignaturesOverrides contains all specific policy signatures overrides for the IDPS -type SignaturesOverrides struct { - autorest.Response `json:"-"` - // Name - Contains the name of the resource (default) - Name *string `json:"name,omitempty"` - // ID - Will contain the resource id of the signature override resource - ID *string `json:"id,omitempty"` - // Type - Will contain the type of the resource: Microsoft.Network/firewallPolicies/intrusionDetectionSignaturesOverrides - Type *string `json:"type,omitempty"` - // Properties - Will contain the properties of the resource (the actual signature overrides) - Properties *SignaturesOverridesProperties `json:"properties,omitempty"` -} - -// SignaturesOverridesList describes an object containing an array with a single item -type SignaturesOverridesList struct { - autorest.Response `json:"-"` - // Value - Describes a list consisting exactly one item describing the policy's signature override status - Value *[]SignaturesOverrides `json:"value,omitempty"` -} - -// SignaturesOverridesProperties will contain the properties of the resource (the actual signature -// overrides) -type SignaturesOverridesProperties struct { - Signatures map[string]*string `json:"signatures"` -} - -// MarshalJSON is the custom marshaler for SignaturesOverridesProperties. -func (so SignaturesOverridesProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if so.Signatures != nil { - objectMap["signatures"] = so.Signatures - } - return json.Marshal(objectMap) -} - -// SingleQueryResult ... -type SingleQueryResult struct { - // SignatureID - The ID of the signature - SignatureID *int32 `json:"signatureId,omitempty"` - // Mode - The current mode enforced, 0 - Disabled, 1 - Alert, 2 -Deny - Mode *int32 `json:"mode,omitempty"` - // Severity - Describes the severity of signature: 1 - Low, 2 - Medium, 3 - High - Severity *int32 `json:"severity,omitempty"` - // Direction - Describes in which direction signature is being enforced: 0 - Inbound, 1 - OutBound, 2 - Bidirectional - Direction *int32 `json:"direction,omitempty"` - // Group - Describes the groups the signature belongs to - Group *string `json:"group,omitempty"` - // Description - Describes what is the signature enforces - Description *string `json:"description,omitempty"` - // Protocol - Describes the protocol the signatures is being enforced in - Protocol *string `json:"protocol,omitempty"` - // SourcePorts - Describes the list of source ports related to this signature - SourcePorts *[]string `json:"sourcePorts,omitempty"` - // DestinationPorts - Describes the list of destination ports related to this signature - DestinationPorts *[]string `json:"destinationPorts,omitempty"` - // LastUpdated - Describes the last updated time of the signature (provided from 3rd party vendor) - LastUpdated *string `json:"lastUpdated,omitempty"` - // InheritedFromParentPolicy - Describes if this override is inherited from base policy or not - InheritedFromParentPolicy *bool `json:"inheritedFromParentPolicy,omitempty"` -} - -// Sku the sku of this Bastion Host. -type Sku struct { - // Name - The name of this Bastion Host. Possible values include: 'BastionHostSkuNameBasic', 'BastionHostSkuNameStandard' - Name BastionHostSkuName `json:"name,omitempty"` -} - -// StaticMember staticMember Item. -type StaticMember struct { - autorest.Response `json:"-"` - // StaticMemberProperties - The Static Member properties - *StaticMemberProperties `json:"properties,omitempty"` - // SystemData - READ-ONLY; The system metadata related to this resource. - SystemData *SystemData `json:"systemData,omitempty"` - // ID - READ-ONLY; Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for StaticMember. -func (sm StaticMember) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sm.StaticMemberProperties != nil { - objectMap["properties"] = sm.StaticMemberProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for StaticMember struct. -func (sm *StaticMember) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var staticMemberProperties StaticMemberProperties - err = json.Unmarshal(*v, &staticMemberProperties) - if err != nil { - return err - } - sm.StaticMemberProperties = &staticMemberProperties - } - case "systemData": - if v != nil { - var systemData SystemData - err = json.Unmarshal(*v, &systemData) - if err != nil { - return err - } - sm.SystemData = &systemData - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - sm.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - sm.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - sm.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - sm.Etag = &etag - } - } - } - - return nil -} - -// StaticMemberListResult result of the request to list StaticMember. It contains a list of groups and a -// URL link to get the next set of results. -type StaticMemberListResult struct { - autorest.Response `json:"-"` - // Value - Gets a page of StaticMember - Value *[]StaticMember `json:"value,omitempty"` - // NextLink - Gets the URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// StaticMemberListResultIterator provides access to a complete listing of StaticMember values. -type StaticMemberListResultIterator struct { - i int - page StaticMemberListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *StaticMemberListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StaticMemberListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *StaticMemberListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter StaticMemberListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter StaticMemberListResultIterator) Response() StaticMemberListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter StaticMemberListResultIterator) Value() StaticMember { - if !iter.page.NotDone() { - return StaticMember{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the StaticMemberListResultIterator type. -func NewStaticMemberListResultIterator(page StaticMemberListResultPage) StaticMemberListResultIterator { - return StaticMemberListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (smlr StaticMemberListResult) IsEmpty() bool { - return smlr.Value == nil || len(*smlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (smlr StaticMemberListResult) hasNextLink() bool { - return smlr.NextLink != nil && len(*smlr.NextLink) != 0 -} - -// staticMemberListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (smlr StaticMemberListResult) staticMemberListResultPreparer(ctx context.Context) (*http.Request, error) { - if !smlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(smlr.NextLink))) -} - -// StaticMemberListResultPage contains a page of StaticMember values. -type StaticMemberListResultPage struct { - fn func(context.Context, StaticMemberListResult) (StaticMemberListResult, error) - smlr StaticMemberListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *StaticMemberListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StaticMemberListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.smlr) - if err != nil { - return err - } - page.smlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *StaticMemberListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page StaticMemberListResultPage) NotDone() bool { - return !page.smlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page StaticMemberListResultPage) Response() StaticMemberListResult { - return page.smlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page StaticMemberListResultPage) Values() []StaticMember { - if page.smlr.IsEmpty() { - return nil - } - return *page.smlr.Value -} - -// Creates a new instance of the StaticMemberListResultPage type. -func NewStaticMemberListResultPage(cur StaticMemberListResult, getNextPage func(context.Context, StaticMemberListResult) (StaticMemberListResult, error)) StaticMemberListResultPage { - return StaticMemberListResultPage{ - fn: getNextPage, - smlr: cur, - } -} - -// StaticMemberProperties properties of static member. -type StaticMemberProperties struct { - // ResourceID - Resource Id. - ResourceID *string `json:"resourceId,omitempty"` - // Region - READ-ONLY; Resource region. - Region *string `json:"region,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the scope assignment resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for StaticMemberProperties. -func (smp StaticMemberProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if smp.ResourceID != nil { - objectMap["resourceId"] = smp.ResourceID - } - return json.Marshal(objectMap) -} - -// StaticRoute list of all Static Routes. -type StaticRoute struct { - // Name - The name of the StaticRoute that is unique within a VnetRoute. - Name *string `json:"name,omitempty"` - // AddressPrefixes - List of all address prefixes. - AddressPrefixes *[]string `json:"addressPrefixes,omitempty"` - // NextHopIPAddress - The ip address of the next hop. - NextHopIPAddress *string `json:"nextHopIpAddress,omitempty"` -} - -// StaticRoutesConfig configuration for static routes on this HubVnetConnectionConfiguration for static -// routes on this HubVnetConnection. -type StaticRoutesConfig struct { - // PropagateStaticRoutes - READ-ONLY; Boolean indicating whether static routes on this connection are automatically propagate to route tables which this connection propagates to. - PropagateStaticRoutes *bool `json:"propagateStaticRoutes,omitempty"` - // VnetLocalRouteOverrideCriteria - Parameter determining whether NVA in spoke vnet is bypassed for traffic with destination in spoke. Possible values include: 'VnetLocalRouteOverrideCriteriaContains', 'VnetLocalRouteOverrideCriteriaEqual' - VnetLocalRouteOverrideCriteria VnetLocalRouteOverrideCriteria `json:"vnetLocalRouteOverrideCriteria,omitempty"` -} - -// MarshalJSON is the custom marshaler for StaticRoutesConfig. -func (src StaticRoutesConfig) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if src.VnetLocalRouteOverrideCriteria != "" { - objectMap["vnetLocalRouteOverrideCriteria"] = src.VnetLocalRouteOverrideCriteria - } - return json.Marshal(objectMap) -} - -// String ... -type String struct { - autorest.Response `json:"-"` - Value *string `json:"value,omitempty"` -} - -// Subnet subnet in a virtual network resource. -type Subnet struct { - autorest.Response `json:"-"` - // SubnetPropertiesFormat - Properties of the subnet. - *SubnetPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for Subnet. -func (s Subnet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if s.SubnetPropertiesFormat != nil { - objectMap["properties"] = s.SubnetPropertiesFormat - } - if s.Name != nil { - objectMap["name"] = s.Name - } - if s.Type != nil { - objectMap["type"] = s.Type - } - if s.ID != nil { - objectMap["id"] = s.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Subnet struct. -func (s *Subnet) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var subnetPropertiesFormat SubnetPropertiesFormat - err = json.Unmarshal(*v, &subnetPropertiesFormat) - if err != nil { - return err - } - s.SubnetPropertiesFormat = &subnetPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - s.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - s.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - s.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - s.ID = &ID - } - } - } - - return nil -} - -// SubnetAssociation subnet and it's custom security rules. -type SubnetAssociation struct { - // ID - READ-ONLY; Subnet ID. - ID *string `json:"id,omitempty"` - // SecurityRules - Collection of custom security rules. - SecurityRules *[]SecurityRule `json:"securityRules,omitempty"` -} - -// MarshalJSON is the custom marshaler for SubnetAssociation. -func (sa SubnetAssociation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sa.SecurityRules != nil { - objectMap["securityRules"] = sa.SecurityRules - } - return json.Marshal(objectMap) -} - -// SubnetListResult response for ListSubnets API service callRetrieves all subnet that belongs to a virtual -// network. -type SubnetListResult struct { - autorest.Response `json:"-"` - // Value - The subnets in a virtual network. - Value *[]Subnet `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// SubnetListResultIterator provides access to a complete listing of Subnet values. -type SubnetListResultIterator struct { - i int - page SubnetListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *SubnetListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SubnetListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter SubnetListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter SubnetListResultIterator) Response() SubnetListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter SubnetListResultIterator) Value() Subnet { - if !iter.page.NotDone() { - return Subnet{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the SubnetListResultIterator type. -func NewSubnetListResultIterator(page SubnetListResultPage) SubnetListResultIterator { - return SubnetListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (slr SubnetListResult) IsEmpty() bool { - return slr.Value == nil || len(*slr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (slr SubnetListResult) hasNextLink() bool { - return slr.NextLink != nil && len(*slr.NextLink) != 0 -} - -// subnetListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (slr SubnetListResult) subnetListResultPreparer(ctx context.Context) (*http.Request, error) { - if !slr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(slr.NextLink))) -} - -// SubnetListResultPage contains a page of Subnet values. -type SubnetListResultPage struct { - fn func(context.Context, SubnetListResult) (SubnetListResult, error) - slr SubnetListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SubnetListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.slr) - if err != nil { - return err - } - page.slr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SubnetListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page SubnetListResultPage) NotDone() bool { - return !page.slr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page SubnetListResultPage) Response() SubnetListResult { - return page.slr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page SubnetListResultPage) Values() []Subnet { - if page.slr.IsEmpty() { - return nil - } - return *page.slr.Value -} - -// Creates a new instance of the SubnetListResultPage type. -func NewSubnetListResultPage(cur SubnetListResult, getNextPage func(context.Context, SubnetListResult) (SubnetListResult, error)) SubnetListResultPage { - return SubnetListResultPage{ - fn: getNextPage, - slr: cur, - } -} - -// SubnetPropertiesFormat properties of the subnet. -type SubnetPropertiesFormat struct { - // AddressPrefix - The address prefix for the subnet. - AddressPrefix *string `json:"addressPrefix,omitempty"` - // AddressPrefixes - List of address prefixes for the subnet. - AddressPrefixes *[]string `json:"addressPrefixes,omitempty"` - // NetworkSecurityGroup - The reference to the NetworkSecurityGroup resource. - NetworkSecurityGroup *SecurityGroup `json:"networkSecurityGroup,omitempty"` - // RouteTable - The reference to the RouteTable resource. - RouteTable *RouteTable `json:"routeTable,omitempty"` - // NatGateway - Nat gateway associated with this subnet. - NatGateway *SubResource `json:"natGateway,omitempty"` - // ServiceEndpoints - An array of service endpoints. - ServiceEndpoints *[]ServiceEndpointPropertiesFormat `json:"serviceEndpoints,omitempty"` - // ServiceEndpointPolicies - An array of service endpoint policies. - ServiceEndpointPolicies *[]ServiceEndpointPolicy `json:"serviceEndpointPolicies,omitempty"` - // PrivateEndpoints - READ-ONLY; An array of references to private endpoints. - PrivateEndpoints *[]PrivateEndpoint `json:"privateEndpoints,omitempty"` - // IPConfigurations - READ-ONLY; An array of references to the network interface IP configurations using subnet. - IPConfigurations *[]IPConfiguration `json:"ipConfigurations,omitempty"` - // IPConfigurationProfiles - READ-ONLY; Array of IP configuration profiles which reference this subnet. - IPConfigurationProfiles *[]IPConfigurationProfile `json:"ipConfigurationProfiles,omitempty"` - // IPAllocations - Array of IpAllocation which reference this subnet. - IPAllocations *[]SubResource `json:"ipAllocations,omitempty"` - // ResourceNavigationLinks - READ-ONLY; An array of references to the external resources using subnet. - ResourceNavigationLinks *[]ResourceNavigationLink `json:"resourceNavigationLinks,omitempty"` - // ServiceAssociationLinks - READ-ONLY; An array of references to services injecting into this subnet. - ServiceAssociationLinks *[]ServiceAssociationLink `json:"serviceAssociationLinks,omitempty"` - // Delegations - An array of references to the delegations on the subnet. - Delegations *[]Delegation `json:"delegations,omitempty"` - // Purpose - READ-ONLY; A read-only string identifying the intention of use for this subnet based on delegations and other user-defined properties. - Purpose *string `json:"purpose,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the subnet resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // PrivateEndpointNetworkPolicies - Enable or Disable apply network policies on private end point in the subnet. Possible values include: 'VirtualNetworkPrivateEndpointNetworkPoliciesEnabled', 'VirtualNetworkPrivateEndpointNetworkPoliciesDisabled' - PrivateEndpointNetworkPolicies VirtualNetworkPrivateEndpointNetworkPolicies `json:"privateEndpointNetworkPolicies,omitempty"` - // PrivateLinkServiceNetworkPolicies - Enable or Disable apply network policies on private link service in the subnet. Possible values include: 'VirtualNetworkPrivateLinkServiceNetworkPoliciesEnabled', 'VirtualNetworkPrivateLinkServiceNetworkPoliciesDisabled' - PrivateLinkServiceNetworkPolicies VirtualNetworkPrivateLinkServiceNetworkPolicies `json:"privateLinkServiceNetworkPolicies,omitempty"` - // ApplicationGatewayIPConfigurations - Application gateway IP configurations of virtual network resource. - ApplicationGatewayIPConfigurations *[]ApplicationGatewayIPConfiguration `json:"applicationGatewayIpConfigurations,omitempty"` -} - -// MarshalJSON is the custom marshaler for SubnetPropertiesFormat. -func (spf SubnetPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if spf.AddressPrefix != nil { - objectMap["addressPrefix"] = spf.AddressPrefix - } - if spf.AddressPrefixes != nil { - objectMap["addressPrefixes"] = spf.AddressPrefixes - } - if spf.NetworkSecurityGroup != nil { - objectMap["networkSecurityGroup"] = spf.NetworkSecurityGroup - } - if spf.RouteTable != nil { - objectMap["routeTable"] = spf.RouteTable - } - if spf.NatGateway != nil { - objectMap["natGateway"] = spf.NatGateway - } - if spf.ServiceEndpoints != nil { - objectMap["serviceEndpoints"] = spf.ServiceEndpoints - } - if spf.ServiceEndpointPolicies != nil { - objectMap["serviceEndpointPolicies"] = spf.ServiceEndpointPolicies - } - if spf.IPAllocations != nil { - objectMap["ipAllocations"] = spf.IPAllocations - } - if spf.Delegations != nil { - objectMap["delegations"] = spf.Delegations - } - if spf.PrivateEndpointNetworkPolicies != "" { - objectMap["privateEndpointNetworkPolicies"] = spf.PrivateEndpointNetworkPolicies - } - if spf.PrivateLinkServiceNetworkPolicies != "" { - objectMap["privateLinkServiceNetworkPolicies"] = spf.PrivateLinkServiceNetworkPolicies - } - if spf.ApplicationGatewayIPConfigurations != nil { - objectMap["applicationGatewayIpConfigurations"] = spf.ApplicationGatewayIPConfigurations - } - return json.Marshal(objectMap) -} - -// SubnetsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SubnetsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SubnetsClient) (Subnet, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SubnetsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SubnetsCreateOrUpdateFuture.Result. -func (future *SubnetsCreateOrUpdateFuture) result(client SubnetsClient) (s Subnet, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SubnetsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.CreateOrUpdateResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsCreateOrUpdateFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// SubnetsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type SubnetsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SubnetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SubnetsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SubnetsDeleteFuture.Result. -func (future *SubnetsDeleteFuture) result(client SubnetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SubnetsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// SubnetsPrepareNetworkPoliciesFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type SubnetsPrepareNetworkPoliciesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SubnetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SubnetsPrepareNetworkPoliciesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SubnetsPrepareNetworkPoliciesFuture.Result. -func (future *SubnetsPrepareNetworkPoliciesFuture) result(client SubnetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsPrepareNetworkPoliciesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SubnetsPrepareNetworkPoliciesFuture") - return - } - ar.Response = future.Response() - return -} - -// SubnetsUnprepareNetworkPoliciesFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type SubnetsUnprepareNetworkPoliciesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(SubnetsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *SubnetsUnprepareNetworkPoliciesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for SubnetsUnprepareNetworkPoliciesFuture.Result. -func (future *SubnetsUnprepareNetworkPoliciesFuture) result(client SubnetsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsUnprepareNetworkPoliciesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.SubnetsUnprepareNetworkPoliciesFuture") - return - } - ar.Response = future.Response() - return -} - -// SubResource reference to another subresource. -type SubResource struct { - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// SwapResource swapResource to represent slot type on the specified cloud service. -type SwapResource struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; Resource Id. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - Properties *SwapResourceProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for SwapResource. -func (sr SwapResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sr.Properties != nil { - objectMap["properties"] = sr.Properties - } - return json.Marshal(objectMap) -} - -// SwapResourceListResult swapResource List with single entry to represent slot type on the specified cloud -// service. -type SwapResourceListResult struct { - autorest.Response `json:"-"` - Value *[]SwapResource `json:"value,omitempty"` -} - -// SwapResourceProperties swap resource properties -type SwapResourceProperties struct { - // SlotType - Specifies slot info on a cloud service. Possible values include: 'Production', 'Staging' - SlotType SlotType `json:"slotType,omitempty"` -} - -// SystemData metadata pertaining to creation and last modification of the resource. -type SystemData struct { - // CreatedBy - The identity that created the resource. - CreatedBy *string `json:"createdBy,omitempty"` - // CreatedByType - The type of identity that created the resource. Possible values include: 'User', 'Application', 'ManagedIdentity', 'Key' - CreatedByType CreatedByType `json:"createdByType,omitempty"` - // CreatedAt - The timestamp of resource creation (UTC). - CreatedAt *date.Time `json:"createdAt,omitempty"` - // LastModifiedBy - The identity that last modified the resource. - LastModifiedBy *string `json:"lastModifiedBy,omitempty"` - // LastModifiedByType - The type of identity that last modified the resource. Possible values include: 'User', 'Application', 'ManagedIdentity', 'Key' - LastModifiedByType CreatedByType `json:"lastModifiedByType,omitempty"` - // LastModifiedAt - The type of identity that last modified the resource. - LastModifiedAt *date.Time `json:"lastModifiedAt,omitempty"` -} - -// TagsObject tags object for patch operations. -type TagsObject struct { - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for TagsObject. -func (toVar TagsObject) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if toVar.Tags != nil { - objectMap["tags"] = toVar.Tags - } - return json.Marshal(objectMap) -} - -// Topology topology of the specified resource group. -type Topology struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; GUID representing the operation id. - ID *string `json:"id,omitempty"` - // CreatedDateTime - READ-ONLY; The datetime when the topology was initially created for the resource group. - CreatedDateTime *date.Time `json:"createdDateTime,omitempty"` - // LastModified - READ-ONLY; The datetime when the topology was last modified. - LastModified *date.Time `json:"lastModified,omitempty"` - // Resources - A list of topology resources. - Resources *[]TopologyResource `json:"resources,omitempty"` -} - -// MarshalJSON is the custom marshaler for Topology. -func (t Topology) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if t.Resources != nil { - objectMap["resources"] = t.Resources - } - return json.Marshal(objectMap) -} - -// TopologyAssociation resources that have an association with the parent resource. -type TopologyAssociation struct { - // Name - The name of the resource that is associated with the parent resource. - Name *string `json:"name,omitempty"` - // ResourceID - The ID of the resource that is associated with the parent resource. - ResourceID *string `json:"resourceId,omitempty"` - // AssociationType - The association type of the child resource to the parent resource. Possible values include: 'Associated', 'Contains' - AssociationType AssociationType `json:"associationType,omitempty"` -} - -// TopologyParameters parameters that define the representation of topology. -type TopologyParameters struct { - // TargetResourceGroupName - The name of the target resource group to perform topology on. - TargetResourceGroupName *string `json:"targetResourceGroupName,omitempty"` - // TargetVirtualNetwork - The reference to the Virtual Network resource. - TargetVirtualNetwork *SubResource `json:"targetVirtualNetwork,omitempty"` - // TargetSubnet - The reference to the Subnet resource. - TargetSubnet *SubResource `json:"targetSubnet,omitempty"` -} - -// TopologyResource the network resource topology information for the given resource group. -type TopologyResource struct { - // Name - Name of the resource. - Name *string `json:"name,omitempty"` - // ID - ID of the resource. - ID *string `json:"id,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Associations - Holds the associations the resource has with other resources in the resource group. - Associations *[]TopologyAssociation `json:"associations,omitempty"` -} - -// TrafficAnalyticsConfigurationProperties parameters that define the configuration of traffic analytics. -type TrafficAnalyticsConfigurationProperties struct { - // Enabled - Flag to enable/disable traffic analytics. - Enabled *bool `json:"enabled,omitempty"` - // WorkspaceID - The resource guid of the attached workspace. - WorkspaceID *string `json:"workspaceId,omitempty"` - // WorkspaceRegion - The location of the attached workspace. - WorkspaceRegion *string `json:"workspaceRegion,omitempty"` - // WorkspaceResourceID - Resource Id of the attached workspace. - WorkspaceResourceID *string `json:"workspaceResourceId,omitempty"` - // TrafficAnalyticsInterval - The interval in minutes which would decide how frequently TA service should do flow analytics. - TrafficAnalyticsInterval *int32 `json:"trafficAnalyticsInterval,omitempty"` -} - -// TrafficAnalyticsProperties parameters that define the configuration of traffic analytics. -type TrafficAnalyticsProperties struct { - // NetworkWatcherFlowAnalyticsConfiguration - Parameters that define the configuration of traffic analytics. - NetworkWatcherFlowAnalyticsConfiguration *TrafficAnalyticsConfigurationProperties `json:"networkWatcherFlowAnalyticsConfiguration,omitempty"` -} - -// TrafficSelectorPolicy an traffic selector policy for a virtual network gateway connection. -type TrafficSelectorPolicy struct { - // LocalAddressRanges - A collection of local address spaces in CIDR format. - LocalAddressRanges *[]string `json:"localAddressRanges,omitempty"` - // RemoteAddressRanges - A collection of remote address spaces in CIDR format. - RemoteAddressRanges *[]string `json:"remoteAddressRanges,omitempty"` -} - -// TroubleshootingDetails information gained from troubleshooting of specified resource. -type TroubleshootingDetails struct { - // ID - The id of the get troubleshoot operation. - ID *string `json:"id,omitempty"` - // ReasonType - Reason type of failure. - ReasonType *string `json:"reasonType,omitempty"` - // Summary - A summary of troubleshooting. - Summary *string `json:"summary,omitempty"` - // Detail - Details on troubleshooting results. - Detail *string `json:"detail,omitempty"` - // RecommendedActions - List of recommended actions. - RecommendedActions *[]TroubleshootingRecommendedActions `json:"recommendedActions,omitempty"` -} - -// TroubleshootingParameters parameters that define the resource to troubleshoot. -type TroubleshootingParameters struct { - // TargetResourceID - The target resource to troubleshoot. - TargetResourceID *string `json:"targetResourceId,omitempty"` - // TroubleshootingProperties - Properties of the troubleshooting resource. - *TroubleshootingProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for TroubleshootingParameters. -func (tp TroubleshootingParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if tp.TargetResourceID != nil { - objectMap["targetResourceId"] = tp.TargetResourceID - } - if tp.TroubleshootingProperties != nil { - objectMap["properties"] = tp.TroubleshootingProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for TroubleshootingParameters struct. -func (tp *TroubleshootingParameters) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "targetResourceId": - if v != nil { - var targetResourceID string - err = json.Unmarshal(*v, &targetResourceID) - if err != nil { - return err - } - tp.TargetResourceID = &targetResourceID - } - case "properties": - if v != nil { - var troubleshootingProperties TroubleshootingProperties - err = json.Unmarshal(*v, &troubleshootingProperties) - if err != nil { - return err - } - tp.TroubleshootingProperties = &troubleshootingProperties - } - } - } - - return nil -} - -// TroubleshootingProperties storage location provided for troubleshoot. -type TroubleshootingProperties struct { - // StorageID - The ID for the storage account to save the troubleshoot result. - StorageID *string `json:"storageId,omitempty"` - // StoragePath - The path to the blob to save the troubleshoot result in. - StoragePath *string `json:"storagePath,omitempty"` -} - -// TroubleshootingRecommendedActions recommended actions based on discovered issues. -type TroubleshootingRecommendedActions struct { - // ActionID - ID of the recommended action. - ActionID *string `json:"actionId,omitempty"` - // ActionText - Description of recommended actions. - ActionText *string `json:"actionText,omitempty"` - // ActionURI - The uri linking to a documentation for the recommended troubleshooting actions. - ActionURI *string `json:"actionUri,omitempty"` - // ActionURIText - The information from the URI for the recommended troubleshooting actions. - ActionURIText *string `json:"actionUriText,omitempty"` -} - -// TroubleshootingResult troubleshooting information gained from specified resource. -type TroubleshootingResult struct { - autorest.Response `json:"-"` - // StartTime - The start time of the troubleshooting. - StartTime *date.Time `json:"startTime,omitempty"` - // EndTime - The end time of the troubleshooting. - EndTime *date.Time `json:"endTime,omitempty"` - // Code - The result code of the troubleshooting. - Code *string `json:"code,omitempty"` - // Results - Information from troubleshooting. - Results *[]TroubleshootingDetails `json:"results,omitempty"` -} - -// TunnelConnectionHealth virtualNetworkGatewayConnection properties. -type TunnelConnectionHealth struct { - // Tunnel - READ-ONLY; Tunnel name. - Tunnel *string `json:"tunnel,omitempty"` - // ConnectionStatus - READ-ONLY; Virtual Network Gateway connection status. Possible values include: 'VirtualNetworkGatewayConnectionStatusUnknown', 'VirtualNetworkGatewayConnectionStatusConnecting', 'VirtualNetworkGatewayConnectionStatusConnected', 'VirtualNetworkGatewayConnectionStatusNotConnected' - ConnectionStatus VirtualNetworkGatewayConnectionStatus `json:"connectionStatus,omitempty"` - // IngressBytesTransferred - READ-ONLY; The Ingress Bytes Transferred in this connection. - IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` - // EgressBytesTransferred - READ-ONLY; The Egress Bytes Transferred in this connection. - EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` - // LastConnectionEstablishedUtcTime - READ-ONLY; The time at which connection was established in Utc format. - LastConnectionEstablishedUtcTime *string `json:"lastConnectionEstablishedUtcTime,omitempty"` -} - -// MarshalJSON is the custom marshaler for TunnelConnectionHealth. -func (tch TunnelConnectionHealth) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// UnprepareNetworkPoliciesRequest details of UnprepareNetworkPolicies for Subnet. -type UnprepareNetworkPoliciesRequest struct { - // ServiceName - The name of the service for which subnet is being unprepared for. - ServiceName *string `json:"serviceName,omitempty"` -} - -// Usage the network resource usage. -type Usage struct { - // ID - READ-ONLY; Resource identifier. - ID *string `json:"id,omitempty"` - // Unit - An enum describing the unit of measurement. - Unit *string `json:"unit,omitempty"` - // CurrentValue - The current value of the usage. - CurrentValue *int64 `json:"currentValue,omitempty"` - // Limit - The limit of usage. - Limit *int64 `json:"limit,omitempty"` - // Name - The name of the type of usage. - Name *UsageName `json:"name,omitempty"` -} - -// MarshalJSON is the custom marshaler for Usage. -func (u Usage) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if u.Unit != nil { - objectMap["unit"] = u.Unit - } - if u.CurrentValue != nil { - objectMap["currentValue"] = u.CurrentValue - } - if u.Limit != nil { - objectMap["limit"] = u.Limit - } - if u.Name != nil { - objectMap["name"] = u.Name - } - return json.Marshal(objectMap) -} - -// UsageName the usage names. -type UsageName struct { - // Value - A string describing the resource name. - Value *string `json:"value,omitempty"` - // LocalizedValue - A localized string describing the resource name. - LocalizedValue *string `json:"localizedValue,omitempty"` -} - -// UsagesListResult the list usages operation response. -type UsagesListResult struct { - autorest.Response `json:"-"` - // Value - The list network resource usages. - Value *[]Usage `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// UsagesListResultIterator provides access to a complete listing of Usage values. -type UsagesListResultIterator struct { - i int - page UsagesListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *UsagesListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/UsagesListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *UsagesListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter UsagesListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter UsagesListResultIterator) Response() UsagesListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter UsagesListResultIterator) Value() Usage { - if !iter.page.NotDone() { - return Usage{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the UsagesListResultIterator type. -func NewUsagesListResultIterator(page UsagesListResultPage) UsagesListResultIterator { - return UsagesListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (ulr UsagesListResult) IsEmpty() bool { - return ulr.Value == nil || len(*ulr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (ulr UsagesListResult) hasNextLink() bool { - return ulr.NextLink != nil && len(*ulr.NextLink) != 0 -} - -// usagesListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (ulr UsagesListResult) usagesListResultPreparer(ctx context.Context) (*http.Request, error) { - if !ulr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(ulr.NextLink))) -} - -// UsagesListResultPage contains a page of Usage values. -type UsagesListResultPage struct { - fn func(context.Context, UsagesListResult) (UsagesListResult, error) - ulr UsagesListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *UsagesListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/UsagesListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.ulr) - if err != nil { - return err - } - page.ulr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *UsagesListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page UsagesListResultPage) NotDone() bool { - return !page.ulr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page UsagesListResultPage) Response() UsagesListResult { - return page.ulr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page UsagesListResultPage) Values() []Usage { - if page.ulr.IsEmpty() { - return nil - } - return *page.ulr.Value -} - -// Creates a new instance of the UsagesListResultPage type. -func NewUsagesListResultPage(cur UsagesListResult, getNextPage func(context.Context, UsagesListResult) (UsagesListResult, error)) UsagesListResultPage { - return UsagesListResultPage{ - fn: getNextPage, - ulr: cur, - } -} - -// VerificationIPFlowParameters parameters that define the IP flow to be verified. -type VerificationIPFlowParameters struct { - // TargetResourceID - The ID of the target resource to perform next-hop on. - TargetResourceID *string `json:"targetResourceId,omitempty"` - // Direction - The direction of the packet represented as a 5-tuple. Possible values include: 'Inbound', 'Outbound' - Direction Direction `json:"direction,omitempty"` - // Protocol - Protocol to be verified on. Possible values include: 'IPFlowProtocolTCP', 'IPFlowProtocolUDP' - Protocol IPFlowProtocol `json:"protocol,omitempty"` - // LocalPort - The local port. Acceptable values are a single integer in the range (0-65535). Support for * for the source port, which depends on the direction. - LocalPort *string `json:"localPort,omitempty"` - // RemotePort - The remote port. Acceptable values are a single integer in the range (0-65535). Support for * for the source port, which depends on the direction. - RemotePort *string `json:"remotePort,omitempty"` - // LocalIPAddress - The local IP address. Acceptable values are valid IPv4 addresses. - LocalIPAddress *string `json:"localIPAddress,omitempty"` - // RemoteIPAddress - The remote IP address. Acceptable values are valid IPv4 addresses. - RemoteIPAddress *string `json:"remoteIPAddress,omitempty"` - // TargetNicResourceID - The NIC ID. (If VM has multiple NICs and IP forwarding is enabled on any of them, then this parameter must be specified. Otherwise optional). - TargetNicResourceID *string `json:"targetNicResourceId,omitempty"` -} - -// VerificationIPFlowResult results of IP flow verification on the target resource. -type VerificationIPFlowResult struct { - autorest.Response `json:"-"` - // Access - Indicates whether the traffic is allowed or denied. Possible values include: 'Allow', 'Deny' - Access Access `json:"access,omitempty"` - // RuleName - Name of the rule. If input is not matched against any security rule, it is not displayed. - RuleName *string `json:"ruleName,omitempty"` -} - -// VipSwapCreateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VipSwapCreateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VipSwapClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VipSwapCreateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VipSwapCreateFuture.Result. -func (future *VipSwapCreateFuture) result(client VipSwapClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VipSwapCreateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VipSwapCreateFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualAppliance networkVirtualAppliance Resource. -type VirtualAppliance struct { - autorest.Response `json:"-"` - // VirtualAppliancePropertiesFormat - Properties of the Network Virtual Appliance. - *VirtualAppliancePropertiesFormat `json:"properties,omitempty"` - // Identity - The service principal that has read access to cloud-init and config blob. - Identity *ManagedServiceIdentity `json:"identity,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualAppliance. -func (va VirtualAppliance) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if va.VirtualAppliancePropertiesFormat != nil { - objectMap["properties"] = va.VirtualAppliancePropertiesFormat - } - if va.Identity != nil { - objectMap["identity"] = va.Identity - } - if va.ID != nil { - objectMap["id"] = va.ID - } - if va.Location != nil { - objectMap["location"] = va.Location - } - if va.Tags != nil { - objectMap["tags"] = va.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualAppliance struct. -func (va *VirtualAppliance) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualAppliancePropertiesFormat VirtualAppliancePropertiesFormat - err = json.Unmarshal(*v, &virtualAppliancePropertiesFormat) - if err != nil { - return err - } - va.VirtualAppliancePropertiesFormat = &virtualAppliancePropertiesFormat - } - case "identity": - if v != nil { - var identity ManagedServiceIdentity - err = json.Unmarshal(*v, &identity) - if err != nil { - return err - } - va.Identity = &identity - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - va.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - va.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - va.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - va.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - va.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - va.Tags = tags - } - } - } - - return nil -} - -// VirtualApplianceListResult response for ListNetworkVirtualAppliances API service call. -type VirtualApplianceListResult struct { - autorest.Response `json:"-"` - // Value - List of Network Virtual Appliances. - Value *[]VirtualAppliance `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualApplianceListResultIterator provides access to a complete listing of VirtualAppliance values. -type VirtualApplianceListResultIterator struct { - i int - page VirtualApplianceListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualApplianceListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualApplianceListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualApplianceListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualApplianceListResultIterator) Response() VirtualApplianceListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualApplianceListResultIterator) Value() VirtualAppliance { - if !iter.page.NotDone() { - return VirtualAppliance{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualApplianceListResultIterator type. -func NewVirtualApplianceListResultIterator(page VirtualApplianceListResultPage) VirtualApplianceListResultIterator { - return VirtualApplianceListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (valr VirtualApplianceListResult) IsEmpty() bool { - return valr.Value == nil || len(*valr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (valr VirtualApplianceListResult) hasNextLink() bool { - return valr.NextLink != nil && len(*valr.NextLink) != 0 -} - -// virtualApplianceListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (valr VirtualApplianceListResult) virtualApplianceListResultPreparer(ctx context.Context) (*http.Request, error) { - if !valr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(valr.NextLink))) -} - -// VirtualApplianceListResultPage contains a page of VirtualAppliance values. -type VirtualApplianceListResultPage struct { - fn func(context.Context, VirtualApplianceListResult) (VirtualApplianceListResult, error) - valr VirtualApplianceListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualApplianceListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.valr) - if err != nil { - return err - } - page.valr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualApplianceListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualApplianceListResultPage) NotDone() bool { - return !page.valr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualApplianceListResultPage) Response() VirtualApplianceListResult { - return page.valr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualApplianceListResultPage) Values() []VirtualAppliance { - if page.valr.IsEmpty() { - return nil - } - return *page.valr.Value -} - -// Creates a new instance of the VirtualApplianceListResultPage type. -func NewVirtualApplianceListResultPage(cur VirtualApplianceListResult, getNextPage func(context.Context, VirtualApplianceListResult) (VirtualApplianceListResult, error)) VirtualApplianceListResultPage { - return VirtualApplianceListResultPage{ - fn: getNextPage, - valr: cur, - } -} - -// VirtualApplianceNicProperties network Virtual Appliance NIC properties. -type VirtualApplianceNicProperties struct { - // Name - READ-ONLY; NIC name. - Name *string `json:"name,omitempty"` - // PublicIPAddress - READ-ONLY; Public IP address. - PublicIPAddress *string `json:"publicIpAddress,omitempty"` - // PrivateIPAddress - READ-ONLY; Private IP address. - PrivateIPAddress *string `json:"privateIpAddress,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualApplianceNicProperties. -func (vanp VirtualApplianceNicProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualAppliancePropertiesFormat network Virtual Appliance definition. -type VirtualAppliancePropertiesFormat struct { - // NvaSku - Network Virtual Appliance SKU. - NvaSku *VirtualApplianceSkuProperties `json:"nvaSku,omitempty"` - // AddressPrefix - READ-ONLY; Address Prefix. - AddressPrefix *string `json:"addressPrefix,omitempty"` - // BootStrapConfigurationBlobs - BootStrapConfigurationBlobs storage URLs. - BootStrapConfigurationBlobs *[]string `json:"bootStrapConfigurationBlobs,omitempty"` - // VirtualHub - The Virtual Hub where Network Virtual Appliance is being deployed. - VirtualHub *SubResource `json:"virtualHub,omitempty"` - // CloudInitConfigurationBlobs - CloudInitConfigurationBlob storage URLs. - CloudInitConfigurationBlobs *[]string `json:"cloudInitConfigurationBlobs,omitempty"` - // CloudInitConfiguration - CloudInitConfiguration string in plain text. - CloudInitConfiguration *string `json:"cloudInitConfiguration,omitempty"` - // VirtualApplianceAsn - VirtualAppliance ASN. Microsoft private, public and IANA reserved ASN are not supported. - VirtualApplianceAsn *int64 `json:"virtualApplianceAsn,omitempty"` - // SSHPublicKey - Public key for SSH login. - SSHPublicKey *string `json:"sshPublicKey,omitempty"` - // VirtualApplianceNics - READ-ONLY; List of Virtual Appliance Network Interfaces. - VirtualApplianceNics *[]VirtualApplianceNicProperties `json:"virtualApplianceNics,omitempty"` - // VirtualApplianceSites - READ-ONLY; List of references to VirtualApplianceSite. - VirtualApplianceSites *[]SubResource `json:"virtualApplianceSites,omitempty"` - // InboundSecurityRules - READ-ONLY; List of references to InboundSecurityRules. - InboundSecurityRules *[]SubResource `json:"inboundSecurityRules,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // DeploymentType - READ-ONLY; The deployment type. PartnerManaged for the SaaS NVA - DeploymentType *string `json:"deploymentType,omitempty"` - // Delegation - The delegation for the Virtual Appliance - Delegation *DelegationProperties `json:"delegation,omitempty"` - // PartnerManagedResource - The delegation for the Virtual Appliance - PartnerManagedResource *PartnerManagedResourceProperties `json:"partnerManagedResource,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualAppliancePropertiesFormat. -func (vapf VirtualAppliancePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vapf.NvaSku != nil { - objectMap["nvaSku"] = vapf.NvaSku - } - if vapf.BootStrapConfigurationBlobs != nil { - objectMap["bootStrapConfigurationBlobs"] = vapf.BootStrapConfigurationBlobs - } - if vapf.VirtualHub != nil { - objectMap["virtualHub"] = vapf.VirtualHub - } - if vapf.CloudInitConfigurationBlobs != nil { - objectMap["cloudInitConfigurationBlobs"] = vapf.CloudInitConfigurationBlobs - } - if vapf.CloudInitConfiguration != nil { - objectMap["cloudInitConfiguration"] = vapf.CloudInitConfiguration - } - if vapf.VirtualApplianceAsn != nil { - objectMap["virtualApplianceAsn"] = vapf.VirtualApplianceAsn - } - if vapf.SSHPublicKey != nil { - objectMap["sshPublicKey"] = vapf.SSHPublicKey - } - if vapf.Delegation != nil { - objectMap["delegation"] = vapf.Delegation - } - if vapf.PartnerManagedResource != nil { - objectMap["partnerManagedResource"] = vapf.PartnerManagedResource - } - return json.Marshal(objectMap) -} - -// VirtualAppliancesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualAppliancesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualAppliancesClient) (VirtualAppliance, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualAppliancesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualAppliancesCreateOrUpdateFuture.Result. -func (future *VirtualAppliancesCreateOrUpdateFuture) result(client VirtualAppliancesClient) (va VirtualAppliance, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - va.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualAppliancesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if va.Response.Response, err = future.GetResult(sender); err == nil && va.Response.Response.StatusCode != http.StatusNoContent { - va, err = client.CreateOrUpdateResponder(va.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesCreateOrUpdateFuture", "Result", va.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualAppliancesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualAppliancesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualAppliancesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualAppliancesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualAppliancesDeleteFuture.Result. -func (future *VirtualAppliancesDeleteFuture) result(client VirtualAppliancesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualAppliancesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualApplianceSite virtual Appliance Site resource. -type VirtualApplianceSite struct { - autorest.Response `json:"-"` - // VirtualApplianceSiteProperties - The properties of the Virtual Appliance Sites. - *VirtualApplianceSiteProperties `json:"properties,omitempty"` - // Name - Name of the virtual appliance site. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Site type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualApplianceSite. -func (vas VirtualApplianceSite) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vas.VirtualApplianceSiteProperties != nil { - objectMap["properties"] = vas.VirtualApplianceSiteProperties - } - if vas.Name != nil { - objectMap["name"] = vas.Name - } - if vas.ID != nil { - objectMap["id"] = vas.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualApplianceSite struct. -func (vas *VirtualApplianceSite) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualApplianceSiteProperties VirtualApplianceSiteProperties - err = json.Unmarshal(*v, &virtualApplianceSiteProperties) - if err != nil { - return err - } - vas.VirtualApplianceSiteProperties = &virtualApplianceSiteProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vas.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vas.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vas.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vas.ID = &ID - } - } - } - - return nil -} - -// VirtualApplianceSiteListResult response for ListNetworkVirtualApplianceSites API service call. -type VirtualApplianceSiteListResult struct { - autorest.Response `json:"-"` - // Value - List of Network Virtual Appliance sites. - Value *[]VirtualApplianceSite `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualApplianceSiteListResultIterator provides access to a complete listing of VirtualApplianceSite -// values. -type VirtualApplianceSiteListResultIterator struct { - i int - page VirtualApplianceSiteListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualApplianceSiteListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceSiteListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualApplianceSiteListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualApplianceSiteListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualApplianceSiteListResultIterator) Response() VirtualApplianceSiteListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualApplianceSiteListResultIterator) Value() VirtualApplianceSite { - if !iter.page.NotDone() { - return VirtualApplianceSite{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualApplianceSiteListResultIterator type. -func NewVirtualApplianceSiteListResultIterator(page VirtualApplianceSiteListResultPage) VirtualApplianceSiteListResultIterator { - return VirtualApplianceSiteListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vaslr VirtualApplianceSiteListResult) IsEmpty() bool { - return vaslr.Value == nil || len(*vaslr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vaslr VirtualApplianceSiteListResult) hasNextLink() bool { - return vaslr.NextLink != nil && len(*vaslr.NextLink) != 0 -} - -// virtualApplianceSiteListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vaslr VirtualApplianceSiteListResult) virtualApplianceSiteListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vaslr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vaslr.NextLink))) -} - -// VirtualApplianceSiteListResultPage contains a page of VirtualApplianceSite values. -type VirtualApplianceSiteListResultPage struct { - fn func(context.Context, VirtualApplianceSiteListResult) (VirtualApplianceSiteListResult, error) - vaslr VirtualApplianceSiteListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualApplianceSiteListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceSiteListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vaslr) - if err != nil { - return err - } - page.vaslr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualApplianceSiteListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualApplianceSiteListResultPage) NotDone() bool { - return !page.vaslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualApplianceSiteListResultPage) Response() VirtualApplianceSiteListResult { - return page.vaslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualApplianceSiteListResultPage) Values() []VirtualApplianceSite { - if page.vaslr.IsEmpty() { - return nil - } - return *page.vaslr.Value -} - -// Creates a new instance of the VirtualApplianceSiteListResultPage type. -func NewVirtualApplianceSiteListResultPage(cur VirtualApplianceSiteListResult, getNextPage func(context.Context, VirtualApplianceSiteListResult) (VirtualApplianceSiteListResult, error)) VirtualApplianceSiteListResultPage { - return VirtualApplianceSiteListResultPage{ - fn: getNextPage, - vaslr: cur, - } -} - -// VirtualApplianceSiteProperties properties of the rule group. -type VirtualApplianceSiteProperties struct { - // AddressPrefix - Address Prefix. - AddressPrefix *string `json:"addressPrefix,omitempty"` - // O365Policy - Office 365 Policy. - O365Policy *Office365PolicyProperties `json:"o365Policy,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualApplianceSiteProperties. -func (vasp VirtualApplianceSiteProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vasp.AddressPrefix != nil { - objectMap["addressPrefix"] = vasp.AddressPrefix - } - if vasp.O365Policy != nil { - objectMap["o365Policy"] = vasp.O365Policy - } - return json.Marshal(objectMap) -} - -// VirtualApplianceSitesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualApplianceSitesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualApplianceSitesClient) (VirtualApplianceSite, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualApplianceSitesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualApplianceSitesCreateOrUpdateFuture.Result. -func (future *VirtualApplianceSitesCreateOrUpdateFuture) result(client VirtualApplianceSitesClient) (vas VirtualApplianceSite, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSitesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vas.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualApplianceSitesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vas.Response.Response, err = future.GetResult(sender); err == nil && vas.Response.Response.StatusCode != http.StatusNoContent { - vas, err = client.CreateOrUpdateResponder(vas.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSitesCreateOrUpdateFuture", "Result", vas.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualApplianceSitesDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualApplianceSitesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualApplianceSitesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualApplianceSitesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualApplianceSitesDeleteFuture.Result. -func (future *VirtualApplianceSitesDeleteFuture) result(client VirtualApplianceSitesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSitesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualApplianceSitesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualApplianceSku definition of the NetworkVirtualApplianceSkus resource. -type VirtualApplianceSku struct { - autorest.Response `json:"-"` - // VirtualApplianceSkuPropertiesFormat - NetworkVirtualApplianceSku properties. - *VirtualApplianceSkuPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualApplianceSku. -func (vas VirtualApplianceSku) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vas.VirtualApplianceSkuPropertiesFormat != nil { - objectMap["properties"] = vas.VirtualApplianceSkuPropertiesFormat - } - if vas.ID != nil { - objectMap["id"] = vas.ID - } - if vas.Location != nil { - objectMap["location"] = vas.Location - } - if vas.Tags != nil { - objectMap["tags"] = vas.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualApplianceSku struct. -func (vas *VirtualApplianceSku) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualApplianceSkuPropertiesFormat VirtualApplianceSkuPropertiesFormat - err = json.Unmarshal(*v, &virtualApplianceSkuPropertiesFormat) - if err != nil { - return err - } - vas.VirtualApplianceSkuPropertiesFormat = &virtualApplianceSkuPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vas.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vas.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vas.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vas.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vas.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vas.Tags = tags - } - } - } - - return nil -} - -// VirtualApplianceSkuInstances list of available Sku and instances. -type VirtualApplianceSkuInstances struct { - // ScaleUnit - READ-ONLY; Scale Unit. - ScaleUnit *string `json:"scaleUnit,omitempty"` - // InstanceCount - READ-ONLY; Instance Count. - InstanceCount *int32 `json:"instanceCount,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualApplianceSkuInstances. -func (vasi VirtualApplianceSkuInstances) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualApplianceSkuListResult response for ListNetworkVirtualApplianceSkus API service call. -type VirtualApplianceSkuListResult struct { - autorest.Response `json:"-"` - // Value - List of Network Virtual Appliance Skus that are available. - Value *[]VirtualApplianceSku `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualApplianceSkuListResultIterator provides access to a complete listing of VirtualApplianceSku -// values. -type VirtualApplianceSkuListResultIterator struct { - i int - page VirtualApplianceSkuListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualApplianceSkuListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceSkuListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualApplianceSkuListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualApplianceSkuListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualApplianceSkuListResultIterator) Response() VirtualApplianceSkuListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualApplianceSkuListResultIterator) Value() VirtualApplianceSku { - if !iter.page.NotDone() { - return VirtualApplianceSku{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualApplianceSkuListResultIterator type. -func NewVirtualApplianceSkuListResultIterator(page VirtualApplianceSkuListResultPage) VirtualApplianceSkuListResultIterator { - return VirtualApplianceSkuListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vaslr VirtualApplianceSkuListResult) IsEmpty() bool { - return vaslr.Value == nil || len(*vaslr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vaslr VirtualApplianceSkuListResult) hasNextLink() bool { - return vaslr.NextLink != nil && len(*vaslr.NextLink) != 0 -} - -// virtualApplianceSkuListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vaslr VirtualApplianceSkuListResult) virtualApplianceSkuListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vaslr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vaslr.NextLink))) -} - -// VirtualApplianceSkuListResultPage contains a page of VirtualApplianceSku values. -type VirtualApplianceSkuListResultPage struct { - fn func(context.Context, VirtualApplianceSkuListResult) (VirtualApplianceSkuListResult, error) - vaslr VirtualApplianceSkuListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualApplianceSkuListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceSkuListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vaslr) - if err != nil { - return err - } - page.vaslr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualApplianceSkuListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualApplianceSkuListResultPage) NotDone() bool { - return !page.vaslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualApplianceSkuListResultPage) Response() VirtualApplianceSkuListResult { - return page.vaslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualApplianceSkuListResultPage) Values() []VirtualApplianceSku { - if page.vaslr.IsEmpty() { - return nil - } - return *page.vaslr.Value -} - -// Creates a new instance of the VirtualApplianceSkuListResultPage type. -func NewVirtualApplianceSkuListResultPage(cur VirtualApplianceSkuListResult, getNextPage func(context.Context, VirtualApplianceSkuListResult) (VirtualApplianceSkuListResult, error)) VirtualApplianceSkuListResultPage { - return VirtualApplianceSkuListResultPage{ - fn: getNextPage, - vaslr: cur, - } -} - -// VirtualApplianceSkuProperties network Virtual Appliance Sku Properties. -type VirtualApplianceSkuProperties struct { - // Vendor - Virtual Appliance Vendor. - Vendor *string `json:"vendor,omitempty"` - // BundledScaleUnit - Virtual Appliance Scale Unit. - BundledScaleUnit *string `json:"bundledScaleUnit,omitempty"` - // MarketPlaceVersion - Virtual Appliance Version. - MarketPlaceVersion *string `json:"marketPlaceVersion,omitempty"` -} - -// VirtualApplianceSkuPropertiesFormat properties specific to NetworkVirtualApplianceSkus. -type VirtualApplianceSkuPropertiesFormat struct { - // Vendor - READ-ONLY; Network Virtual Appliance Sku vendor. - Vendor *string `json:"vendor,omitempty"` - // AvailableVersions - READ-ONLY; Available Network Virtual Appliance versions. - AvailableVersions *[]string `json:"availableVersions,omitempty"` - // AvailableScaleUnits - The list of scale units available. - AvailableScaleUnits *[]VirtualApplianceSkuInstances `json:"availableScaleUnits,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualApplianceSkuPropertiesFormat. -func (vaspf VirtualApplianceSkuPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vaspf.AvailableScaleUnits != nil { - objectMap["availableScaleUnits"] = vaspf.AvailableScaleUnits - } - return json.Marshal(objectMap) -} - -// VirtualHub virtualHub Resource. -type VirtualHub struct { - autorest.Response `json:"-"` - // VirtualHubProperties - Properties of the virtual hub. - *VirtualHubProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Kind - READ-ONLY; Kind of service virtual hub. This is metadata used for the Azure portal experience for Route Server. - Kind *string `json:"kind,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualHub. -func (vh VirtualHub) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vh.VirtualHubProperties != nil { - objectMap["properties"] = vh.VirtualHubProperties - } - if vh.ID != nil { - objectMap["id"] = vh.ID - } - if vh.Location != nil { - objectMap["location"] = vh.Location - } - if vh.Tags != nil { - objectMap["tags"] = vh.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualHub struct. -func (vh *VirtualHub) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualHubProperties VirtualHubProperties - err = json.Unmarshal(*v, &virtualHubProperties) - if err != nil { - return err - } - vh.VirtualHubProperties = &virtualHubProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vh.Etag = &etag - } - case "kind": - if v != nil { - var kind string - err = json.Unmarshal(*v, &kind) - if err != nil { - return err - } - vh.Kind = &kind - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vh.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vh.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vh.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vh.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vh.Tags = tags - } - } - } - - return nil -} - -// VirtualHubBgpConnectionCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VirtualHubBgpConnectionCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubBgpConnectionClient) (BgpConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubBgpConnectionCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubBgpConnectionCreateOrUpdateFuture.Result. -func (future *VirtualHubBgpConnectionCreateOrUpdateFuture) result(client VirtualHubBgpConnectionClient) (bc BgpConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - bc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubBgpConnectionCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if bc.Response.Response, err = future.GetResult(sender); err == nil && bc.Response.Response.StatusCode != http.StatusNoContent { - bc, err = client.CreateOrUpdateResponder(bc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionCreateOrUpdateFuture", "Result", bc.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualHubBgpConnectionDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualHubBgpConnectionDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubBgpConnectionClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubBgpConnectionDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubBgpConnectionDeleteFuture.Result. -func (future *VirtualHubBgpConnectionDeleteFuture) result(client VirtualHubBgpConnectionClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubBgpConnectionDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualHubBgpConnectionsListAdvertisedRoutesFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualHubBgpConnectionsListAdvertisedRoutesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubBgpConnectionsClient) (PeerRouteList, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubBgpConnectionsListAdvertisedRoutesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubBgpConnectionsListAdvertisedRoutesFuture.Result. -func (future *VirtualHubBgpConnectionsListAdvertisedRoutesFuture) result(client VirtualHubBgpConnectionsClient) (prl PeerRouteList, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsListAdvertisedRoutesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - prl.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubBgpConnectionsListAdvertisedRoutesFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if prl.Response.Response, err = future.GetResult(sender); err == nil && prl.Response.Response.StatusCode != http.StatusNoContent { - prl, err = client.ListAdvertisedRoutesResponder(prl.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsListAdvertisedRoutesFuture", "Result", prl.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualHubBgpConnectionsListLearnedRoutesFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type VirtualHubBgpConnectionsListLearnedRoutesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubBgpConnectionsClient) (PeerRouteList, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubBgpConnectionsListLearnedRoutesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubBgpConnectionsListLearnedRoutesFuture.Result. -func (future *VirtualHubBgpConnectionsListLearnedRoutesFuture) result(client VirtualHubBgpConnectionsClient) (prl PeerRouteList, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsListLearnedRoutesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - prl.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubBgpConnectionsListLearnedRoutesFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if prl.Response.Response, err = future.GetResult(sender); err == nil && prl.Response.Response.StatusCode != http.StatusNoContent { - prl, err = client.ListLearnedRoutesResponder(prl.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsListLearnedRoutesFuture", "Result", prl.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualHubEffectiveRoute the effective route configured on the virtual hub or specified resource. -type VirtualHubEffectiveRoute struct { - // AddressPrefixes - The list of address prefixes. - AddressPrefixes *[]string `json:"addressPrefixes,omitempty"` - // NextHops - The list of next hops. - NextHops *[]string `json:"nextHops,omitempty"` - // NextHopType - The type of the next hop. - NextHopType *string `json:"nextHopType,omitempty"` - // AsPath - The ASPath of this route. - AsPath *string `json:"asPath,omitempty"` - // RouteOrigin - The origin of this route. - RouteOrigin *string `json:"routeOrigin,omitempty"` -} - -// VirtualHubEffectiveRouteList effectiveRoutes List. -type VirtualHubEffectiveRouteList struct { - // Value - The list of effective routes configured on the virtual hub or the specified resource. - Value *[]VirtualHubEffectiveRoute `json:"value,omitempty"` -} - -// VirtualHubID virtual Hub identifier. -type VirtualHubID struct { - // ID - The resource URI for the Virtual Hub where the ExpressRoute gateway is or will be deployed. The Virtual Hub resource and the ExpressRoute gateway resource reside in the same subscription. - ID *string `json:"id,omitempty"` -} - -// VirtualHubIPConfigurationCreateOrUpdateFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type VirtualHubIPConfigurationCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubIPConfigurationClient) (HubIPConfiguration, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubIPConfigurationCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubIPConfigurationCreateOrUpdateFuture.Result. -func (future *VirtualHubIPConfigurationCreateOrUpdateFuture) result(client VirtualHubIPConfigurationClient) (hic HubIPConfiguration, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - hic.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubIPConfigurationCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if hic.Response.Response, err = future.GetResult(sender); err == nil && hic.Response.Response.StatusCode != http.StatusNoContent { - hic, err = client.CreateOrUpdateResponder(hic.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationCreateOrUpdateFuture", "Result", hic.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualHubIPConfigurationDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualHubIPConfigurationDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubIPConfigurationClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubIPConfigurationDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubIPConfigurationDeleteFuture.Result. -func (future *VirtualHubIPConfigurationDeleteFuture) result(client VirtualHubIPConfigurationClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubIPConfigurationDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualHubProperties parameters for VirtualHub. -type VirtualHubProperties struct { - // VirtualWan - The VirtualWAN to which the VirtualHub belongs. - VirtualWan *SubResource `json:"virtualWan,omitempty"` - // VpnGateway - The VpnGateway associated with this VirtualHub. - VpnGateway *SubResource `json:"vpnGateway,omitempty"` - // P2SVpnGateway - The P2SVpnGateway associated with this VirtualHub. - P2SVpnGateway *SubResource `json:"p2SVpnGateway,omitempty"` - // ExpressRouteGateway - The expressRouteGateway associated with this VirtualHub. - ExpressRouteGateway *SubResource `json:"expressRouteGateway,omitempty"` - // AzureFirewall - The azureFirewall associated with this VirtualHub. - AzureFirewall *SubResource `json:"azureFirewall,omitempty"` - // SecurityPartnerProvider - The securityPartnerProvider associated with this VirtualHub. - SecurityPartnerProvider *SubResource `json:"securityPartnerProvider,omitempty"` - // AddressPrefix - Address-prefix for this VirtualHub. - AddressPrefix *string `json:"addressPrefix,omitempty"` - // RouteTable - The routeTable associated with this virtual hub. - RouteTable *VirtualHubRouteTable `json:"routeTable,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the virtual hub resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // SecurityProviderName - The Security Provider name. - SecurityProviderName *string `json:"securityProviderName,omitempty"` - // VirtualHubRouteTableV2s - List of all virtual hub route table v2s associated with this VirtualHub. - VirtualHubRouteTableV2s *[]VirtualHubRouteTableV2 `json:"virtualHubRouteTableV2s,omitempty"` - // Sku - The sku of this VirtualHub. - Sku *string `json:"sku,omitempty"` - // RoutingState - The routing state. Possible values include: 'RoutingStateNone', 'RoutingStateProvisioned', 'RoutingStateProvisioning', 'RoutingStateFailed' - RoutingState RoutingState `json:"routingState,omitempty"` - // BgpConnections - READ-ONLY; List of references to Bgp Connections. - BgpConnections *[]SubResource `json:"bgpConnections,omitempty"` - // IPConfigurations - READ-ONLY; List of references to IpConfigurations. - IPConfigurations *[]SubResource `json:"ipConfigurations,omitempty"` - // RouteMaps - READ-ONLY; List of references to RouteMaps. - RouteMaps *[]SubResource `json:"routeMaps,omitempty"` - // VirtualRouterAsn - VirtualRouter ASN. - VirtualRouterAsn *int64 `json:"virtualRouterAsn,omitempty"` - // VirtualRouterIps - VirtualRouter IPs. - VirtualRouterIps *[]string `json:"virtualRouterIps,omitempty"` - // AllowBranchToBranchTraffic - Flag to control transit for VirtualRouter hub. - AllowBranchToBranchTraffic *bool `json:"allowBranchToBranchTraffic,omitempty"` - // PreferredRoutingGateway - The preferred gateway to route on-prem traffic. Possible values include: 'PreferredRoutingGatewayExpressRoute', 'PreferredRoutingGatewayVpnGateway', 'PreferredRoutingGatewayNone' - PreferredRoutingGateway PreferredRoutingGateway `json:"preferredRoutingGateway,omitempty"` - // HubRoutingPreference - The hubRoutingPreference of this VirtualHub. Possible values include: 'HubRoutingPreferenceExpressRoute', 'HubRoutingPreferenceVpnGateway', 'HubRoutingPreferenceASPath' - HubRoutingPreference HubRoutingPreference `json:"hubRoutingPreference,omitempty"` - // VirtualRouterAutoScaleConfiguration - The VirtualHub Router autoscale configuration. - VirtualRouterAutoScaleConfiguration *VirtualRouterAutoScaleConfiguration `json:"virtualRouterAutoScaleConfiguration,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualHubProperties. -func (vhp VirtualHubProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vhp.VirtualWan != nil { - objectMap["virtualWan"] = vhp.VirtualWan - } - if vhp.VpnGateway != nil { - objectMap["vpnGateway"] = vhp.VpnGateway - } - if vhp.P2SVpnGateway != nil { - objectMap["p2SVpnGateway"] = vhp.P2SVpnGateway - } - if vhp.ExpressRouteGateway != nil { - objectMap["expressRouteGateway"] = vhp.ExpressRouteGateway - } - if vhp.AzureFirewall != nil { - objectMap["azureFirewall"] = vhp.AzureFirewall - } - if vhp.SecurityPartnerProvider != nil { - objectMap["securityPartnerProvider"] = vhp.SecurityPartnerProvider - } - if vhp.AddressPrefix != nil { - objectMap["addressPrefix"] = vhp.AddressPrefix - } - if vhp.RouteTable != nil { - objectMap["routeTable"] = vhp.RouteTable - } - if vhp.SecurityProviderName != nil { - objectMap["securityProviderName"] = vhp.SecurityProviderName - } - if vhp.VirtualHubRouteTableV2s != nil { - objectMap["virtualHubRouteTableV2s"] = vhp.VirtualHubRouteTableV2s - } - if vhp.Sku != nil { - objectMap["sku"] = vhp.Sku - } - if vhp.RoutingState != "" { - objectMap["routingState"] = vhp.RoutingState - } - if vhp.VirtualRouterAsn != nil { - objectMap["virtualRouterAsn"] = vhp.VirtualRouterAsn - } - if vhp.VirtualRouterIps != nil { - objectMap["virtualRouterIps"] = vhp.VirtualRouterIps - } - if vhp.AllowBranchToBranchTraffic != nil { - objectMap["allowBranchToBranchTraffic"] = vhp.AllowBranchToBranchTraffic - } - if vhp.PreferredRoutingGateway != "" { - objectMap["preferredRoutingGateway"] = vhp.PreferredRoutingGateway - } - if vhp.HubRoutingPreference != "" { - objectMap["hubRoutingPreference"] = vhp.HubRoutingPreference - } - if vhp.VirtualRouterAutoScaleConfiguration != nil { - objectMap["virtualRouterAutoScaleConfiguration"] = vhp.VirtualRouterAutoScaleConfiguration - } - return json.Marshal(objectMap) -} - -// VirtualHubRoute virtualHub route. -type VirtualHubRoute struct { - // AddressPrefixes - List of all addressPrefixes. - AddressPrefixes *[]string `json:"addressPrefixes,omitempty"` - // NextHopIPAddress - NextHop ip address. - NextHopIPAddress *string `json:"nextHopIpAddress,omitempty"` -} - -// VirtualHubRouteTable virtualHub route table. -type VirtualHubRouteTable struct { - // Routes - List of all routes. - Routes *[]VirtualHubRoute `json:"routes,omitempty"` -} - -// VirtualHubRouteTableV2 virtualHubRouteTableV2 Resource. -type VirtualHubRouteTableV2 struct { - autorest.Response `json:"-"` - // VirtualHubRouteTableV2Properties - Properties of the virtual hub route table v2. - *VirtualHubRouteTableV2Properties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualHubRouteTableV2. -func (vhrtv VirtualHubRouteTableV2) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vhrtv.VirtualHubRouteTableV2Properties != nil { - objectMap["properties"] = vhrtv.VirtualHubRouteTableV2Properties - } - if vhrtv.Name != nil { - objectMap["name"] = vhrtv.Name - } - if vhrtv.ID != nil { - objectMap["id"] = vhrtv.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualHubRouteTableV2 struct. -func (vhrtv *VirtualHubRouteTableV2) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualHubRouteTableV2Properties VirtualHubRouteTableV2Properties - err = json.Unmarshal(*v, &virtualHubRouteTableV2Properties) - if err != nil { - return err - } - vhrtv.VirtualHubRouteTableV2Properties = &virtualHubRouteTableV2Properties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vhrtv.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vhrtv.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vhrtv.ID = &ID - } - } - } - - return nil -} - -// VirtualHubRouteTableV2Properties parameters for VirtualHubRouteTableV2. -type VirtualHubRouteTableV2Properties struct { - // Routes - List of all routes. - Routes *[]VirtualHubRouteV2 `json:"routes,omitempty"` - // AttachedConnections - List of all connections attached to this route table v2. - AttachedConnections *[]string `json:"attachedConnections,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the virtual hub route table v2 resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualHubRouteTableV2Properties. -func (vhrtvp VirtualHubRouteTableV2Properties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vhrtvp.Routes != nil { - objectMap["routes"] = vhrtvp.Routes - } - if vhrtvp.AttachedConnections != nil { - objectMap["attachedConnections"] = vhrtvp.AttachedConnections - } - return json.Marshal(objectMap) -} - -// VirtualHubRouteTableV2sCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VirtualHubRouteTableV2sCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubRouteTableV2sClient) (VirtualHubRouteTableV2, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubRouteTableV2sCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubRouteTableV2sCreateOrUpdateFuture.Result. -func (future *VirtualHubRouteTableV2sCreateOrUpdateFuture) result(client VirtualHubRouteTableV2sClient) (vhrtv VirtualHubRouteTableV2, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vhrtv.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubRouteTableV2sCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vhrtv.Response.Response, err = future.GetResult(sender); err == nil && vhrtv.Response.Response.StatusCode != http.StatusNoContent { - vhrtv, err = client.CreateOrUpdateResponder(vhrtv.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sCreateOrUpdateFuture", "Result", vhrtv.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualHubRouteTableV2sDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualHubRouteTableV2sDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubRouteTableV2sClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubRouteTableV2sDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubRouteTableV2sDeleteFuture.Result. -func (future *VirtualHubRouteTableV2sDeleteFuture) result(client VirtualHubRouteTableV2sClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubRouteTableV2sDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualHubRouteV2 virtualHubRouteTableV2 route. -type VirtualHubRouteV2 struct { - // DestinationType - The type of destinations. - DestinationType *string `json:"destinationType,omitempty"` - // Destinations - List of all destinations. - Destinations *[]string `json:"destinations,omitempty"` - // NextHopType - The type of next hops. - NextHopType *string `json:"nextHopType,omitempty"` - // NextHops - NextHops ip address. - NextHops *[]string `json:"nextHops,omitempty"` -} - -// VirtualHubsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualHubsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubsClient) (VirtualHub, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubsCreateOrUpdateFuture.Result. -func (future *VirtualHubsCreateOrUpdateFuture) result(client VirtualHubsClient) (vh VirtualHub, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vh.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vh.Response.Response, err = future.GetResult(sender); err == nil && vh.Response.Response.StatusCode != http.StatusNoContent { - vh, err = client.CreateOrUpdateResponder(vh.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsCreateOrUpdateFuture", "Result", vh.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualHubsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualHubsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubsDeleteFuture.Result. -func (future *VirtualHubsDeleteFuture) result(client VirtualHubsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualHubsGetEffectiveVirtualHubRoutesFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type VirtualHubsGetEffectiveVirtualHubRoutesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubsGetEffectiveVirtualHubRoutesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubsGetEffectiveVirtualHubRoutesFuture.Result. -func (future *VirtualHubsGetEffectiveVirtualHubRoutesFuture) result(client VirtualHubsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsGetEffectiveVirtualHubRoutesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubsGetEffectiveVirtualHubRoutesFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualHubsGetInboundRoutesFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualHubsGetInboundRoutesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubsGetInboundRoutesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubsGetInboundRoutesFuture.Result. -func (future *VirtualHubsGetInboundRoutesFuture) result(client VirtualHubsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsGetInboundRoutesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubsGetInboundRoutesFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualHubsGetOutboundRoutesFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualHubsGetOutboundRoutesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualHubsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualHubsGetOutboundRoutesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualHubsGetOutboundRoutesFuture.Result. -func (future *VirtualHubsGetOutboundRoutesFuture) result(client VirtualHubsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsGetOutboundRoutesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualHubsGetOutboundRoutesFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetwork virtual Network resource. -type VirtualNetwork struct { - autorest.Response `json:"-"` - // ExtendedLocation - The extended location of the virtual network. - ExtendedLocation *ExtendedLocation `json:"extendedLocation,omitempty"` - // VirtualNetworkPropertiesFormat - Properties of the virtual network. - *VirtualNetworkPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualNetwork. -func (vn VirtualNetwork) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vn.ExtendedLocation != nil { - objectMap["extendedLocation"] = vn.ExtendedLocation - } - if vn.VirtualNetworkPropertiesFormat != nil { - objectMap["properties"] = vn.VirtualNetworkPropertiesFormat - } - if vn.ID != nil { - objectMap["id"] = vn.ID - } - if vn.Location != nil { - objectMap["location"] = vn.Location - } - if vn.Tags != nil { - objectMap["tags"] = vn.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetwork struct. -func (vn *VirtualNetwork) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "extendedLocation": - if v != nil { - var extendedLocation ExtendedLocation - err = json.Unmarshal(*v, &extendedLocation) - if err != nil { - return err - } - vn.ExtendedLocation = &extendedLocation - } - case "properties": - if v != nil { - var virtualNetworkPropertiesFormat VirtualNetworkPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkPropertiesFormat) - if err != nil { - return err - } - vn.VirtualNetworkPropertiesFormat = &virtualNetworkPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vn.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vn.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vn.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vn.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vn.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vn.Tags = tags - } - } - } - - return nil -} - -// VirtualNetworkBgpCommunities bgp Communities sent over ExpressRoute with each route corresponding to a -// prefix in this VNET. -type VirtualNetworkBgpCommunities struct { - // VirtualNetworkCommunity - The BGP community associated with the virtual network. - VirtualNetworkCommunity *string `json:"virtualNetworkCommunity,omitempty"` - // RegionalCommunity - READ-ONLY; The BGP community associated with the region of the virtual network. - RegionalCommunity *string `json:"regionalCommunity,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkBgpCommunities. -func (vnbc VirtualNetworkBgpCommunities) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vnbc.VirtualNetworkCommunity != nil { - objectMap["virtualNetworkCommunity"] = vnbc.VirtualNetworkCommunity - } - return json.Marshal(objectMap) -} - -// VirtualNetworkConnectionGatewayReference a reference to VirtualNetworkGateway or LocalNetworkGateway -// resource. -type VirtualNetworkConnectionGatewayReference struct { - // ID - The ID of VirtualNetworkGateway or LocalNetworkGateway resource. - ID *string `json:"id,omitempty"` -} - -// VirtualNetworkDdosProtectionStatusResult response for GetVirtualNetworkDdosProtectionStatusOperation. -type VirtualNetworkDdosProtectionStatusResult struct { - autorest.Response `json:"-"` - // Value - The Ddos Protection Status Result for each public ip under a virtual network. - Value *[]PublicIPDdosProtectionStatusResult `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualNetworkDdosProtectionStatusResultIterator provides access to a complete listing of -// PublicIPDdosProtectionStatusResult values. -type VirtualNetworkDdosProtectionStatusResultIterator struct { - i int - page VirtualNetworkDdosProtectionStatusResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkDdosProtectionStatusResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkDdosProtectionStatusResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkDdosProtectionStatusResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkDdosProtectionStatusResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkDdosProtectionStatusResultIterator) Response() VirtualNetworkDdosProtectionStatusResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkDdosProtectionStatusResultIterator) Value() PublicIPDdosProtectionStatusResult { - if !iter.page.NotDone() { - return PublicIPDdosProtectionStatusResult{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkDdosProtectionStatusResultIterator type. -func NewVirtualNetworkDdosProtectionStatusResultIterator(page VirtualNetworkDdosProtectionStatusResultPage) VirtualNetworkDdosProtectionStatusResultIterator { - return VirtualNetworkDdosProtectionStatusResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vndpsr VirtualNetworkDdosProtectionStatusResult) IsEmpty() bool { - return vndpsr.Value == nil || len(*vndpsr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vndpsr VirtualNetworkDdosProtectionStatusResult) hasNextLink() bool { - return vndpsr.NextLink != nil && len(*vndpsr.NextLink) != 0 -} - -// virtualNetworkDdosProtectionStatusResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vndpsr VirtualNetworkDdosProtectionStatusResult) virtualNetworkDdosProtectionStatusResultPreparer(ctx context.Context) (*http.Request, error) { - if !vndpsr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vndpsr.NextLink))) -} - -// VirtualNetworkDdosProtectionStatusResultPage contains a page of PublicIPDdosProtectionStatusResult -// values. -type VirtualNetworkDdosProtectionStatusResultPage struct { - fn func(context.Context, VirtualNetworkDdosProtectionStatusResult) (VirtualNetworkDdosProtectionStatusResult, error) - vndpsr VirtualNetworkDdosProtectionStatusResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkDdosProtectionStatusResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkDdosProtectionStatusResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vndpsr) - if err != nil { - return err - } - page.vndpsr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkDdosProtectionStatusResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkDdosProtectionStatusResultPage) NotDone() bool { - return !page.vndpsr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkDdosProtectionStatusResultPage) Response() VirtualNetworkDdosProtectionStatusResult { - return page.vndpsr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkDdosProtectionStatusResultPage) Values() []PublicIPDdosProtectionStatusResult { - if page.vndpsr.IsEmpty() { - return nil - } - return *page.vndpsr.Value -} - -// Creates a new instance of the VirtualNetworkDdosProtectionStatusResultPage type. -func NewVirtualNetworkDdosProtectionStatusResultPage(cur VirtualNetworkDdosProtectionStatusResult, getNextPage func(context.Context, VirtualNetworkDdosProtectionStatusResult) (VirtualNetworkDdosProtectionStatusResult, error)) VirtualNetworkDdosProtectionStatusResultPage { - return VirtualNetworkDdosProtectionStatusResultPage{ - fn: getNextPage, - vndpsr: cur, - } -} - -// VirtualNetworkEncryption indicates if encryption is enabled on virtual network and if VM without -// encryption is allowed in encrypted VNet. -type VirtualNetworkEncryption struct { - // Enabled - Indicates if encryption is enabled on the virtual network. - Enabled *bool `json:"enabled,omitempty"` - // Enforcement - If the encrypted VNet allows VM that does not support encryption. Possible values include: 'DropUnencrypted', 'AllowUnencrypted' - Enforcement VirtualNetworkEncryptionEnforcement `json:"enforcement,omitempty"` -} - -// VirtualNetworkGateway a common class for general resource information. -type VirtualNetworkGateway struct { - autorest.Response `json:"-"` - // VirtualNetworkGatewayPropertiesFormat - Properties of the virtual network gateway. - *VirtualNetworkGatewayPropertiesFormat `json:"properties,omitempty"` - // ExtendedLocation - The extended location of type local virtual network gateway. - ExtendedLocation *ExtendedLocation `json:"extendedLocation,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGateway. -func (vng VirtualNetworkGateway) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vng.VirtualNetworkGatewayPropertiesFormat != nil { - objectMap["properties"] = vng.VirtualNetworkGatewayPropertiesFormat - } - if vng.ExtendedLocation != nil { - objectMap["extendedLocation"] = vng.ExtendedLocation - } - if vng.ID != nil { - objectMap["id"] = vng.ID - } - if vng.Location != nil { - objectMap["location"] = vng.Location - } - if vng.Tags != nil { - objectMap["tags"] = vng.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkGateway struct. -func (vng *VirtualNetworkGateway) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkGatewayPropertiesFormat VirtualNetworkGatewayPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkGatewayPropertiesFormat) - if err != nil { - return err - } - vng.VirtualNetworkGatewayPropertiesFormat = &virtualNetworkGatewayPropertiesFormat - } - case "extendedLocation": - if v != nil { - var extendedLocation ExtendedLocation - err = json.Unmarshal(*v, &extendedLocation) - if err != nil { - return err - } - vng.ExtendedLocation = &extendedLocation - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vng.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vng.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vng.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vng.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vng.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vng.Tags = tags - } - } - } - - return nil -} - -// VirtualNetworkGatewayConnection a common class for general resource information. -type VirtualNetworkGatewayConnection struct { - autorest.Response `json:"-"` - // VirtualNetworkGatewayConnectionPropertiesFormat - Properties of the virtual network gateway connection. - *VirtualNetworkGatewayConnectionPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayConnection. -func (vngc VirtualNetworkGatewayConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngc.VirtualNetworkGatewayConnectionPropertiesFormat != nil { - objectMap["properties"] = vngc.VirtualNetworkGatewayConnectionPropertiesFormat - } - if vngc.ID != nil { - objectMap["id"] = vngc.ID - } - if vngc.Location != nil { - objectMap["location"] = vngc.Location - } - if vngc.Tags != nil { - objectMap["tags"] = vngc.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkGatewayConnection struct. -func (vngc *VirtualNetworkGatewayConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkGatewayConnectionPropertiesFormat VirtualNetworkGatewayConnectionPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkGatewayConnectionPropertiesFormat) - if err != nil { - return err - } - vngc.VirtualNetworkGatewayConnectionPropertiesFormat = &virtualNetworkGatewayConnectionPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vngc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vngc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vngc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vngc.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vngc.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vngc.Tags = tags - } - } - } - - return nil -} - -// VirtualNetworkGatewayConnectionListEntity a common class for general resource information. -type VirtualNetworkGatewayConnectionListEntity struct { - // VirtualNetworkGatewayConnectionListEntityPropertiesFormat - Properties of the virtual network gateway connection. - *VirtualNetworkGatewayConnectionListEntityPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayConnectionListEntity. -func (vngcle VirtualNetworkGatewayConnectionListEntity) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngcle.VirtualNetworkGatewayConnectionListEntityPropertiesFormat != nil { - objectMap["properties"] = vngcle.VirtualNetworkGatewayConnectionListEntityPropertiesFormat - } - if vngcle.ID != nil { - objectMap["id"] = vngcle.ID - } - if vngcle.Location != nil { - objectMap["location"] = vngcle.Location - } - if vngcle.Tags != nil { - objectMap["tags"] = vngcle.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkGatewayConnectionListEntity struct. -func (vngcle *VirtualNetworkGatewayConnectionListEntity) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkGatewayConnectionListEntityPropertiesFormat VirtualNetworkGatewayConnectionListEntityPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkGatewayConnectionListEntityPropertiesFormat) - if err != nil { - return err - } - vngcle.VirtualNetworkGatewayConnectionListEntityPropertiesFormat = &virtualNetworkGatewayConnectionListEntityPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vngcle.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vngcle.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vngcle.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vngcle.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vngcle.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vngcle.Tags = tags - } - } - } - - return nil -} - -// VirtualNetworkGatewayConnectionListEntityPropertiesFormat virtualNetworkGatewayConnection properties. -type VirtualNetworkGatewayConnectionListEntityPropertiesFormat struct { - // AuthorizationKey - The authorizationKey. - AuthorizationKey *string `json:"authorizationKey,omitempty"` - // VirtualNetworkGateway1 - The reference to virtual network gateway resource. - VirtualNetworkGateway1 *VirtualNetworkConnectionGatewayReference `json:"virtualNetworkGateway1,omitempty"` - // VirtualNetworkGateway2 - The reference to virtual network gateway resource. - VirtualNetworkGateway2 *VirtualNetworkConnectionGatewayReference `json:"virtualNetworkGateway2,omitempty"` - // LocalNetworkGateway2 - The reference to local network gateway resource. - LocalNetworkGateway2 *VirtualNetworkConnectionGatewayReference `json:"localNetworkGateway2,omitempty"` - // ConnectionType - Gateway connection type. Possible values include: 'IPsec', 'Vnet2Vnet', 'ExpressRoute', 'VPNClient' - ConnectionType VirtualNetworkGatewayConnectionType `json:"connectionType,omitempty"` - // ConnectionProtocol - Connection protocol used for this connection. Possible values include: 'IKEv2', 'IKEv1' - ConnectionProtocol VirtualNetworkGatewayConnectionProtocol `json:"connectionProtocol,omitempty"` - // RoutingWeight - The routing weight. - RoutingWeight *int32 `json:"routingWeight,omitempty"` - // ConnectionMode - The connection mode for this connection. Possible values include: 'VirtualNetworkGatewayConnectionModeDefault', 'VirtualNetworkGatewayConnectionModeResponderOnly', 'VirtualNetworkGatewayConnectionModeInitiatorOnly' - ConnectionMode VirtualNetworkGatewayConnectionMode `json:"connectionMode,omitempty"` - // SharedKey - The IPSec shared key. - SharedKey *string `json:"sharedKey,omitempty"` - // ConnectionStatus - READ-ONLY; Virtual Network Gateway connection status. Possible values include: 'VirtualNetworkGatewayConnectionStatusUnknown', 'VirtualNetworkGatewayConnectionStatusConnecting', 'VirtualNetworkGatewayConnectionStatusConnected', 'VirtualNetworkGatewayConnectionStatusNotConnected' - ConnectionStatus VirtualNetworkGatewayConnectionStatus `json:"connectionStatus,omitempty"` - // TunnelConnectionStatus - READ-ONLY; Collection of all tunnels' connection health status. - TunnelConnectionStatus *[]TunnelConnectionHealth `json:"tunnelConnectionStatus,omitempty"` - // EgressBytesTransferred - READ-ONLY; The egress bytes transferred in this connection. - EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` - // IngressBytesTransferred - READ-ONLY; The ingress bytes transferred in this connection. - IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` - // Peer - The reference to peerings resource. - Peer *SubResource `json:"peer,omitempty"` - // EnableBgp - EnableBgp flag. - EnableBgp *bool `json:"enableBgp,omitempty"` - // GatewayCustomBgpIPAddresses - GatewayCustomBgpIpAddresses to be used for virtual network gateway Connection. - GatewayCustomBgpIPAddresses *[]GatewayCustomBgpIPAddressIPConfiguration `json:"gatewayCustomBgpIpAddresses,omitempty"` - // UsePolicyBasedTrafficSelectors - Enable policy-based traffic selectors. - UsePolicyBasedTrafficSelectors *bool `json:"usePolicyBasedTrafficSelectors,omitempty"` - // IpsecPolicies - The IPSec Policies to be considered by this connection. - IpsecPolicies *[]IpsecPolicy `json:"ipsecPolicies,omitempty"` - // TrafficSelectorPolicies - The Traffic Selector Policies to be considered by this connection. - TrafficSelectorPolicies *[]TrafficSelectorPolicy `json:"trafficSelectorPolicies,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the virtual network gateway connection resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the virtual network gateway connection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ExpressRouteGatewayBypass - Bypass ExpressRoute Gateway for data forwarding. - ExpressRouteGatewayBypass *bool `json:"expressRouteGatewayBypass,omitempty"` - // EnablePrivateLinkFastPath - Bypass the ExpressRoute gateway when accessing private-links. ExpressRoute FastPath (expressRouteGatewayBypass) must be enabled. - EnablePrivateLinkFastPath *bool `json:"enablePrivateLinkFastPath,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayConnectionListEntityPropertiesFormat. -func (vngclepf VirtualNetworkGatewayConnectionListEntityPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngclepf.AuthorizationKey != nil { - objectMap["authorizationKey"] = vngclepf.AuthorizationKey - } - if vngclepf.VirtualNetworkGateway1 != nil { - objectMap["virtualNetworkGateway1"] = vngclepf.VirtualNetworkGateway1 - } - if vngclepf.VirtualNetworkGateway2 != nil { - objectMap["virtualNetworkGateway2"] = vngclepf.VirtualNetworkGateway2 - } - if vngclepf.LocalNetworkGateway2 != nil { - objectMap["localNetworkGateway2"] = vngclepf.LocalNetworkGateway2 - } - if vngclepf.ConnectionType != "" { - objectMap["connectionType"] = vngclepf.ConnectionType - } - if vngclepf.ConnectionProtocol != "" { - objectMap["connectionProtocol"] = vngclepf.ConnectionProtocol - } - if vngclepf.RoutingWeight != nil { - objectMap["routingWeight"] = vngclepf.RoutingWeight - } - if vngclepf.ConnectionMode != "" { - objectMap["connectionMode"] = vngclepf.ConnectionMode - } - if vngclepf.SharedKey != nil { - objectMap["sharedKey"] = vngclepf.SharedKey - } - if vngclepf.Peer != nil { - objectMap["peer"] = vngclepf.Peer - } - if vngclepf.EnableBgp != nil { - objectMap["enableBgp"] = vngclepf.EnableBgp - } - if vngclepf.GatewayCustomBgpIPAddresses != nil { - objectMap["gatewayCustomBgpIpAddresses"] = vngclepf.GatewayCustomBgpIPAddresses - } - if vngclepf.UsePolicyBasedTrafficSelectors != nil { - objectMap["usePolicyBasedTrafficSelectors"] = vngclepf.UsePolicyBasedTrafficSelectors - } - if vngclepf.IpsecPolicies != nil { - objectMap["ipsecPolicies"] = vngclepf.IpsecPolicies - } - if vngclepf.TrafficSelectorPolicies != nil { - objectMap["trafficSelectorPolicies"] = vngclepf.TrafficSelectorPolicies - } - if vngclepf.ExpressRouteGatewayBypass != nil { - objectMap["expressRouteGatewayBypass"] = vngclepf.ExpressRouteGatewayBypass - } - if vngclepf.EnablePrivateLinkFastPath != nil { - objectMap["enablePrivateLinkFastPath"] = vngclepf.EnablePrivateLinkFastPath - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayConnectionListResult response for the ListVirtualNetworkGatewayConnections API -// service call. -type VirtualNetworkGatewayConnectionListResult struct { - autorest.Response `json:"-"` - // Value - A list of VirtualNetworkGatewayConnection resources that exists in a resource group. - Value *[]VirtualNetworkGatewayConnection `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayConnectionListResult. -func (vngclr VirtualNetworkGatewayConnectionListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngclr.Value != nil { - objectMap["value"] = vngclr.Value - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayConnectionListResultIterator provides access to a complete listing of -// VirtualNetworkGatewayConnection values. -type VirtualNetworkGatewayConnectionListResultIterator struct { - i int - page VirtualNetworkGatewayConnectionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkGatewayConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkGatewayConnectionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkGatewayConnectionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkGatewayConnectionListResultIterator) Response() VirtualNetworkGatewayConnectionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkGatewayConnectionListResultIterator) Value() VirtualNetworkGatewayConnection { - if !iter.page.NotDone() { - return VirtualNetworkGatewayConnection{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkGatewayConnectionListResultIterator type. -func NewVirtualNetworkGatewayConnectionListResultIterator(page VirtualNetworkGatewayConnectionListResultPage) VirtualNetworkGatewayConnectionListResultIterator { - return VirtualNetworkGatewayConnectionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vngclr VirtualNetworkGatewayConnectionListResult) IsEmpty() bool { - return vngclr.Value == nil || len(*vngclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vngclr VirtualNetworkGatewayConnectionListResult) hasNextLink() bool { - return vngclr.NextLink != nil && len(*vngclr.NextLink) != 0 -} - -// virtualNetworkGatewayConnectionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vngclr VirtualNetworkGatewayConnectionListResult) virtualNetworkGatewayConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vngclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vngclr.NextLink))) -} - -// VirtualNetworkGatewayConnectionListResultPage contains a page of VirtualNetworkGatewayConnection values. -type VirtualNetworkGatewayConnectionListResultPage struct { - fn func(context.Context, VirtualNetworkGatewayConnectionListResult) (VirtualNetworkGatewayConnectionListResult, error) - vngclr VirtualNetworkGatewayConnectionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkGatewayConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vngclr) - if err != nil { - return err - } - page.vngclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkGatewayConnectionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkGatewayConnectionListResultPage) NotDone() bool { - return !page.vngclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkGatewayConnectionListResultPage) Response() VirtualNetworkGatewayConnectionListResult { - return page.vngclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkGatewayConnectionListResultPage) Values() []VirtualNetworkGatewayConnection { - if page.vngclr.IsEmpty() { - return nil - } - return *page.vngclr.Value -} - -// Creates a new instance of the VirtualNetworkGatewayConnectionListResultPage type. -func NewVirtualNetworkGatewayConnectionListResultPage(cur VirtualNetworkGatewayConnectionListResult, getNextPage func(context.Context, VirtualNetworkGatewayConnectionListResult) (VirtualNetworkGatewayConnectionListResult, error)) VirtualNetworkGatewayConnectionListResultPage { - return VirtualNetworkGatewayConnectionListResultPage{ - fn: getNextPage, - vngclr: cur, - } -} - -// VirtualNetworkGatewayConnectionPropertiesFormat virtualNetworkGatewayConnection properties. -type VirtualNetworkGatewayConnectionPropertiesFormat struct { - // AuthorizationKey - The authorizationKey. - AuthorizationKey *string `json:"authorizationKey,omitempty"` - // VirtualNetworkGateway1 - The reference to virtual network gateway resource. - VirtualNetworkGateway1 *VirtualNetworkGateway `json:"virtualNetworkGateway1,omitempty"` - // VirtualNetworkGateway2 - The reference to virtual network gateway resource. - VirtualNetworkGateway2 *VirtualNetworkGateway `json:"virtualNetworkGateway2,omitempty"` - // LocalNetworkGateway2 - The reference to local network gateway resource. - LocalNetworkGateway2 *LocalNetworkGateway `json:"localNetworkGateway2,omitempty"` - // IngressNatRules - List of ingress NatRules. - IngressNatRules *[]SubResource `json:"ingressNatRules,omitempty"` - // EgressNatRules - List of egress NatRules. - EgressNatRules *[]SubResource `json:"egressNatRules,omitempty"` - // ConnectionType - Gateway connection type. Possible values include: 'IPsec', 'Vnet2Vnet', 'ExpressRoute', 'VPNClient' - ConnectionType VirtualNetworkGatewayConnectionType `json:"connectionType,omitempty"` - // ConnectionProtocol - Connection protocol used for this connection. Possible values include: 'IKEv2', 'IKEv1' - ConnectionProtocol VirtualNetworkGatewayConnectionProtocol `json:"connectionProtocol,omitempty"` - // RoutingWeight - The routing weight. - RoutingWeight *int32 `json:"routingWeight,omitempty"` - // DpdTimeoutSeconds - The dead peer detection timeout of this connection in seconds. - DpdTimeoutSeconds *int32 `json:"dpdTimeoutSeconds,omitempty"` - // ConnectionMode - The connection mode for this connection. Possible values include: 'VirtualNetworkGatewayConnectionModeDefault', 'VirtualNetworkGatewayConnectionModeResponderOnly', 'VirtualNetworkGatewayConnectionModeInitiatorOnly' - ConnectionMode VirtualNetworkGatewayConnectionMode `json:"connectionMode,omitempty"` - // SharedKey - The IPSec shared key. - SharedKey *string `json:"sharedKey,omitempty"` - // ConnectionStatus - READ-ONLY; Virtual Network Gateway connection status. Possible values include: 'VirtualNetworkGatewayConnectionStatusUnknown', 'VirtualNetworkGatewayConnectionStatusConnecting', 'VirtualNetworkGatewayConnectionStatusConnected', 'VirtualNetworkGatewayConnectionStatusNotConnected' - ConnectionStatus VirtualNetworkGatewayConnectionStatus `json:"connectionStatus,omitempty"` - // TunnelConnectionStatus - READ-ONLY; Collection of all tunnels' connection health status. - TunnelConnectionStatus *[]TunnelConnectionHealth `json:"tunnelConnectionStatus,omitempty"` - // EgressBytesTransferred - READ-ONLY; The egress bytes transferred in this connection. - EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` - // IngressBytesTransferred - READ-ONLY; The ingress bytes transferred in this connection. - IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` - // Peer - The reference to peerings resource. - Peer *SubResource `json:"peer,omitempty"` - // EnableBgp - EnableBgp flag. - EnableBgp *bool `json:"enableBgp,omitempty"` - // GatewayCustomBgpIPAddresses - GatewayCustomBgpIpAddresses to be used for virtual network gateway Connection. - GatewayCustomBgpIPAddresses *[]GatewayCustomBgpIPAddressIPConfiguration `json:"gatewayCustomBgpIpAddresses,omitempty"` - // UseLocalAzureIPAddress - Use private local Azure IP for the connection. - UseLocalAzureIPAddress *bool `json:"useLocalAzureIpAddress,omitempty"` - // UsePolicyBasedTrafficSelectors - Enable policy-based traffic selectors. - UsePolicyBasedTrafficSelectors *bool `json:"usePolicyBasedTrafficSelectors,omitempty"` - // IpsecPolicies - The IPSec Policies to be considered by this connection. - IpsecPolicies *[]IpsecPolicy `json:"ipsecPolicies,omitempty"` - // TrafficSelectorPolicies - The Traffic Selector Policies to be considered by this connection. - TrafficSelectorPolicies *[]TrafficSelectorPolicy `json:"trafficSelectorPolicies,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the virtual network gateway connection resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the virtual network gateway connection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ExpressRouteGatewayBypass - Bypass ExpressRoute Gateway for data forwarding. - ExpressRouteGatewayBypass *bool `json:"expressRouteGatewayBypass,omitempty"` - // EnablePrivateLinkFastPath - Bypass the ExpressRoute gateway when accessing private-links. ExpressRoute FastPath (expressRouteGatewayBypass) must be enabled. - EnablePrivateLinkFastPath *bool `json:"enablePrivateLinkFastPath,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayConnectionPropertiesFormat. -func (vngcpf VirtualNetworkGatewayConnectionPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngcpf.AuthorizationKey != nil { - objectMap["authorizationKey"] = vngcpf.AuthorizationKey - } - if vngcpf.VirtualNetworkGateway1 != nil { - objectMap["virtualNetworkGateway1"] = vngcpf.VirtualNetworkGateway1 - } - if vngcpf.VirtualNetworkGateway2 != nil { - objectMap["virtualNetworkGateway2"] = vngcpf.VirtualNetworkGateway2 - } - if vngcpf.LocalNetworkGateway2 != nil { - objectMap["localNetworkGateway2"] = vngcpf.LocalNetworkGateway2 - } - if vngcpf.IngressNatRules != nil { - objectMap["ingressNatRules"] = vngcpf.IngressNatRules - } - if vngcpf.EgressNatRules != nil { - objectMap["egressNatRules"] = vngcpf.EgressNatRules - } - if vngcpf.ConnectionType != "" { - objectMap["connectionType"] = vngcpf.ConnectionType - } - if vngcpf.ConnectionProtocol != "" { - objectMap["connectionProtocol"] = vngcpf.ConnectionProtocol - } - if vngcpf.RoutingWeight != nil { - objectMap["routingWeight"] = vngcpf.RoutingWeight - } - if vngcpf.DpdTimeoutSeconds != nil { - objectMap["dpdTimeoutSeconds"] = vngcpf.DpdTimeoutSeconds - } - if vngcpf.ConnectionMode != "" { - objectMap["connectionMode"] = vngcpf.ConnectionMode - } - if vngcpf.SharedKey != nil { - objectMap["sharedKey"] = vngcpf.SharedKey - } - if vngcpf.Peer != nil { - objectMap["peer"] = vngcpf.Peer - } - if vngcpf.EnableBgp != nil { - objectMap["enableBgp"] = vngcpf.EnableBgp - } - if vngcpf.GatewayCustomBgpIPAddresses != nil { - objectMap["gatewayCustomBgpIpAddresses"] = vngcpf.GatewayCustomBgpIPAddresses - } - if vngcpf.UseLocalAzureIPAddress != nil { - objectMap["useLocalAzureIpAddress"] = vngcpf.UseLocalAzureIPAddress - } - if vngcpf.UsePolicyBasedTrafficSelectors != nil { - objectMap["usePolicyBasedTrafficSelectors"] = vngcpf.UsePolicyBasedTrafficSelectors - } - if vngcpf.IpsecPolicies != nil { - objectMap["ipsecPolicies"] = vngcpf.IpsecPolicies - } - if vngcpf.TrafficSelectorPolicies != nil { - objectMap["trafficSelectorPolicies"] = vngcpf.TrafficSelectorPolicies - } - if vngcpf.ExpressRouteGatewayBypass != nil { - objectMap["expressRouteGatewayBypass"] = vngcpf.ExpressRouteGatewayBypass - } - if vngcpf.EnablePrivateLinkFastPath != nil { - objectMap["enablePrivateLinkFastPath"] = vngcpf.EnablePrivateLinkFastPath - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewayConnectionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (VirtualNetworkGatewayConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsCreateOrUpdateFuture.Result. -func (future *VirtualNetworkGatewayConnectionsCreateOrUpdateFuture) result(client VirtualNetworkGatewayConnectionsClient) (vngc VirtualNetworkGatewayConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vngc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vngc.Response.Response, err = future.GetResult(sender); err == nil && vngc.Response.Response.StatusCode != http.StatusNoContent { - vngc, err = client.CreateOrUpdateResponder(vngc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsCreateOrUpdateFuture", "Result", vngc.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewayConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VirtualNetworkGatewayConnectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsDeleteFuture.Result. -func (future *VirtualNetworkGatewayConnectionsDeleteFuture) result(client VirtualNetworkGatewayConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworkGatewayConnectionsGetIkeSasFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type VirtualNetworkGatewayConnectionsGetIkeSasFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsGetIkeSasFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsGetIkeSasFuture.Result. -func (future *VirtualNetworkGatewayConnectionsGetIkeSasFuture) result(client VirtualNetworkGatewayConnectionsClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsGetIkeSasFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsGetIkeSasFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.GetIkeSasResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsGetIkeSasFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewayConnectionsResetConnectionFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewayConnectionsResetConnectionFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsResetConnectionFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsResetConnectionFuture.Result. -func (future *VirtualNetworkGatewayConnectionsResetConnectionFuture) result(client VirtualNetworkGatewayConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsResetConnectionFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsResetConnectionFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworkGatewayConnectionsResetSharedKeyFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewayConnectionsResetSharedKeyFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (ConnectionResetSharedKey, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsResetSharedKeyFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsResetSharedKeyFuture.Result. -func (future *VirtualNetworkGatewayConnectionsResetSharedKeyFuture) result(client VirtualNetworkGatewayConnectionsClient) (crsk ConnectionResetSharedKey, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsResetSharedKeyFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - crsk.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsResetSharedKeyFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if crsk.Response.Response, err = future.GetResult(sender); err == nil && crsk.Response.Response.StatusCode != http.StatusNoContent { - crsk, err = client.ResetSharedKeyResponder(crsk.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsResetSharedKeyFuture", "Result", crsk.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewayConnectionsSetSharedKeyFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewayConnectionsSetSharedKeyFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (ConnectionSharedKey, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsSetSharedKeyFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsSetSharedKeyFuture.Result. -func (future *VirtualNetworkGatewayConnectionsSetSharedKeyFuture) result(client VirtualNetworkGatewayConnectionsClient) (csk ConnectionSharedKey, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsSetSharedKeyFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - csk.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsSetSharedKeyFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if csk.Response.Response, err = future.GetResult(sender); err == nil && csk.Response.Response.StatusCode != http.StatusNoContent { - csk, err = client.SetSharedKeyResponder(csk.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsSetSharedKeyFuture", "Result", csk.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewayConnectionsStartPacketCaptureFuture an abstraction for monitoring and retrieving -// the results of a long-running operation. -type VirtualNetworkGatewayConnectionsStartPacketCaptureFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsStartPacketCaptureFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsStartPacketCaptureFuture.Result. -func (future *VirtualNetworkGatewayConnectionsStartPacketCaptureFuture) result(client VirtualNetworkGatewayConnectionsClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsStartPacketCaptureFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsStartPacketCaptureFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.StartPacketCaptureResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsStartPacketCaptureFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewayConnectionsStopPacketCaptureFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewayConnectionsStopPacketCaptureFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsStopPacketCaptureFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsStopPacketCaptureFuture.Result. -func (future *VirtualNetworkGatewayConnectionsStopPacketCaptureFuture) result(client VirtualNetworkGatewayConnectionsClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsStopPacketCaptureFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsStopPacketCaptureFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.StopPacketCaptureResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsStopPacketCaptureFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewayConnectionsUpdateTagsFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewayConnectionsUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayConnectionsClient) (VirtualNetworkGatewayConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayConnectionsUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayConnectionsUpdateTagsFuture.Result. -func (future *VirtualNetworkGatewayConnectionsUpdateTagsFuture) result(client VirtualNetworkGatewayConnectionsClient) (vngc VirtualNetworkGatewayConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vngc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayConnectionsUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vngc.Response.Response, err = future.GetResult(sender); err == nil && vngc.Response.Response.StatusCode != http.StatusNoContent { - vngc, err = client.UpdateTagsResponder(vngc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsUpdateTagsFuture", "Result", vngc.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewayIPConfiguration IP configuration for virtual network gateway. -type VirtualNetworkGatewayIPConfiguration struct { - // VirtualNetworkGatewayIPConfigurationPropertiesFormat - Properties of the virtual network gateway ip configuration. - *VirtualNetworkGatewayIPConfigurationPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayIPConfiguration. -func (vngic VirtualNetworkGatewayIPConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngic.VirtualNetworkGatewayIPConfigurationPropertiesFormat != nil { - objectMap["properties"] = vngic.VirtualNetworkGatewayIPConfigurationPropertiesFormat - } - if vngic.Name != nil { - objectMap["name"] = vngic.Name - } - if vngic.ID != nil { - objectMap["id"] = vngic.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkGatewayIPConfiguration struct. -func (vngic *VirtualNetworkGatewayIPConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkGatewayIPConfigurationPropertiesFormat VirtualNetworkGatewayIPConfigurationPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkGatewayIPConfigurationPropertiesFormat) - if err != nil { - return err - } - vngic.VirtualNetworkGatewayIPConfigurationPropertiesFormat = &virtualNetworkGatewayIPConfigurationPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vngic.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vngic.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vngic.ID = &ID - } - } - } - - return nil -} - -// VirtualNetworkGatewayIPConfigurationPropertiesFormat properties of VirtualNetworkGatewayIPConfiguration. -type VirtualNetworkGatewayIPConfigurationPropertiesFormat struct { - // PrivateIPAllocationMethod - The private IP address allocation method. Possible values include: 'Static', 'Dynamic' - PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` - // Subnet - The reference to the subnet resource. - Subnet *SubResource `json:"subnet,omitempty"` - // PublicIPAddress - The reference to the public IP resource. - PublicIPAddress *SubResource `json:"publicIPAddress,omitempty"` - // PrivateIPAddress - READ-ONLY; Private IP Address for this gateway. - PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the virtual network gateway IP configuration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayIPConfigurationPropertiesFormat. -func (vngicpf VirtualNetworkGatewayIPConfigurationPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngicpf.PrivateIPAllocationMethod != "" { - objectMap["privateIPAllocationMethod"] = vngicpf.PrivateIPAllocationMethod - } - if vngicpf.Subnet != nil { - objectMap["subnet"] = vngicpf.Subnet - } - if vngicpf.PublicIPAddress != nil { - objectMap["publicIPAddress"] = vngicpf.PublicIPAddress - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayListConnectionsResult response for the VirtualNetworkGatewayListConnections API -// service call. -type VirtualNetworkGatewayListConnectionsResult struct { - autorest.Response `json:"-"` - // Value - A list of VirtualNetworkGatewayConnection resources that exists in a resource group. - Value *[]VirtualNetworkGatewayConnectionListEntity `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayListConnectionsResult. -func (vnglcr VirtualNetworkGatewayListConnectionsResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vnglcr.Value != nil { - objectMap["value"] = vnglcr.Value - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayListConnectionsResultIterator provides access to a complete listing of -// VirtualNetworkGatewayConnectionListEntity values. -type VirtualNetworkGatewayListConnectionsResultIterator struct { - i int - page VirtualNetworkGatewayListConnectionsResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkGatewayListConnectionsResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayListConnectionsResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkGatewayListConnectionsResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkGatewayListConnectionsResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkGatewayListConnectionsResultIterator) Response() VirtualNetworkGatewayListConnectionsResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkGatewayListConnectionsResultIterator) Value() VirtualNetworkGatewayConnectionListEntity { - if !iter.page.NotDone() { - return VirtualNetworkGatewayConnectionListEntity{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkGatewayListConnectionsResultIterator type. -func NewVirtualNetworkGatewayListConnectionsResultIterator(page VirtualNetworkGatewayListConnectionsResultPage) VirtualNetworkGatewayListConnectionsResultIterator { - return VirtualNetworkGatewayListConnectionsResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vnglcr VirtualNetworkGatewayListConnectionsResult) IsEmpty() bool { - return vnglcr.Value == nil || len(*vnglcr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vnglcr VirtualNetworkGatewayListConnectionsResult) hasNextLink() bool { - return vnglcr.NextLink != nil && len(*vnglcr.NextLink) != 0 -} - -// virtualNetworkGatewayListConnectionsResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vnglcr VirtualNetworkGatewayListConnectionsResult) virtualNetworkGatewayListConnectionsResultPreparer(ctx context.Context) (*http.Request, error) { - if !vnglcr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vnglcr.NextLink))) -} - -// VirtualNetworkGatewayListConnectionsResultPage contains a page of -// VirtualNetworkGatewayConnectionListEntity values. -type VirtualNetworkGatewayListConnectionsResultPage struct { - fn func(context.Context, VirtualNetworkGatewayListConnectionsResult) (VirtualNetworkGatewayListConnectionsResult, error) - vnglcr VirtualNetworkGatewayListConnectionsResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkGatewayListConnectionsResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayListConnectionsResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vnglcr) - if err != nil { - return err - } - page.vnglcr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkGatewayListConnectionsResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkGatewayListConnectionsResultPage) NotDone() bool { - return !page.vnglcr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkGatewayListConnectionsResultPage) Response() VirtualNetworkGatewayListConnectionsResult { - return page.vnglcr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkGatewayListConnectionsResultPage) Values() []VirtualNetworkGatewayConnectionListEntity { - if page.vnglcr.IsEmpty() { - return nil - } - return *page.vnglcr.Value -} - -// Creates a new instance of the VirtualNetworkGatewayListConnectionsResultPage type. -func NewVirtualNetworkGatewayListConnectionsResultPage(cur VirtualNetworkGatewayListConnectionsResult, getNextPage func(context.Context, VirtualNetworkGatewayListConnectionsResult) (VirtualNetworkGatewayListConnectionsResult, error)) VirtualNetworkGatewayListConnectionsResultPage { - return VirtualNetworkGatewayListConnectionsResultPage{ - fn: getNextPage, - vnglcr: cur, - } -} - -// VirtualNetworkGatewayListResult response for the ListVirtualNetworkGateways API service call. -type VirtualNetworkGatewayListResult struct { - autorest.Response `json:"-"` - // Value - A list of VirtualNetworkGateway resources that exists in a resource group. - Value *[]VirtualNetworkGateway `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayListResult. -func (vnglr VirtualNetworkGatewayListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vnglr.Value != nil { - objectMap["value"] = vnglr.Value - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayListResultIterator provides access to a complete listing of VirtualNetworkGateway -// values. -type VirtualNetworkGatewayListResultIterator struct { - i int - page VirtualNetworkGatewayListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkGatewayListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkGatewayListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkGatewayListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkGatewayListResultIterator) Response() VirtualNetworkGatewayListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkGatewayListResultIterator) Value() VirtualNetworkGateway { - if !iter.page.NotDone() { - return VirtualNetworkGateway{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkGatewayListResultIterator type. -func NewVirtualNetworkGatewayListResultIterator(page VirtualNetworkGatewayListResultPage) VirtualNetworkGatewayListResultIterator { - return VirtualNetworkGatewayListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vnglr VirtualNetworkGatewayListResult) IsEmpty() bool { - return vnglr.Value == nil || len(*vnglr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vnglr VirtualNetworkGatewayListResult) hasNextLink() bool { - return vnglr.NextLink != nil && len(*vnglr.NextLink) != 0 -} - -// virtualNetworkGatewayListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vnglr VirtualNetworkGatewayListResult) virtualNetworkGatewayListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vnglr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vnglr.NextLink))) -} - -// VirtualNetworkGatewayListResultPage contains a page of VirtualNetworkGateway values. -type VirtualNetworkGatewayListResultPage struct { - fn func(context.Context, VirtualNetworkGatewayListResult) (VirtualNetworkGatewayListResult, error) - vnglr VirtualNetworkGatewayListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkGatewayListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vnglr) - if err != nil { - return err - } - page.vnglr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkGatewayListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkGatewayListResultPage) NotDone() bool { - return !page.vnglr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkGatewayListResultPage) Response() VirtualNetworkGatewayListResult { - return page.vnglr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkGatewayListResultPage) Values() []VirtualNetworkGateway { - if page.vnglr.IsEmpty() { - return nil - } - return *page.vnglr.Value -} - -// Creates a new instance of the VirtualNetworkGatewayListResultPage type. -func NewVirtualNetworkGatewayListResultPage(cur VirtualNetworkGatewayListResult, getNextPage func(context.Context, VirtualNetworkGatewayListResult) (VirtualNetworkGatewayListResult, error)) VirtualNetworkGatewayListResultPage { - return VirtualNetworkGatewayListResultPage{ - fn: getNextPage, - vnglr: cur, - } -} - -// VirtualNetworkGatewayNatRule virtualNetworkGatewayNatRule Resource. -type VirtualNetworkGatewayNatRule struct { - autorest.Response `json:"-"` - // VirtualNetworkGatewayNatRuleProperties - Properties of the Virtual Network Gateway NAT rule. - *VirtualNetworkGatewayNatRuleProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayNatRule. -func (vngnr VirtualNetworkGatewayNatRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngnr.VirtualNetworkGatewayNatRuleProperties != nil { - objectMap["properties"] = vngnr.VirtualNetworkGatewayNatRuleProperties - } - if vngnr.Name != nil { - objectMap["name"] = vngnr.Name - } - if vngnr.ID != nil { - objectMap["id"] = vngnr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkGatewayNatRule struct. -func (vngnr *VirtualNetworkGatewayNatRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkGatewayNatRuleProperties VirtualNetworkGatewayNatRuleProperties - err = json.Unmarshal(*v, &virtualNetworkGatewayNatRuleProperties) - if err != nil { - return err - } - vngnr.VirtualNetworkGatewayNatRuleProperties = &virtualNetworkGatewayNatRuleProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vngnr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vngnr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vngnr.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vngnr.ID = &ID - } - } - } - - return nil -} - -// VirtualNetworkGatewayNatRuleProperties parameters for VirtualNetworkGatewayNatRule. -type VirtualNetworkGatewayNatRuleProperties struct { - // ProvisioningState - READ-ONLY; The provisioning state of the NAT Rule resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // Type - The type of NAT rule for VPN NAT. Possible values include: 'VpnNatRuleTypeStatic', 'VpnNatRuleTypeDynamic' - Type VpnNatRuleType `json:"type,omitempty"` - // Mode - The Source NAT direction of a VPN NAT. Possible values include: 'EgressSnat', 'IngressSnat' - Mode VpnNatRuleMode `json:"mode,omitempty"` - // InternalMappings - The private IP address internal mapping for NAT. - InternalMappings *[]VpnNatRuleMapping `json:"internalMappings,omitempty"` - // ExternalMappings - The private IP address external mapping for NAT. - ExternalMappings *[]VpnNatRuleMapping `json:"externalMappings,omitempty"` - // IPConfigurationID - The IP Configuration ID this NAT rule applies to. - IPConfigurationID *string `json:"ipConfigurationId,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayNatRuleProperties. -func (vngnrp VirtualNetworkGatewayNatRuleProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngnrp.Type != "" { - objectMap["type"] = vngnrp.Type - } - if vngnrp.Mode != "" { - objectMap["mode"] = vngnrp.Mode - } - if vngnrp.InternalMappings != nil { - objectMap["internalMappings"] = vngnrp.InternalMappings - } - if vngnrp.ExternalMappings != nil { - objectMap["externalMappings"] = vngnrp.ExternalMappings - } - if vngnrp.IPConfigurationID != nil { - objectMap["ipConfigurationId"] = vngnrp.IPConfigurationID - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayNatRulesCreateOrUpdateFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewayNatRulesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayNatRulesClient) (VirtualNetworkGatewayNatRule, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayNatRulesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayNatRulesCreateOrUpdateFuture.Result. -func (future *VirtualNetworkGatewayNatRulesCreateOrUpdateFuture) result(client VirtualNetworkGatewayNatRulesClient) (vngnr VirtualNetworkGatewayNatRule, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vngnr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayNatRulesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vngnr.Response.Response, err = future.GetResult(sender); err == nil && vngnr.Response.Response.StatusCode != http.StatusNoContent { - vngnr, err = client.CreateOrUpdateResponder(vngnr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesCreateOrUpdateFuture", "Result", vngnr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewayNatRulesDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkGatewayNatRulesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewayNatRulesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewayNatRulesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewayNatRulesDeleteFuture.Result. -func (future *VirtualNetworkGatewayNatRulesDeleteFuture) result(client VirtualNetworkGatewayNatRulesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewayNatRulesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworkGatewayPolicyGroup parameters for VirtualNetworkGatewayPolicyGroup. -type VirtualNetworkGatewayPolicyGroup struct { - // VirtualNetworkGatewayPolicyGroupProperties - Properties of tVirtualNetworkGatewayPolicyGroup. - *VirtualNetworkGatewayPolicyGroupProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayPolicyGroup. -func (vngpg VirtualNetworkGatewayPolicyGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngpg.VirtualNetworkGatewayPolicyGroupProperties != nil { - objectMap["properties"] = vngpg.VirtualNetworkGatewayPolicyGroupProperties - } - if vngpg.Name != nil { - objectMap["name"] = vngpg.Name - } - if vngpg.ID != nil { - objectMap["id"] = vngpg.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkGatewayPolicyGroup struct. -func (vngpg *VirtualNetworkGatewayPolicyGroup) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkGatewayPolicyGroupProperties VirtualNetworkGatewayPolicyGroupProperties - err = json.Unmarshal(*v, &virtualNetworkGatewayPolicyGroupProperties) - if err != nil { - return err - } - vngpg.VirtualNetworkGatewayPolicyGroupProperties = &virtualNetworkGatewayPolicyGroupProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vngpg.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vngpg.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vngpg.ID = &ID - } - } - } - - return nil -} - -// VirtualNetworkGatewayPolicyGroupMember vpn Client Connection configuration PolicyGroup member -type VirtualNetworkGatewayPolicyGroupMember struct { - // Name - Name of the VirtualNetworkGatewayPolicyGroupMember. - Name *string `json:"name,omitempty"` - // AttributeType - The Vpn Policy member attribute type. Possible values include: 'CertificateGroupID', 'AADGroupID', 'RadiusAzureGroupID' - AttributeType VpnPolicyMemberAttributeType `json:"attributeType,omitempty"` - // AttributeValue - The value of Attribute used for this VirtualNetworkGatewayPolicyGroupMember. - AttributeValue *string `json:"attributeValue,omitempty"` -} - -// VirtualNetworkGatewayPolicyGroupProperties properties of VirtualNetworkGatewayPolicyGroup. -type VirtualNetworkGatewayPolicyGroupProperties struct { - // IsDefault - Shows if this is a Default VirtualNetworkGatewayPolicyGroup or not. - IsDefault *bool `json:"isDefault,omitempty"` - // Priority - Priority for VirtualNetworkGatewayPolicyGroup. - Priority *int32 `json:"priority,omitempty"` - // PolicyMembers - Multiple PolicyMembers for VirtualNetworkGatewayPolicyGroup. - PolicyMembers *[]VirtualNetworkGatewayPolicyGroupMember `json:"policyMembers,omitempty"` - // VngClientConnectionConfigurations - READ-ONLY; List of references to vngClientConnectionConfigurations. - VngClientConnectionConfigurations *[]SubResource `json:"vngClientConnectionConfigurations,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VirtualNetworkGatewayPolicyGroup resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayPolicyGroupProperties. -func (vngpgp VirtualNetworkGatewayPolicyGroupProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngpgp.IsDefault != nil { - objectMap["isDefault"] = vngpgp.IsDefault - } - if vngpgp.Priority != nil { - objectMap["priority"] = vngpgp.Priority - } - if vngpgp.PolicyMembers != nil { - objectMap["policyMembers"] = vngpgp.PolicyMembers - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewayPropertiesFormat virtualNetworkGateway properties. -type VirtualNetworkGatewayPropertiesFormat struct { - // IPConfigurations - IP configurations for virtual network gateway. - IPConfigurations *[]VirtualNetworkGatewayIPConfiguration `json:"ipConfigurations,omitempty"` - // GatewayType - The type of this virtual network gateway. Possible values include: 'VirtualNetworkGatewayTypeVpn', 'VirtualNetworkGatewayTypeExpressRoute', 'VirtualNetworkGatewayTypeLocalGateway' - GatewayType VirtualNetworkGatewayType `json:"gatewayType,omitempty"` - // VpnType - The type of this virtual network gateway. Possible values include: 'PolicyBased', 'RouteBased' - VpnType VpnType `json:"vpnType,omitempty"` - // VpnGatewayGeneration - The generation for this VirtualNetworkGateway. Must be None if gatewayType is not VPN. Possible values include: 'VpnGatewayGenerationNone', 'VpnGatewayGenerationGeneration1', 'VpnGatewayGenerationGeneration2' - VpnGatewayGeneration VpnGatewayGeneration `json:"vpnGatewayGeneration,omitempty"` - // EnableBgp - Whether BGP is enabled for this virtual network gateway or not. - EnableBgp *bool `json:"enableBgp,omitempty"` - // EnablePrivateIPAddress - Whether private IP needs to be enabled on this gateway for connections or not. - EnablePrivateIPAddress *bool `json:"enablePrivateIpAddress,omitempty"` - // ActiveActive - ActiveActive flag. - ActiveActive *bool `json:"activeActive,omitempty"` - // DisableIPSecReplayProtection - disableIPSecReplayProtection flag. - DisableIPSecReplayProtection *bool `json:"disableIPSecReplayProtection,omitempty"` - // GatewayDefaultSite - The reference to the LocalNetworkGateway resource which represents local network site having default routes. Assign Null value in case of removing existing default site setting. - GatewayDefaultSite *SubResource `json:"gatewayDefaultSite,omitempty"` - // Sku - The reference to the VirtualNetworkGatewaySku resource which represents the SKU selected for Virtual network gateway. - Sku *VirtualNetworkGatewaySku `json:"sku,omitempty"` - // VpnClientConfiguration - The reference to the VpnClientConfiguration resource which represents the P2S VpnClient configurations. - VpnClientConfiguration *VpnClientConfiguration `json:"vpnClientConfiguration,omitempty"` - // VirtualNetworkGatewayPolicyGroups - The reference to the VirtualNetworkGatewayPolicyGroup resource which represents the available VirtualNetworkGatewayPolicyGroup for the gateway. - VirtualNetworkGatewayPolicyGroups *[]VirtualNetworkGatewayPolicyGroup `json:"virtualNetworkGatewayPolicyGroups,omitempty"` - // BgpSettings - Virtual network gateway's BGP speaker settings. - BgpSettings *BgpSettings `json:"bgpSettings,omitempty"` - // CustomRoutes - The reference to the address space resource which represents the custom routes address space specified by the customer for virtual network gateway and VpnClient. - CustomRoutes *AddressSpace `json:"customRoutes,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the virtual network gateway resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the virtual network gateway resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // EnableDNSForwarding - Whether dns forwarding is enabled or not. - EnableDNSForwarding *bool `json:"enableDnsForwarding,omitempty"` - // InboundDNSForwardingEndpoint - READ-ONLY; The IP address allocated by the gateway to which dns requests can be sent. - InboundDNSForwardingEndpoint *string `json:"inboundDnsForwardingEndpoint,omitempty"` - // VNetExtendedLocationResourceID - Customer vnet resource id. VirtualNetworkGateway of type local gateway is associated with the customer vnet. - VNetExtendedLocationResourceID *string `json:"vNetExtendedLocationResourceId,omitempty"` - // NatRules - NatRules for virtual network gateway. - NatRules *[]VirtualNetworkGatewayNatRule `json:"natRules,omitempty"` - // EnableBgpRouteTranslationForNat - EnableBgpRouteTranslationForNat flag. - EnableBgpRouteTranslationForNat *bool `json:"enableBgpRouteTranslationForNat,omitempty"` - // AllowVirtualWanTraffic - Configures this gateway to accept traffic from remote Virtual WAN networks. - AllowVirtualWanTraffic *bool `json:"allowVirtualWanTraffic,omitempty"` - // AllowRemoteVnetTraffic - Configure this gateway to accept traffic from other Azure Virtual Networks. This configuration does not support connectivity to Azure Virtual WAN. - AllowRemoteVnetTraffic *bool `json:"allowRemoteVnetTraffic,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewayPropertiesFormat. -func (vngpf VirtualNetworkGatewayPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngpf.IPConfigurations != nil { - objectMap["ipConfigurations"] = vngpf.IPConfigurations - } - if vngpf.GatewayType != "" { - objectMap["gatewayType"] = vngpf.GatewayType - } - if vngpf.VpnType != "" { - objectMap["vpnType"] = vngpf.VpnType - } - if vngpf.VpnGatewayGeneration != "" { - objectMap["vpnGatewayGeneration"] = vngpf.VpnGatewayGeneration - } - if vngpf.EnableBgp != nil { - objectMap["enableBgp"] = vngpf.EnableBgp - } - if vngpf.EnablePrivateIPAddress != nil { - objectMap["enablePrivateIpAddress"] = vngpf.EnablePrivateIPAddress - } - if vngpf.ActiveActive != nil { - objectMap["activeActive"] = vngpf.ActiveActive - } - if vngpf.DisableIPSecReplayProtection != nil { - objectMap["disableIPSecReplayProtection"] = vngpf.DisableIPSecReplayProtection - } - if vngpf.GatewayDefaultSite != nil { - objectMap["gatewayDefaultSite"] = vngpf.GatewayDefaultSite - } - if vngpf.Sku != nil { - objectMap["sku"] = vngpf.Sku - } - if vngpf.VpnClientConfiguration != nil { - objectMap["vpnClientConfiguration"] = vngpf.VpnClientConfiguration - } - if vngpf.VirtualNetworkGatewayPolicyGroups != nil { - objectMap["virtualNetworkGatewayPolicyGroups"] = vngpf.VirtualNetworkGatewayPolicyGroups - } - if vngpf.BgpSettings != nil { - objectMap["bgpSettings"] = vngpf.BgpSettings - } - if vngpf.CustomRoutes != nil { - objectMap["customRoutes"] = vngpf.CustomRoutes - } - if vngpf.EnableDNSForwarding != nil { - objectMap["enableDnsForwarding"] = vngpf.EnableDNSForwarding - } - if vngpf.VNetExtendedLocationResourceID != nil { - objectMap["vNetExtendedLocationResourceId"] = vngpf.VNetExtendedLocationResourceID - } - if vngpf.NatRules != nil { - objectMap["natRules"] = vngpf.NatRules - } - if vngpf.EnableBgpRouteTranslationForNat != nil { - objectMap["enableBgpRouteTranslationForNat"] = vngpf.EnableBgpRouteTranslationForNat - } - if vngpf.AllowVirtualWanTraffic != nil { - objectMap["allowVirtualWanTraffic"] = vngpf.AllowVirtualWanTraffic - } - if vngpf.AllowRemoteVnetTraffic != nil { - objectMap["allowRemoteVnetTraffic"] = vngpf.AllowRemoteVnetTraffic - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkGatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (VirtualNetworkGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysCreateOrUpdateFuture.Result. -func (future *VirtualNetworkGatewaysCreateOrUpdateFuture) result(client VirtualNetworkGatewaysClient) (vng VirtualNetworkGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vng.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vng.Response.Response, err = future.GetResult(sender); err == nil && vng.Response.Response.StatusCode != http.StatusNoContent { - vng, err = client.CreateOrUpdateResponder(vng.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysCreateOrUpdateFuture", "Result", vng.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkGatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysDeleteFuture.Result. -func (future *VirtualNetworkGatewaysDeleteFuture) result(client VirtualNetworkGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworkGatewaysDisconnectVirtualNetworkGatewayVpnConnectionsFuture an abstraction for monitoring -// and retrieving the results of a long-running operation. -type VirtualNetworkGatewaysDisconnectVirtualNetworkGatewayVpnConnectionsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysDisconnectVirtualNetworkGatewayVpnConnectionsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysDisconnectVirtualNetworkGatewayVpnConnectionsFuture.Result. -func (future *VirtualNetworkGatewaysDisconnectVirtualNetworkGatewayVpnConnectionsFuture) result(client VirtualNetworkGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysDisconnectVirtualNetworkGatewayVpnConnectionsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysDisconnectVirtualNetworkGatewayVpnConnectionsFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworkGatewaysGeneratevpnclientpackageFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewaysGeneratevpnclientpackageFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGeneratevpnclientpackageFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGeneratevpnclientpackageFuture.Result. -func (future *VirtualNetworkGatewaysGeneratevpnclientpackageFuture) result(client VirtualNetworkGatewaysClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGeneratevpnclientpackageFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGeneratevpnclientpackageFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.GeneratevpnclientpackageResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGeneratevpnclientpackageFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysGenerateVpnProfileFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type VirtualNetworkGatewaysGenerateVpnProfileFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGenerateVpnProfileFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGenerateVpnProfileFuture.Result. -func (future *VirtualNetworkGatewaysGenerateVpnProfileFuture) result(client VirtualNetworkGatewaysClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGenerateVpnProfileFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGenerateVpnProfileFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.GenerateVpnProfileResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGenerateVpnProfileFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysGetAdvertisedRoutesFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type VirtualNetworkGatewaysGetAdvertisedRoutesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (GatewayRouteListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGetAdvertisedRoutesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGetAdvertisedRoutesFuture.Result. -func (future *VirtualNetworkGatewaysGetAdvertisedRoutesFuture) result(client VirtualNetworkGatewaysClient) (grlr GatewayRouteListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetAdvertisedRoutesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - grlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGetAdvertisedRoutesFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if grlr.Response.Response, err = future.GetResult(sender); err == nil && grlr.Response.Response.StatusCode != http.StatusNoContent { - grlr, err = client.GetAdvertisedRoutesResponder(grlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetAdvertisedRoutesFuture", "Result", grlr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysGetBgpPeerStatusFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VirtualNetworkGatewaysGetBgpPeerStatusFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (BgpPeerStatusListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGetBgpPeerStatusFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGetBgpPeerStatusFuture.Result. -func (future *VirtualNetworkGatewaysGetBgpPeerStatusFuture) result(client VirtualNetworkGatewaysClient) (bpslr BgpPeerStatusListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetBgpPeerStatusFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - bpslr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGetBgpPeerStatusFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if bpslr.Response.Response, err = future.GetResult(sender); err == nil && bpslr.Response.Response.StatusCode != http.StatusNoContent { - bpslr, err = client.GetBgpPeerStatusResponder(bpslr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetBgpPeerStatusFuture", "Result", bpslr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysGetLearnedRoutesFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VirtualNetworkGatewaysGetLearnedRoutesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (GatewayRouteListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGetLearnedRoutesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGetLearnedRoutesFuture.Result. -func (future *VirtualNetworkGatewaysGetLearnedRoutesFuture) result(client VirtualNetworkGatewaysClient) (grlr GatewayRouteListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetLearnedRoutesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - grlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGetLearnedRoutesFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if grlr.Response.Response, err = future.GetResult(sender); err == nil && grlr.Response.Response.StatusCode != http.StatusNoContent { - grlr, err = client.GetLearnedRoutesResponder(grlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetLearnedRoutesFuture", "Result", grlr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysGetVpnclientConnectionHealthFuture an abstraction for monitoring and retrieving -// the results of a long-running operation. -type VirtualNetworkGatewaysGetVpnclientConnectionHealthFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (VpnClientConnectionHealthDetailListResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGetVpnclientConnectionHealthFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGetVpnclientConnectionHealthFuture.Result. -func (future *VirtualNetworkGatewaysGetVpnclientConnectionHealthFuture) result(client VirtualNetworkGatewaysClient) (vcchdlr VpnClientConnectionHealthDetailListResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetVpnclientConnectionHealthFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vcchdlr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGetVpnclientConnectionHealthFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vcchdlr.Response.Response, err = future.GetResult(sender); err == nil && vcchdlr.Response.Response.StatusCode != http.StatusNoContent { - vcchdlr, err = client.GetVpnclientConnectionHealthResponder(vcchdlr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetVpnclientConnectionHealthFuture", "Result", vcchdlr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (VpnClientIPsecParameters, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture.Result. -func (future *VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture) result(client VirtualNetworkGatewaysClient) (vcipp VpnClientIPsecParameters, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vcipp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vcipp.Response.Response, err = future.GetResult(sender); err == nil && vcipp.Response.Response.StatusCode != http.StatusNoContent { - vcipp, err = client.GetVpnclientIpsecParametersResponder(vcipp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture", "Result", vcipp.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysGetVpnProfilePackageURLFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewaysGetVpnProfilePackageURLFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysGetVpnProfilePackageURLFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysGetVpnProfilePackageURLFuture.Result. -func (future *VirtualNetworkGatewaysGetVpnProfilePackageURLFuture) result(client VirtualNetworkGatewaysClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetVpnProfilePackageURLFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysGetVpnProfilePackageURLFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.GetVpnProfilePackageURLResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysGetVpnProfilePackageURLFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaySku virtualNetworkGatewaySku details. -type VirtualNetworkGatewaySku struct { - // Name - Gateway SKU name. Possible values include: 'VirtualNetworkGatewaySkuNameBasic', 'VirtualNetworkGatewaySkuNameHighPerformance', 'VirtualNetworkGatewaySkuNameStandard', 'VirtualNetworkGatewaySkuNameUltraPerformance', 'VirtualNetworkGatewaySkuNameVpnGw1', 'VirtualNetworkGatewaySkuNameVpnGw2', 'VirtualNetworkGatewaySkuNameVpnGw3', 'VirtualNetworkGatewaySkuNameVpnGw4', 'VirtualNetworkGatewaySkuNameVpnGw5', 'VirtualNetworkGatewaySkuNameVpnGw1AZ', 'VirtualNetworkGatewaySkuNameVpnGw2AZ', 'VirtualNetworkGatewaySkuNameVpnGw3AZ', 'VirtualNetworkGatewaySkuNameVpnGw4AZ', 'VirtualNetworkGatewaySkuNameVpnGw5AZ', 'VirtualNetworkGatewaySkuNameErGw1AZ', 'VirtualNetworkGatewaySkuNameErGw2AZ', 'VirtualNetworkGatewaySkuNameErGw3AZ' - Name VirtualNetworkGatewaySkuName `json:"name,omitempty"` - // Tier - Gateway SKU tier. Possible values include: 'VirtualNetworkGatewaySkuTierBasic', 'VirtualNetworkGatewaySkuTierHighPerformance', 'VirtualNetworkGatewaySkuTierStandard', 'VirtualNetworkGatewaySkuTierUltraPerformance', 'VirtualNetworkGatewaySkuTierVpnGw1', 'VirtualNetworkGatewaySkuTierVpnGw2', 'VirtualNetworkGatewaySkuTierVpnGw3', 'VirtualNetworkGatewaySkuTierVpnGw4', 'VirtualNetworkGatewaySkuTierVpnGw5', 'VirtualNetworkGatewaySkuTierVpnGw1AZ', 'VirtualNetworkGatewaySkuTierVpnGw2AZ', 'VirtualNetworkGatewaySkuTierVpnGw3AZ', 'VirtualNetworkGatewaySkuTierVpnGw4AZ', 'VirtualNetworkGatewaySkuTierVpnGw5AZ', 'VirtualNetworkGatewaySkuTierErGw1AZ', 'VirtualNetworkGatewaySkuTierErGw2AZ', 'VirtualNetworkGatewaySkuTierErGw3AZ' - Tier VirtualNetworkGatewaySkuTier `json:"tier,omitempty"` - // Capacity - READ-ONLY; The capacity. - Capacity *int32 `json:"capacity,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkGatewaySku. -func (vngs VirtualNetworkGatewaySku) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vngs.Name != "" { - objectMap["name"] = vngs.Name - } - if vngs.Tier != "" { - objectMap["tier"] = vngs.Tier - } - return json.Marshal(objectMap) -} - -// VirtualNetworkGatewaysResetFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkGatewaysResetFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (VirtualNetworkGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysResetFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysResetFuture.Result. -func (future *VirtualNetworkGatewaysResetFuture) result(client VirtualNetworkGatewaysClient) (vng VirtualNetworkGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysResetFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vng.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysResetFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vng.Response.Response, err = future.GetResult(sender); err == nil && vng.Response.Response.StatusCode != http.StatusNoContent { - vng, err = client.ResetResponder(vng.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysResetFuture", "Result", vng.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysResetVpnClientSharedKeyFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewaysResetVpnClientSharedKeyFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysResetVpnClientSharedKeyFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysResetVpnClientSharedKeyFuture.Result. -func (future *VirtualNetworkGatewaysResetVpnClientSharedKeyFuture) result(client VirtualNetworkGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysResetVpnClientSharedKeyFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysResetVpnClientSharedKeyFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (VpnClientIPsecParameters, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture.Result. -func (future *VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture) result(client VirtualNetworkGatewaysClient) (vcipp VpnClientIPsecParameters, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vcipp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vcipp.Response.Response, err = future.GetResult(sender); err == nil && vcipp.Response.Response.StatusCode != http.StatusNoContent { - vcipp, err = client.SetVpnclientIpsecParametersResponder(vcipp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture", "Result", vcipp.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysStartPacketCaptureFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type VirtualNetworkGatewaysStartPacketCaptureFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysStartPacketCaptureFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysStartPacketCaptureFuture.Result. -func (future *VirtualNetworkGatewaysStartPacketCaptureFuture) result(client VirtualNetworkGatewaysClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysStartPacketCaptureFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysStartPacketCaptureFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.StartPacketCaptureResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysStartPacketCaptureFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysStopPacketCaptureFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type VirtualNetworkGatewaysStopPacketCaptureFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysStopPacketCaptureFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysStopPacketCaptureFuture.Result. -func (future *VirtualNetworkGatewaysStopPacketCaptureFuture) result(client VirtualNetworkGatewaysClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysStopPacketCaptureFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysStopPacketCaptureFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.StopPacketCaptureResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysStopPacketCaptureFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkGatewaysUpdateTagsFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkGatewaysUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkGatewaysClient) (VirtualNetworkGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkGatewaysUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkGatewaysUpdateTagsFuture.Result. -func (future *VirtualNetworkGatewaysUpdateTagsFuture) result(client VirtualNetworkGatewaysClient) (vng VirtualNetworkGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vng.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkGatewaysUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vng.Response.Response, err = future.GetResult(sender); err == nil && vng.Response.Response.StatusCode != http.StatusNoContent { - vng, err = client.UpdateTagsResponder(vng.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysUpdateTagsFuture", "Result", vng.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkListResult response for the ListVirtualNetworks API service call. -type VirtualNetworkListResult struct { - autorest.Response `json:"-"` - // Value - A list of VirtualNetwork resources in a resource group. - Value *[]VirtualNetwork `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualNetworkListResultIterator provides access to a complete listing of VirtualNetwork values. -type VirtualNetworkListResultIterator struct { - i int - page VirtualNetworkListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkListResultIterator) Response() VirtualNetworkListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkListResultIterator) Value() VirtualNetwork { - if !iter.page.NotDone() { - return VirtualNetwork{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkListResultIterator type. -func NewVirtualNetworkListResultIterator(page VirtualNetworkListResultPage) VirtualNetworkListResultIterator { - return VirtualNetworkListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vnlr VirtualNetworkListResult) IsEmpty() bool { - return vnlr.Value == nil || len(*vnlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vnlr VirtualNetworkListResult) hasNextLink() bool { - return vnlr.NextLink != nil && len(*vnlr.NextLink) != 0 -} - -// virtualNetworkListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vnlr VirtualNetworkListResult) virtualNetworkListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vnlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vnlr.NextLink))) -} - -// VirtualNetworkListResultPage contains a page of VirtualNetwork values. -type VirtualNetworkListResultPage struct { - fn func(context.Context, VirtualNetworkListResult) (VirtualNetworkListResult, error) - vnlr VirtualNetworkListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vnlr) - if err != nil { - return err - } - page.vnlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkListResultPage) NotDone() bool { - return !page.vnlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkListResultPage) Response() VirtualNetworkListResult { - return page.vnlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkListResultPage) Values() []VirtualNetwork { - if page.vnlr.IsEmpty() { - return nil - } - return *page.vnlr.Value -} - -// Creates a new instance of the VirtualNetworkListResultPage type. -func NewVirtualNetworkListResultPage(cur VirtualNetworkListResult, getNextPage func(context.Context, VirtualNetworkListResult) (VirtualNetworkListResult, error)) VirtualNetworkListResultPage { - return VirtualNetworkListResultPage{ - fn: getNextPage, - vnlr: cur, - } -} - -// VirtualNetworkListUsageResult response for the virtual networks GetUsage API service call. -type VirtualNetworkListUsageResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; VirtualNetwork usage stats. - Value *[]VirtualNetworkUsage `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkListUsageResult. -func (vnlur VirtualNetworkListUsageResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vnlur.NextLink != nil { - objectMap["nextLink"] = vnlur.NextLink - } - return json.Marshal(objectMap) -} - -// VirtualNetworkListUsageResultIterator provides access to a complete listing of VirtualNetworkUsage -// values. -type VirtualNetworkListUsageResultIterator struct { - i int - page VirtualNetworkListUsageResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkListUsageResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkListUsageResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkListUsageResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkListUsageResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkListUsageResultIterator) Response() VirtualNetworkListUsageResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkListUsageResultIterator) Value() VirtualNetworkUsage { - if !iter.page.NotDone() { - return VirtualNetworkUsage{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkListUsageResultIterator type. -func NewVirtualNetworkListUsageResultIterator(page VirtualNetworkListUsageResultPage) VirtualNetworkListUsageResultIterator { - return VirtualNetworkListUsageResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vnlur VirtualNetworkListUsageResult) IsEmpty() bool { - return vnlur.Value == nil || len(*vnlur.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vnlur VirtualNetworkListUsageResult) hasNextLink() bool { - return vnlur.NextLink != nil && len(*vnlur.NextLink) != 0 -} - -// virtualNetworkListUsageResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vnlur VirtualNetworkListUsageResult) virtualNetworkListUsageResultPreparer(ctx context.Context) (*http.Request, error) { - if !vnlur.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vnlur.NextLink))) -} - -// VirtualNetworkListUsageResultPage contains a page of VirtualNetworkUsage values. -type VirtualNetworkListUsageResultPage struct { - fn func(context.Context, VirtualNetworkListUsageResult) (VirtualNetworkListUsageResult, error) - vnlur VirtualNetworkListUsageResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkListUsageResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkListUsageResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vnlur) - if err != nil { - return err - } - page.vnlur = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkListUsageResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkListUsageResultPage) NotDone() bool { - return !page.vnlur.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkListUsageResultPage) Response() VirtualNetworkListUsageResult { - return page.vnlur -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkListUsageResultPage) Values() []VirtualNetworkUsage { - if page.vnlur.IsEmpty() { - return nil - } - return *page.vnlur.Value -} - -// Creates a new instance of the VirtualNetworkListUsageResultPage type. -func NewVirtualNetworkListUsageResultPage(cur VirtualNetworkListUsageResult, getNextPage func(context.Context, VirtualNetworkListUsageResult) (VirtualNetworkListUsageResult, error)) VirtualNetworkListUsageResultPage { - return VirtualNetworkListUsageResultPage{ - fn: getNextPage, - vnlur: cur, - } -} - -// VirtualNetworkPeering peerings in a virtual network resource. -type VirtualNetworkPeering struct { - autorest.Response `json:"-"` - // VirtualNetworkPeeringPropertiesFormat - Properties of the virtual network peering. - *VirtualNetworkPeeringPropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkPeering. -func (vnp VirtualNetworkPeering) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vnp.VirtualNetworkPeeringPropertiesFormat != nil { - objectMap["properties"] = vnp.VirtualNetworkPeeringPropertiesFormat - } - if vnp.Name != nil { - objectMap["name"] = vnp.Name - } - if vnp.Type != nil { - objectMap["type"] = vnp.Type - } - if vnp.ID != nil { - objectMap["id"] = vnp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkPeering struct. -func (vnp *VirtualNetworkPeering) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkPeeringPropertiesFormat VirtualNetworkPeeringPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkPeeringPropertiesFormat) - if err != nil { - return err - } - vnp.VirtualNetworkPeeringPropertiesFormat = &virtualNetworkPeeringPropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vnp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vnp.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vnp.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vnp.ID = &ID - } - } - } - - return nil -} - -// VirtualNetworkPeeringListResult response for ListSubnets API service call. Retrieves all subnets that -// belong to a virtual network. -type VirtualNetworkPeeringListResult struct { - autorest.Response `json:"-"` - // Value - The peerings in a virtual network. - Value *[]VirtualNetworkPeering `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualNetworkPeeringListResultIterator provides access to a complete listing of VirtualNetworkPeering -// values. -type VirtualNetworkPeeringListResultIterator struct { - i int - page VirtualNetworkPeeringListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkPeeringListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkPeeringListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkPeeringListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkPeeringListResultIterator) Response() VirtualNetworkPeeringListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkPeeringListResultIterator) Value() VirtualNetworkPeering { - if !iter.page.NotDone() { - return VirtualNetworkPeering{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkPeeringListResultIterator type. -func NewVirtualNetworkPeeringListResultIterator(page VirtualNetworkPeeringListResultPage) VirtualNetworkPeeringListResultIterator { - return VirtualNetworkPeeringListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vnplr VirtualNetworkPeeringListResult) IsEmpty() bool { - return vnplr.Value == nil || len(*vnplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vnplr VirtualNetworkPeeringListResult) hasNextLink() bool { - return vnplr.NextLink != nil && len(*vnplr.NextLink) != 0 -} - -// virtualNetworkPeeringListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vnplr VirtualNetworkPeeringListResult) virtualNetworkPeeringListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vnplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vnplr.NextLink))) -} - -// VirtualNetworkPeeringListResultPage contains a page of VirtualNetworkPeering values. -type VirtualNetworkPeeringListResultPage struct { - fn func(context.Context, VirtualNetworkPeeringListResult) (VirtualNetworkPeeringListResult, error) - vnplr VirtualNetworkPeeringListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkPeeringListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vnplr) - if err != nil { - return err - } - page.vnplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkPeeringListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkPeeringListResultPage) NotDone() bool { - return !page.vnplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkPeeringListResultPage) Response() VirtualNetworkPeeringListResult { - return page.vnplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkPeeringListResultPage) Values() []VirtualNetworkPeering { - if page.vnplr.IsEmpty() { - return nil - } - return *page.vnplr.Value -} - -// Creates a new instance of the VirtualNetworkPeeringListResultPage type. -func NewVirtualNetworkPeeringListResultPage(cur VirtualNetworkPeeringListResult, getNextPage func(context.Context, VirtualNetworkPeeringListResult) (VirtualNetworkPeeringListResult, error)) VirtualNetworkPeeringListResultPage { - return VirtualNetworkPeeringListResultPage{ - fn: getNextPage, - vnplr: cur, - } -} - -// VirtualNetworkPeeringPropertiesFormat properties of the virtual network peering. -type VirtualNetworkPeeringPropertiesFormat struct { - // AllowVirtualNetworkAccess - Whether the VMs in the local virtual network space would be able to access the VMs in remote virtual network space. - AllowVirtualNetworkAccess *bool `json:"allowVirtualNetworkAccess,omitempty"` - // AllowForwardedTraffic - Whether the forwarded traffic from the VMs in the local virtual network will be allowed/disallowed in remote virtual network. - AllowForwardedTraffic *bool `json:"allowForwardedTraffic,omitempty"` - // AllowGatewayTransit - If gateway links can be used in remote virtual networking to link to this virtual network. - AllowGatewayTransit *bool `json:"allowGatewayTransit,omitempty"` - // UseRemoteGateways - If remote gateways can be used on this virtual network. If the flag is set to true, and allowGatewayTransit on remote peering is also true, virtual network will use gateways of remote virtual network for transit. Only one peering can have this flag set to true. This flag cannot be set if virtual network already has a gateway. - UseRemoteGateways *bool `json:"useRemoteGateways,omitempty"` - // RemoteVirtualNetwork - The reference to the remote virtual network. The remote virtual network can be in the same or different region (preview). See here to register for the preview and learn more (https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-create-peering). - RemoteVirtualNetwork *SubResource `json:"remoteVirtualNetwork,omitempty"` - // RemoteAddressSpace - The reference to the address space peered with the remote virtual network. - RemoteAddressSpace *AddressSpace `json:"remoteAddressSpace,omitempty"` - // RemoteVirtualNetworkAddressSpace - The reference to the current address space of the remote virtual network. - RemoteVirtualNetworkAddressSpace *AddressSpace `json:"remoteVirtualNetworkAddressSpace,omitempty"` - // RemoteBgpCommunities - The reference to the remote virtual network's Bgp Communities. - RemoteBgpCommunities *VirtualNetworkBgpCommunities `json:"remoteBgpCommunities,omitempty"` - // RemoteVirtualNetworkEncryption - READ-ONLY; The reference to the remote virtual network's encryption - RemoteVirtualNetworkEncryption *VirtualNetworkEncryption `json:"remoteVirtualNetworkEncryption,omitempty"` - // PeeringState - The status of the virtual network peering. Possible values include: 'VirtualNetworkPeeringStateInitiated', 'VirtualNetworkPeeringStateConnected', 'VirtualNetworkPeeringStateDisconnected' - PeeringState VirtualNetworkPeeringState `json:"peeringState,omitempty"` - // PeeringSyncLevel - The peering sync status of the virtual network peering. Possible values include: 'FullyInSync', 'RemoteNotInSync', 'LocalNotInSync', 'LocalAndRemoteNotInSync' - PeeringSyncLevel VirtualNetworkPeeringLevel `json:"peeringSyncLevel,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the virtual network peering resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // DoNotVerifyRemoteGateways - If we need to verify the provisioning state of the remote gateway. - DoNotVerifyRemoteGateways *bool `json:"doNotVerifyRemoteGateways,omitempty"` - // ResourceGUID - READ-ONLY; The resourceGuid property of the Virtual Network peering resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkPeeringPropertiesFormat. -func (vnppf VirtualNetworkPeeringPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vnppf.AllowVirtualNetworkAccess != nil { - objectMap["allowVirtualNetworkAccess"] = vnppf.AllowVirtualNetworkAccess - } - if vnppf.AllowForwardedTraffic != nil { - objectMap["allowForwardedTraffic"] = vnppf.AllowForwardedTraffic - } - if vnppf.AllowGatewayTransit != nil { - objectMap["allowGatewayTransit"] = vnppf.AllowGatewayTransit - } - if vnppf.UseRemoteGateways != nil { - objectMap["useRemoteGateways"] = vnppf.UseRemoteGateways - } - if vnppf.RemoteVirtualNetwork != nil { - objectMap["remoteVirtualNetwork"] = vnppf.RemoteVirtualNetwork - } - if vnppf.RemoteAddressSpace != nil { - objectMap["remoteAddressSpace"] = vnppf.RemoteAddressSpace - } - if vnppf.RemoteVirtualNetworkAddressSpace != nil { - objectMap["remoteVirtualNetworkAddressSpace"] = vnppf.RemoteVirtualNetworkAddressSpace - } - if vnppf.RemoteBgpCommunities != nil { - objectMap["remoteBgpCommunities"] = vnppf.RemoteBgpCommunities - } - if vnppf.PeeringState != "" { - objectMap["peeringState"] = vnppf.PeeringState - } - if vnppf.PeeringSyncLevel != "" { - objectMap["peeringSyncLevel"] = vnppf.PeeringSyncLevel - } - if vnppf.DoNotVerifyRemoteGateways != nil { - objectMap["doNotVerifyRemoteGateways"] = vnppf.DoNotVerifyRemoteGateways - } - return json.Marshal(objectMap) -} - -// VirtualNetworkPeeringsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkPeeringsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkPeeringsClient) (VirtualNetworkPeering, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkPeeringsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkPeeringsCreateOrUpdateFuture.Result. -func (future *VirtualNetworkPeeringsCreateOrUpdateFuture) result(client VirtualNetworkPeeringsClient) (vnp VirtualNetworkPeering, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vnp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkPeeringsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vnp.Response.Response, err = future.GetResult(sender); err == nil && vnp.Response.Response.StatusCode != http.StatusNoContent { - vnp, err = client.CreateOrUpdateResponder(vnp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsCreateOrUpdateFuture", "Result", vnp.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkPeeringsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkPeeringsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkPeeringsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkPeeringsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkPeeringsDeleteFuture.Result. -func (future *VirtualNetworkPeeringsDeleteFuture) result(client VirtualNetworkPeeringsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkPeeringsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworkPropertiesFormat properties of the virtual network. -type VirtualNetworkPropertiesFormat struct { - // AddressSpace - The AddressSpace that contains an array of IP address ranges that can be used by subnets. - AddressSpace *AddressSpace `json:"addressSpace,omitempty"` - // DhcpOptions - The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual network. - DhcpOptions *DhcpOptions `json:"dhcpOptions,omitempty"` - // FlowTimeoutInMinutes - The FlowTimeout value (in minutes) for the Virtual Network - FlowTimeoutInMinutes *int32 `json:"flowTimeoutInMinutes,omitempty"` - // Subnets - A list of subnets in a Virtual Network. - Subnets *[]Subnet `json:"subnets,omitempty"` - // VirtualNetworkPeerings - A list of peerings in a Virtual Network. - VirtualNetworkPeerings *[]VirtualNetworkPeering `json:"virtualNetworkPeerings,omitempty"` - // ResourceGUID - READ-ONLY; The resourceGuid property of the Virtual Network resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the virtual network resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // EnableDdosProtection - Indicates if DDoS protection is enabled for all the protected resources in the virtual network. It requires a DDoS protection plan associated with the resource. - EnableDdosProtection *bool `json:"enableDdosProtection,omitempty"` - // EnableVMProtection - Indicates if VM protection is enabled for all the subnets in the virtual network. - EnableVMProtection *bool `json:"enableVmProtection,omitempty"` - // DdosProtectionPlan - The DDoS protection plan associated with the virtual network. - DdosProtectionPlan *SubResource `json:"ddosProtectionPlan,omitempty"` - // BgpCommunities - Bgp Communities sent over ExpressRoute with each route corresponding to a prefix in this VNET. - BgpCommunities *VirtualNetworkBgpCommunities `json:"bgpCommunities,omitempty"` - // Encryption - Indicates if encryption is enabled on virtual network and if VM without encryption is allowed in encrypted VNet. - Encryption *VirtualNetworkEncryption `json:"encryption,omitempty"` - // IPAllocations - Array of IpAllocation which reference this VNET. - IPAllocations *[]SubResource `json:"ipAllocations,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkPropertiesFormat. -func (vnpf VirtualNetworkPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vnpf.AddressSpace != nil { - objectMap["addressSpace"] = vnpf.AddressSpace - } - if vnpf.DhcpOptions != nil { - objectMap["dhcpOptions"] = vnpf.DhcpOptions - } - if vnpf.FlowTimeoutInMinutes != nil { - objectMap["flowTimeoutInMinutes"] = vnpf.FlowTimeoutInMinutes - } - if vnpf.Subnets != nil { - objectMap["subnets"] = vnpf.Subnets - } - if vnpf.VirtualNetworkPeerings != nil { - objectMap["virtualNetworkPeerings"] = vnpf.VirtualNetworkPeerings - } - if vnpf.EnableDdosProtection != nil { - objectMap["enableDdosProtection"] = vnpf.EnableDdosProtection - } - if vnpf.EnableVMProtection != nil { - objectMap["enableVmProtection"] = vnpf.EnableVMProtection - } - if vnpf.DdosProtectionPlan != nil { - objectMap["ddosProtectionPlan"] = vnpf.DdosProtectionPlan - } - if vnpf.BgpCommunities != nil { - objectMap["bgpCommunities"] = vnpf.BgpCommunities - } - if vnpf.Encryption != nil { - objectMap["encryption"] = vnpf.Encryption - } - if vnpf.IPAllocations != nil { - objectMap["ipAllocations"] = vnpf.IPAllocations - } - return json.Marshal(objectMap) -} - -// VirtualNetworksCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworksCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworksClient) (VirtualNetwork, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworksCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworksCreateOrUpdateFuture.Result. -func (future *VirtualNetworksCreateOrUpdateFuture) result(client VirtualNetworksClient) (vn VirtualNetwork, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vn.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworksCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vn.Response.Response, err = future.GetResult(sender); err == nil && vn.Response.Response.StatusCode != http.StatusNoContent { - vn, err = client.CreateOrUpdateResponder(vn.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksCreateOrUpdateFuture", "Result", vn.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworksDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualNetworksDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworksClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworksDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworksDeleteFuture.Result. -func (future *VirtualNetworksDeleteFuture) result(client VirtualNetworksClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworksDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworksListDdosProtectionStatusAllFuture an abstraction for monitoring and retrieving the -// results of a long-running operation. -type VirtualNetworksListDdosProtectionStatusAllFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworksClient) (VirtualNetworkDdosProtectionStatusResultPage, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworksListDdosProtectionStatusAllFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworksListDdosProtectionStatusAllFuture.Result. -func (future *VirtualNetworksListDdosProtectionStatusAllFuture) result(client VirtualNetworksClient) (vndpsrp VirtualNetworkDdosProtectionStatusResultPage, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksListDdosProtectionStatusAllFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vndpsrp.vndpsr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworksListDdosProtectionStatusAllFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vndpsrp.vndpsr.Response.Response, err = future.GetResult(sender); err == nil && vndpsrp.vndpsr.Response.Response.StatusCode != http.StatusNoContent { - vndpsrp, err = client.ListDdosProtectionStatusResponder(vndpsrp.vndpsr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksListDdosProtectionStatusAllFuture", "Result", vndpsrp.vndpsr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworksListDdosProtectionStatusFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type VirtualNetworksListDdosProtectionStatusFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworksClient) (VirtualNetworkDdosProtectionStatusResultPage, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworksListDdosProtectionStatusFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworksListDdosProtectionStatusFuture.Result. -func (future *VirtualNetworksListDdosProtectionStatusFuture) result(client VirtualNetworksClient) (vndpsrp VirtualNetworkDdosProtectionStatusResultPage, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksListDdosProtectionStatusFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vndpsrp.vndpsr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworksListDdosProtectionStatusFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vndpsrp.vndpsr.Response.Response, err = future.GetResult(sender); err == nil && vndpsrp.vndpsr.Response.Response.StatusCode != http.StatusNoContent { - vndpsrp, err = client.ListDdosProtectionStatusResponder(vndpsrp.vndpsr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksListDdosProtectionStatusFuture", "Result", vndpsrp.vndpsr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkTap virtual Network Tap resource. -type VirtualNetworkTap struct { - autorest.Response `json:"-"` - // VirtualNetworkTapPropertiesFormat - Virtual Network Tap Properties. - *VirtualNetworkTapPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkTap. -func (vnt VirtualNetworkTap) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vnt.VirtualNetworkTapPropertiesFormat != nil { - objectMap["properties"] = vnt.VirtualNetworkTapPropertiesFormat - } - if vnt.ID != nil { - objectMap["id"] = vnt.ID - } - if vnt.Location != nil { - objectMap["location"] = vnt.Location - } - if vnt.Tags != nil { - objectMap["tags"] = vnt.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualNetworkTap struct. -func (vnt *VirtualNetworkTap) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualNetworkTapPropertiesFormat VirtualNetworkTapPropertiesFormat - err = json.Unmarshal(*v, &virtualNetworkTapPropertiesFormat) - if err != nil { - return err - } - vnt.VirtualNetworkTapPropertiesFormat = &virtualNetworkTapPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vnt.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vnt.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vnt.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vnt.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vnt.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vnt.Tags = tags - } - } - } - - return nil -} - -// VirtualNetworkTapListResult response for ListVirtualNetworkTap API service call. -type VirtualNetworkTapListResult struct { - autorest.Response `json:"-"` - // Value - A list of VirtualNetworkTaps in a resource group. - Value *[]VirtualNetworkTap `json:"value,omitempty"` - // NextLink - The URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualNetworkTapListResultIterator provides access to a complete listing of VirtualNetworkTap values. -type VirtualNetworkTapListResultIterator struct { - i int - page VirtualNetworkTapListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualNetworkTapListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualNetworkTapListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualNetworkTapListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualNetworkTapListResultIterator) Response() VirtualNetworkTapListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualNetworkTapListResultIterator) Value() VirtualNetworkTap { - if !iter.page.NotDone() { - return VirtualNetworkTap{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualNetworkTapListResultIterator type. -func NewVirtualNetworkTapListResultIterator(page VirtualNetworkTapListResultPage) VirtualNetworkTapListResultIterator { - return VirtualNetworkTapListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vntlr VirtualNetworkTapListResult) IsEmpty() bool { - return vntlr.Value == nil || len(*vntlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vntlr VirtualNetworkTapListResult) hasNextLink() bool { - return vntlr.NextLink != nil && len(*vntlr.NextLink) != 0 -} - -// virtualNetworkTapListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vntlr VirtualNetworkTapListResult) virtualNetworkTapListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vntlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vntlr.NextLink))) -} - -// VirtualNetworkTapListResultPage contains a page of VirtualNetworkTap values. -type VirtualNetworkTapListResultPage struct { - fn func(context.Context, VirtualNetworkTapListResult) (VirtualNetworkTapListResult, error) - vntlr VirtualNetworkTapListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualNetworkTapListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vntlr) - if err != nil { - return err - } - page.vntlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualNetworkTapListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualNetworkTapListResultPage) NotDone() bool { - return !page.vntlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualNetworkTapListResultPage) Response() VirtualNetworkTapListResult { - return page.vntlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualNetworkTapListResultPage) Values() []VirtualNetworkTap { - if page.vntlr.IsEmpty() { - return nil - } - return *page.vntlr.Value -} - -// Creates a new instance of the VirtualNetworkTapListResultPage type. -func NewVirtualNetworkTapListResultPage(cur VirtualNetworkTapListResult, getNextPage func(context.Context, VirtualNetworkTapListResult) (VirtualNetworkTapListResult, error)) VirtualNetworkTapListResultPage { - return VirtualNetworkTapListResultPage{ - fn: getNextPage, - vntlr: cur, - } -} - -// VirtualNetworkTapPropertiesFormat virtual Network Tap properties. -type VirtualNetworkTapPropertiesFormat struct { - // NetworkInterfaceTapConfigurations - READ-ONLY; Specifies the list of resource IDs for the network interface IP configuration that needs to be tapped. - NetworkInterfaceTapConfigurations *[]InterfaceTapConfiguration `json:"networkInterfaceTapConfigurations,omitempty"` - // ResourceGUID - READ-ONLY; The resource GUID property of the virtual network tap resource. - ResourceGUID *string `json:"resourceGuid,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the virtual network tap resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // DestinationNetworkInterfaceIPConfiguration - The reference to the private IP Address of the collector nic that will receive the tap. - DestinationNetworkInterfaceIPConfiguration *InterfaceIPConfiguration `json:"destinationNetworkInterfaceIPConfiguration,omitempty"` - // DestinationLoadBalancerFrontEndIPConfiguration - The reference to the private IP address on the internal Load Balancer that will receive the tap. - DestinationLoadBalancerFrontEndIPConfiguration *FrontendIPConfiguration `json:"destinationLoadBalancerFrontEndIPConfiguration,omitempty"` - // DestinationPort - The VXLAN destination port that will receive the tapped traffic. - DestinationPort *int32 `json:"destinationPort,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkTapPropertiesFormat. -func (vntpf VirtualNetworkTapPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vntpf.DestinationNetworkInterfaceIPConfiguration != nil { - objectMap["destinationNetworkInterfaceIPConfiguration"] = vntpf.DestinationNetworkInterfaceIPConfiguration - } - if vntpf.DestinationLoadBalancerFrontEndIPConfiguration != nil { - objectMap["destinationLoadBalancerFrontEndIPConfiguration"] = vntpf.DestinationLoadBalancerFrontEndIPConfiguration - } - if vntpf.DestinationPort != nil { - objectMap["destinationPort"] = vntpf.DestinationPort - } - return json.Marshal(objectMap) -} - -// VirtualNetworkTapsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkTapsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkTapsClient) (VirtualNetworkTap, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkTapsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkTapsCreateOrUpdateFuture.Result. -func (future *VirtualNetworkTapsCreateOrUpdateFuture) result(client VirtualNetworkTapsClient) (vnt VirtualNetworkTap, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vnt.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkTapsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vnt.Response.Response, err = future.GetResult(sender); err == nil && vnt.Response.Response.StatusCode != http.StatusNoContent { - vnt, err = client.CreateOrUpdateResponder(vnt.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsCreateOrUpdateFuture", "Result", vnt.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualNetworkTapsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualNetworkTapsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualNetworkTapsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualNetworkTapsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualNetworkTapsDeleteFuture.Result. -func (future *VirtualNetworkTapsDeleteFuture) result(client VirtualNetworkTapsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualNetworkTapsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualNetworkUsage usage details for subnet. -type VirtualNetworkUsage struct { - // CurrentValue - READ-ONLY; Indicates number of IPs used from the Subnet. - CurrentValue *float64 `json:"currentValue,omitempty"` - // ID - READ-ONLY; Subnet identifier. - ID *string `json:"id,omitempty"` - // Limit - READ-ONLY; Indicates the size of the subnet. - Limit *float64 `json:"limit,omitempty"` - // Name - READ-ONLY; The name containing common and localized value for usage. - Name *VirtualNetworkUsageName `json:"name,omitempty"` - // Unit - READ-ONLY; Usage units. Returns 'Count'. - Unit *string `json:"unit,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkUsage. -func (vnu VirtualNetworkUsage) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualNetworkUsageName usage strings container. -type VirtualNetworkUsageName struct { - // LocalizedValue - READ-ONLY; Localized subnet size and usage string. - LocalizedValue *string `json:"localizedValue,omitempty"` - // Value - READ-ONLY; Subnet size and usage string. - Value *string `json:"value,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualNetworkUsageName. -func (vnun VirtualNetworkUsageName) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VirtualRouter virtualRouter Resource. -type VirtualRouter struct { - autorest.Response `json:"-"` - // VirtualRouterPropertiesFormat - Properties of the Virtual Router. - *VirtualRouterPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualRouter. -func (vr VirtualRouter) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vr.VirtualRouterPropertiesFormat != nil { - objectMap["properties"] = vr.VirtualRouterPropertiesFormat - } - if vr.ID != nil { - objectMap["id"] = vr.ID - } - if vr.Location != nil { - objectMap["location"] = vr.Location - } - if vr.Tags != nil { - objectMap["tags"] = vr.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualRouter struct. -func (vr *VirtualRouter) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualRouterPropertiesFormat VirtualRouterPropertiesFormat - err = json.Unmarshal(*v, &virtualRouterPropertiesFormat) - if err != nil { - return err - } - vr.VirtualRouterPropertiesFormat = &virtualRouterPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vr.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vr.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vr.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vr.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vr.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vr.Tags = tags - } - } - } - - return nil -} - -// VirtualRouterAutoScaleConfiguration the VirtualHub Router autoscale configuration. -type VirtualRouterAutoScaleConfiguration struct { - // MinCapacity - The minimum number of scale units for VirtualHub Router. - MinCapacity *int32 `json:"minCapacity,omitempty"` -} - -// VirtualRouterListResult response for ListVirtualRouters API service call. -type VirtualRouterListResult struct { - autorest.Response `json:"-"` - // Value - List of Virtual Routers. - Value *[]VirtualRouter `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualRouterListResultIterator provides access to a complete listing of VirtualRouter values. -type VirtualRouterListResultIterator struct { - i int - page VirtualRouterListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualRouterListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRouterListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualRouterListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualRouterListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualRouterListResultIterator) Response() VirtualRouterListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualRouterListResultIterator) Value() VirtualRouter { - if !iter.page.NotDone() { - return VirtualRouter{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualRouterListResultIterator type. -func NewVirtualRouterListResultIterator(page VirtualRouterListResultPage) VirtualRouterListResultIterator { - return VirtualRouterListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vrlr VirtualRouterListResult) IsEmpty() bool { - return vrlr.Value == nil || len(*vrlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vrlr VirtualRouterListResult) hasNextLink() bool { - return vrlr.NextLink != nil && len(*vrlr.NextLink) != 0 -} - -// virtualRouterListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vrlr VirtualRouterListResult) virtualRouterListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vrlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vrlr.NextLink))) -} - -// VirtualRouterListResultPage contains a page of VirtualRouter values. -type VirtualRouterListResultPage struct { - fn func(context.Context, VirtualRouterListResult) (VirtualRouterListResult, error) - vrlr VirtualRouterListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualRouterListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRouterListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vrlr) - if err != nil { - return err - } - page.vrlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualRouterListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualRouterListResultPage) NotDone() bool { - return !page.vrlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualRouterListResultPage) Response() VirtualRouterListResult { - return page.vrlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualRouterListResultPage) Values() []VirtualRouter { - if page.vrlr.IsEmpty() { - return nil - } - return *page.vrlr.Value -} - -// Creates a new instance of the VirtualRouterListResultPage type. -func NewVirtualRouterListResultPage(cur VirtualRouterListResult, getNextPage func(context.Context, VirtualRouterListResult) (VirtualRouterListResult, error)) VirtualRouterListResultPage { - return VirtualRouterListResultPage{ - fn: getNextPage, - vrlr: cur, - } -} - -// VirtualRouterPeering virtual Router Peering resource. -type VirtualRouterPeering struct { - autorest.Response `json:"-"` - // VirtualRouterPeeringProperties - The properties of the Virtual Router Peering. - *VirtualRouterPeeringProperties `json:"properties,omitempty"` - // Name - Name of the virtual router peering that is unique within a virtual router. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Peering type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualRouterPeering. -func (vrp VirtualRouterPeering) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vrp.VirtualRouterPeeringProperties != nil { - objectMap["properties"] = vrp.VirtualRouterPeeringProperties - } - if vrp.Name != nil { - objectMap["name"] = vrp.Name - } - if vrp.ID != nil { - objectMap["id"] = vrp.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualRouterPeering struct. -func (vrp *VirtualRouterPeering) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualRouterPeeringProperties VirtualRouterPeeringProperties - err = json.Unmarshal(*v, &virtualRouterPeeringProperties) - if err != nil { - return err - } - vrp.VirtualRouterPeeringProperties = &virtualRouterPeeringProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vrp.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vrp.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vrp.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vrp.ID = &ID - } - } - } - - return nil -} - -// VirtualRouterPeeringListResult response for ListVirtualRouterPeerings API service call. -type VirtualRouterPeeringListResult struct { - autorest.Response `json:"-"` - // Value - List of VirtualRouterPeerings in a VirtualRouter. - Value *[]VirtualRouterPeering `json:"value,omitempty"` - // NextLink - URL to get the next set of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// VirtualRouterPeeringListResultIterator provides access to a complete listing of VirtualRouterPeering -// values. -type VirtualRouterPeeringListResultIterator struct { - i int - page VirtualRouterPeeringListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *VirtualRouterPeeringListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRouterPeeringListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *VirtualRouterPeeringListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter VirtualRouterPeeringListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter VirtualRouterPeeringListResultIterator) Response() VirtualRouterPeeringListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter VirtualRouterPeeringListResultIterator) Value() VirtualRouterPeering { - if !iter.page.NotDone() { - return VirtualRouterPeering{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the VirtualRouterPeeringListResultIterator type. -func NewVirtualRouterPeeringListResultIterator(page VirtualRouterPeeringListResultPage) VirtualRouterPeeringListResultIterator { - return VirtualRouterPeeringListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (vrplr VirtualRouterPeeringListResult) IsEmpty() bool { - return vrplr.Value == nil || len(*vrplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (vrplr VirtualRouterPeeringListResult) hasNextLink() bool { - return vrplr.NextLink != nil && len(*vrplr.NextLink) != 0 -} - -// virtualRouterPeeringListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (vrplr VirtualRouterPeeringListResult) virtualRouterPeeringListResultPreparer(ctx context.Context) (*http.Request, error) { - if !vrplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(vrplr.NextLink))) -} - -// VirtualRouterPeeringListResultPage contains a page of VirtualRouterPeering values. -type VirtualRouterPeeringListResultPage struct { - fn func(context.Context, VirtualRouterPeeringListResult) (VirtualRouterPeeringListResult, error) - vrplr VirtualRouterPeeringListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *VirtualRouterPeeringListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRouterPeeringListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.vrplr) - if err != nil { - return err - } - page.vrplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *VirtualRouterPeeringListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page VirtualRouterPeeringListResultPage) NotDone() bool { - return !page.vrplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page VirtualRouterPeeringListResultPage) Response() VirtualRouterPeeringListResult { - return page.vrplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page VirtualRouterPeeringListResultPage) Values() []VirtualRouterPeering { - if page.vrplr.IsEmpty() { - return nil - } - return *page.vrplr.Value -} - -// Creates a new instance of the VirtualRouterPeeringListResultPage type. -func NewVirtualRouterPeeringListResultPage(cur VirtualRouterPeeringListResult, getNextPage func(context.Context, VirtualRouterPeeringListResult) (VirtualRouterPeeringListResult, error)) VirtualRouterPeeringListResultPage { - return VirtualRouterPeeringListResultPage{ - fn: getNextPage, - vrplr: cur, - } -} - -// VirtualRouterPeeringProperties properties of the rule group. -type VirtualRouterPeeringProperties struct { - // PeerAsn - Peer ASN. - PeerAsn *int64 `json:"peerAsn,omitempty"` - // PeerIP - Peer IP. - PeerIP *string `json:"peerIp,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualRouterPeeringProperties. -func (vrpp VirtualRouterPeeringProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vrpp.PeerAsn != nil { - objectMap["peerAsn"] = vrpp.PeerAsn - } - if vrpp.PeerIP != nil { - objectMap["peerIp"] = vrpp.PeerIP - } - return json.Marshal(objectMap) -} - -// VirtualRouterPeeringsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualRouterPeeringsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualRouterPeeringsClient) (VirtualRouterPeering, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualRouterPeeringsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualRouterPeeringsCreateOrUpdateFuture.Result. -func (future *VirtualRouterPeeringsCreateOrUpdateFuture) result(client VirtualRouterPeeringsClient) (vrp VirtualRouterPeering, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vrp.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualRouterPeeringsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vrp.Response.Response, err = future.GetResult(sender); err == nil && vrp.Response.Response.StatusCode != http.StatusNoContent { - vrp, err = client.CreateOrUpdateResponder(vrp.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsCreateOrUpdateFuture", "Result", vrp.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualRouterPeeringsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualRouterPeeringsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualRouterPeeringsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualRouterPeeringsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualRouterPeeringsDeleteFuture.Result. -func (future *VirtualRouterPeeringsDeleteFuture) result(client VirtualRouterPeeringsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualRouterPeeringsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualRouterPropertiesFormat virtual Router definition. -type VirtualRouterPropertiesFormat struct { - // VirtualRouterAsn - VirtualRouter ASN. - VirtualRouterAsn *int64 `json:"virtualRouterAsn,omitempty"` - // VirtualRouterIps - VirtualRouter IPs. - VirtualRouterIps *[]string `json:"virtualRouterIps,omitempty"` - // HostedSubnet - The Subnet on which VirtualRouter is hosted. - HostedSubnet *SubResource `json:"hostedSubnet,omitempty"` - // HostedGateway - The Gateway on which VirtualRouter is hosted. - HostedGateway *SubResource `json:"hostedGateway,omitempty"` - // Peerings - READ-ONLY; List of references to VirtualRouterPeerings. - Peerings *[]SubResource `json:"peerings,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualRouterPropertiesFormat. -func (vrpf VirtualRouterPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vrpf.VirtualRouterAsn != nil { - objectMap["virtualRouterAsn"] = vrpf.VirtualRouterAsn - } - if vrpf.VirtualRouterIps != nil { - objectMap["virtualRouterIps"] = vrpf.VirtualRouterIps - } - if vrpf.HostedSubnet != nil { - objectMap["hostedSubnet"] = vrpf.HostedSubnet - } - if vrpf.HostedGateway != nil { - objectMap["hostedGateway"] = vrpf.HostedGateway - } - return json.Marshal(objectMap) -} - -// VirtualRoutersCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualRoutersCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualRoutersClient) (VirtualRouter, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualRoutersCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualRoutersCreateOrUpdateFuture.Result. -func (future *VirtualRoutersCreateOrUpdateFuture) result(client VirtualRoutersClient) (vr VirtualRouter, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualRoutersCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vr.Response.Response, err = future.GetResult(sender); err == nil && vr.Response.Response.StatusCode != http.StatusNoContent { - vr, err = client.CreateOrUpdateResponder(vr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersCreateOrUpdateFuture", "Result", vr.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualRoutersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualRoutersDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualRoutersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualRoutersDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualRoutersDeleteFuture.Result. -func (future *VirtualRoutersDeleteFuture) result(client VirtualRoutersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualRoutersDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualWAN virtualWAN Resource. -type VirtualWAN struct { - autorest.Response `json:"-"` - // VirtualWanProperties - Properties of the virtual WAN. - *VirtualWanProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VirtualWAN. -func (vw VirtualWAN) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vw.VirtualWanProperties != nil { - objectMap["properties"] = vw.VirtualWanProperties - } - if vw.ID != nil { - objectMap["id"] = vw.ID - } - if vw.Location != nil { - objectMap["location"] = vw.Location - } - if vw.Tags != nil { - objectMap["tags"] = vw.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VirtualWAN struct. -func (vw *VirtualWAN) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var virtualWanProperties VirtualWanProperties - err = json.Unmarshal(*v, &virtualWanProperties) - if err != nil { - return err - } - vw.VirtualWanProperties = &virtualWanProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vw.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vw.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vw.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vw.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vw.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vw.Tags = tags - } - } - } - - return nil -} - -// VirtualWanProperties parameters for VirtualWAN. -type VirtualWanProperties struct { - // DisableVpnEncryption - Vpn encryption to be disabled or not. - DisableVpnEncryption *bool `json:"disableVpnEncryption,omitempty"` - // VirtualHubs - READ-ONLY; List of VirtualHubs in the VirtualWAN. - VirtualHubs *[]SubResource `json:"virtualHubs,omitempty"` - // VpnSites - READ-ONLY; List of VpnSites in the VirtualWAN. - VpnSites *[]SubResource `json:"vpnSites,omitempty"` - // AllowBranchToBranchTraffic - True if branch to branch traffic is allowed. - AllowBranchToBranchTraffic *bool `json:"allowBranchToBranchTraffic,omitempty"` - // AllowVnetToVnetTraffic - True if Vnet to Vnet traffic is allowed. - AllowVnetToVnetTraffic *bool `json:"allowVnetToVnetTraffic,omitempty"` - // Office365LocalBreakoutCategory - The office local breakout category. Possible values include: 'OfficeTrafficCategoryOptimize', 'OfficeTrafficCategoryOptimizeAndAllow', 'OfficeTrafficCategoryAll', 'OfficeTrafficCategoryNone' - Office365LocalBreakoutCategory OfficeTrafficCategory `json:"office365LocalBreakoutCategory,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the virtual WAN resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // Type - The type of the VirtualWAN. - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for VirtualWanProperties. -func (vwp VirtualWanProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vwp.DisableVpnEncryption != nil { - objectMap["disableVpnEncryption"] = vwp.DisableVpnEncryption - } - if vwp.AllowBranchToBranchTraffic != nil { - objectMap["allowBranchToBranchTraffic"] = vwp.AllowBranchToBranchTraffic - } - if vwp.AllowVnetToVnetTraffic != nil { - objectMap["allowVnetToVnetTraffic"] = vwp.AllowVnetToVnetTraffic - } - if vwp.Office365LocalBreakoutCategory != "" { - objectMap["office365LocalBreakoutCategory"] = vwp.Office365LocalBreakoutCategory - } - if vwp.Type != nil { - objectMap["type"] = vwp.Type - } - return json.Marshal(objectMap) -} - -// VirtualWansCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VirtualWansCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualWansClient) (VirtualWAN, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualWansCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualWansCreateOrUpdateFuture.Result. -func (future *VirtualWansCreateOrUpdateFuture) result(client VirtualWansClient) (vw VirtualWAN, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vw.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualWansCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vw.Response.Response, err = future.GetResult(sender); err == nil && vw.Response.Response.StatusCode != http.StatusNoContent { - vw, err = client.CreateOrUpdateResponder(vw.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansCreateOrUpdateFuture", "Result", vw.Response.Response, "Failure responding to request") - } - } - return -} - -// VirtualWansDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VirtualWansDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VirtualWansClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VirtualWansDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VirtualWansDeleteFuture.Result. -func (future *VirtualWansDeleteFuture) result(client VirtualWansClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VirtualWansDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VirtualWanSecurityProvider collection of SecurityProviders. -type VirtualWanSecurityProvider struct { - // Name - Name of the security provider. - Name *string `json:"name,omitempty"` - // URL - Url of the security provider. - URL *string `json:"url,omitempty"` - // Type - Name of the security provider. Possible values include: 'External', 'Native' - Type VirtualWanSecurityProviderType `json:"type,omitempty"` -} - -// VirtualWanSecurityProviders collection of SecurityProviders. -type VirtualWanSecurityProviders struct { - autorest.Response `json:"-"` - // SupportedProviders - List of VirtualWAN security providers. - SupportedProviders *[]VirtualWanSecurityProvider `json:"supportedProviders,omitempty"` -} - -// VirtualWanVpnProfileParameters virtual Wan Vpn profile parameters Vpn profile generation. -type VirtualWanVpnProfileParameters struct { - // VpnServerConfigurationResourceID - VpnServerConfiguration partial resource uri with which VirtualWan is associated to. - VpnServerConfigurationResourceID *string `json:"vpnServerConfigurationResourceId,omitempty"` - // AuthenticationMethod - VPN client authentication method. Possible values include: 'EAPTLS', 'EAPMSCHAPv2' - AuthenticationMethod AuthenticationMethod `json:"authenticationMethod,omitempty"` -} - -// VM describes a Virtual Machine. -type VM struct { - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VM. -func (vVar VM) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vVar.ID != nil { - objectMap["id"] = vVar.ID - } - if vVar.Location != nil { - objectMap["location"] = vVar.Location - } - if vVar.Tags != nil { - objectMap["tags"] = vVar.Tags - } - return json.Marshal(objectMap) -} - -// VnetRoute list of routes that control routing from VirtualHub into a virtual network connection. -type VnetRoute struct { - // StaticRoutesConfig - Configuration for static routes on this HubVnetConnection. - StaticRoutesConfig *StaticRoutesConfig `json:"staticRoutesConfig,omitempty"` - // StaticRoutes - List of all Static Routes. - StaticRoutes *[]StaticRoute `json:"staticRoutes,omitempty"` - // BgpConnections - READ-ONLY; The list of references to HubBgpConnection objects. - BgpConnections *[]SubResource `json:"bgpConnections,omitempty"` -} - -// MarshalJSON is the custom marshaler for VnetRoute. -func (vr VnetRoute) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vr.StaticRoutesConfig != nil { - objectMap["staticRoutesConfig"] = vr.StaticRoutesConfig - } - if vr.StaticRoutes != nil { - objectMap["staticRoutes"] = vr.StaticRoutes - } - return json.Marshal(objectMap) -} - -// VngClientConnectionConfiguration a vpn client connection configuration for client connection -// configuration. -type VngClientConnectionConfiguration struct { - // VngClientConnectionConfigurationProperties - Properties of the vpn client root certificate. - *VngClientConnectionConfigurationProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VngClientConnectionConfiguration. -func (vccc VngClientConnectionConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vccc.VngClientConnectionConfigurationProperties != nil { - objectMap["properties"] = vccc.VngClientConnectionConfigurationProperties - } - if vccc.Name != nil { - objectMap["name"] = vccc.Name - } - if vccc.ID != nil { - objectMap["id"] = vccc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VngClientConnectionConfiguration struct. -func (vccc *VngClientConnectionConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vngClientConnectionConfigurationProperties VngClientConnectionConfigurationProperties - err = json.Unmarshal(*v, &vngClientConnectionConfigurationProperties) - if err != nil { - return err - } - vccc.VngClientConnectionConfigurationProperties = &vngClientConnectionConfigurationProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vccc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vccc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vccc.ID = &ID - } - } - } - - return nil -} - -// VngClientConnectionConfigurationProperties properties of VngClientConnectionConfiguration. -type VngClientConnectionConfigurationProperties struct { - // VpnClientAddressPool - The reference to the address space resource which represents Address space for P2S VpnClient. - VpnClientAddressPool *AddressSpace `json:"vpnClientAddressPool,omitempty"` - // VirtualNetworkGatewayPolicyGroups - List of references to virtualNetworkGatewayPolicyGroups - VirtualNetworkGatewayPolicyGroups *[]SubResource `json:"virtualNetworkGatewayPolicyGroups,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VngClientConnectionConfiguration resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VngClientConnectionConfigurationProperties. -func (vcccp VngClientConnectionConfigurationProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vcccp.VpnClientAddressPool != nil { - objectMap["vpnClientAddressPool"] = vcccp.VpnClientAddressPool - } - if vcccp.VirtualNetworkGatewayPolicyGroups != nil { - objectMap["virtualNetworkGatewayPolicyGroups"] = vcccp.VirtualNetworkGatewayPolicyGroups - } - return json.Marshal(objectMap) -} - -// VpnClientConfiguration vpnClientConfiguration for P2S client. -type VpnClientConfiguration struct { - // VpnClientAddressPool - The reference to the address space resource which represents Address space for P2S VpnClient. - VpnClientAddressPool *AddressSpace `json:"vpnClientAddressPool,omitempty"` - // VpnClientRootCertificates - VpnClientRootCertificate for virtual network gateway. - VpnClientRootCertificates *[]VpnClientRootCertificate `json:"vpnClientRootCertificates,omitempty"` - // VpnClientRevokedCertificates - VpnClientRevokedCertificate for Virtual network gateway. - VpnClientRevokedCertificates *[]VpnClientRevokedCertificate `json:"vpnClientRevokedCertificates,omitempty"` - // VpnClientProtocols - VpnClientProtocols for Virtual network gateway. - VpnClientProtocols *[]VpnClientProtocol `json:"vpnClientProtocols,omitempty"` - // VpnAuthenticationTypes - VPN authentication types for the virtual network gateway.. - VpnAuthenticationTypes *[]VpnAuthenticationType `json:"vpnAuthenticationTypes,omitempty"` - // VpnClientIpsecPolicies - VpnClientIpsecPolicies for virtual network gateway P2S client. - VpnClientIpsecPolicies *[]IpsecPolicy `json:"vpnClientIpsecPolicies,omitempty"` - // RadiusServerAddress - The radius server address property of the VirtualNetworkGateway resource for vpn client connection. - RadiusServerAddress *string `json:"radiusServerAddress,omitempty"` - // RadiusServerSecret - The radius secret property of the VirtualNetworkGateway resource for vpn client connection. - RadiusServerSecret *string `json:"radiusServerSecret,omitempty"` - // RadiusServers - The radiusServers property for multiple radius server configuration. - RadiusServers *[]RadiusServer `json:"radiusServers,omitempty"` - // AadTenant - The AADTenant property of the VirtualNetworkGateway resource for vpn client connection used for AAD authentication. - AadTenant *string `json:"aadTenant,omitempty"` - // AadAudience - The AADAudience property of the VirtualNetworkGateway resource for vpn client connection used for AAD authentication. - AadAudience *string `json:"aadAudience,omitempty"` - // AadIssuer - The AADIssuer property of the VirtualNetworkGateway resource for vpn client connection used for AAD authentication. - AadIssuer *string `json:"aadIssuer,omitempty"` - // VngClientConnectionConfigurations - per ip address pool connection policy for virtual network gateway P2S client. - VngClientConnectionConfigurations *[]VngClientConnectionConfiguration `json:"vngClientConnectionConfigurations,omitempty"` -} - -// VpnClientConnectionHealth vpnClientConnectionHealth properties. -type VpnClientConnectionHealth struct { - // TotalIngressBytesTransferred - READ-ONLY; Total of the Ingress Bytes Transferred in this P2S Vpn connection. - TotalIngressBytesTransferred *int64 `json:"totalIngressBytesTransferred,omitempty"` - // TotalEgressBytesTransferred - READ-ONLY; Total of the Egress Bytes Transferred in this connection. - TotalEgressBytesTransferred *int64 `json:"totalEgressBytesTransferred,omitempty"` - // VpnClientConnectionsCount - The total of p2s vpn clients connected at this time to this P2SVpnGateway. - VpnClientConnectionsCount *int32 `json:"vpnClientConnectionsCount,omitempty"` - // AllocatedIPAddresses - List of allocated ip addresses to the connected p2s vpn clients. - AllocatedIPAddresses *[]string `json:"allocatedIpAddresses,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnClientConnectionHealth. -func (vcch VpnClientConnectionHealth) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vcch.VpnClientConnectionsCount != nil { - objectMap["vpnClientConnectionsCount"] = vcch.VpnClientConnectionsCount - } - if vcch.AllocatedIPAddresses != nil { - objectMap["allocatedIpAddresses"] = vcch.AllocatedIPAddresses - } - return json.Marshal(objectMap) -} - -// VpnClientConnectionHealthDetail VPN client connection health detail. -type VpnClientConnectionHealthDetail struct { - // VpnConnectionID - READ-ONLY; The vpn client Id. - VpnConnectionID *string `json:"vpnConnectionId,omitempty"` - // VpnConnectionDuration - READ-ONLY; The duration time of a connected vpn client. - VpnConnectionDuration *int64 `json:"vpnConnectionDuration,omitempty"` - // VpnConnectionTime - READ-ONLY; The start time of a connected vpn client. - VpnConnectionTime *string `json:"vpnConnectionTime,omitempty"` - // PublicIPAddress - READ-ONLY; The public Ip of a connected vpn client. - PublicIPAddress *string `json:"publicIpAddress,omitempty"` - // PrivateIPAddress - READ-ONLY; The assigned private Ip of a connected vpn client. - PrivateIPAddress *string `json:"privateIpAddress,omitempty"` - // VpnUserName - READ-ONLY; The user name of a connected vpn client. - VpnUserName *string `json:"vpnUserName,omitempty"` - // MaxBandwidth - READ-ONLY; The max band width. - MaxBandwidth *int64 `json:"maxBandwidth,omitempty"` - // EgressPacketsTransferred - READ-ONLY; The egress packets per second. - EgressPacketsTransferred *int64 `json:"egressPacketsTransferred,omitempty"` - // EgressBytesTransferred - READ-ONLY; The egress bytes per second. - EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` - // IngressPacketsTransferred - READ-ONLY; The ingress packets per second. - IngressPacketsTransferred *int64 `json:"ingressPacketsTransferred,omitempty"` - // IngressBytesTransferred - READ-ONLY; The ingress bytes per second. - IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` - // MaxPacketsPerSecond - READ-ONLY; The max packets transferred per second. - MaxPacketsPerSecond *int64 `json:"maxPacketsPerSecond,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnClientConnectionHealthDetail. -func (vcchd VpnClientConnectionHealthDetail) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VpnClientConnectionHealthDetailListResult list of virtual network gateway vpn client connection health. -type VpnClientConnectionHealthDetailListResult struct { - autorest.Response `json:"-"` - // Value - List of vpn client connection health. - Value *[]VpnClientConnectionHealthDetail `json:"value,omitempty"` -} - -// VpnClientIPsecParameters an IPSec parameters for a virtual network gateway P2S connection. -type VpnClientIPsecParameters struct { - autorest.Response `json:"-"` - // SaLifeTimeSeconds - The IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds for P2S client. - SaLifeTimeSeconds *int32 `json:"saLifeTimeSeconds,omitempty"` - // SaDataSizeKilobytes - The IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB for P2S client.. - SaDataSizeKilobytes *int32 `json:"saDataSizeKilobytes,omitempty"` - // IpsecEncryption - The IPSec encryption algorithm (IKE phase 1). Possible values include: 'IpsecEncryptionNone', 'IpsecEncryptionDES', 'IpsecEncryptionDES3', 'IpsecEncryptionAES128', 'IpsecEncryptionAES192', 'IpsecEncryptionAES256', 'IpsecEncryptionGCMAES128', 'IpsecEncryptionGCMAES192', 'IpsecEncryptionGCMAES256' - IpsecEncryption IpsecEncryption `json:"ipsecEncryption,omitempty"` - // IpsecIntegrity - The IPSec integrity algorithm (IKE phase 1). Possible values include: 'IpsecIntegrityMD5', 'IpsecIntegritySHA1', 'IpsecIntegritySHA256', 'IpsecIntegrityGCMAES128', 'IpsecIntegrityGCMAES192', 'IpsecIntegrityGCMAES256' - IpsecIntegrity IpsecIntegrity `json:"ipsecIntegrity,omitempty"` - // IkeEncryption - The IKE encryption algorithm (IKE phase 2). Possible values include: 'DES', 'DES3', 'AES128', 'AES192', 'AES256', 'GCMAES256', 'GCMAES128' - IkeEncryption IkeEncryption `json:"ikeEncryption,omitempty"` - // IkeIntegrity - The IKE integrity algorithm (IKE phase 2). Possible values include: 'IkeIntegrityMD5', 'IkeIntegritySHA1', 'IkeIntegritySHA256', 'IkeIntegritySHA384', 'IkeIntegrityGCMAES256', 'IkeIntegrityGCMAES128' - IkeIntegrity IkeIntegrity `json:"ikeIntegrity,omitempty"` - // DhGroup - The DH Group used in IKE Phase 1 for initial SA. Possible values include: 'DhGroupNone', 'DhGroupDHGroup1', 'DhGroupDHGroup2', 'DhGroupDHGroup14', 'DhGroupDHGroup2048', 'DhGroupECP256', 'DhGroupECP384', 'DhGroupDHGroup24' - DhGroup DhGroup `json:"dhGroup,omitempty"` - // PfsGroup - The Pfs Group used in IKE Phase 2 for new child SA. Possible values include: 'PfsGroupNone', 'PfsGroupPFS1', 'PfsGroupPFS2', 'PfsGroupPFS2048', 'PfsGroupECP256', 'PfsGroupECP384', 'PfsGroupPFS24', 'PfsGroupPFS14', 'PfsGroupPFSMM' - PfsGroup PfsGroup `json:"pfsGroup,omitempty"` -} - -// VpnClientParameters vpn Client Parameters for package generation. -type VpnClientParameters struct { - // ProcessorArchitecture - VPN client Processor Architecture. Possible values include: 'Amd64', 'X86' - ProcessorArchitecture ProcessorArchitecture `json:"processorArchitecture,omitempty"` - // AuthenticationMethod - VPN client authentication method. Possible values include: 'EAPTLS', 'EAPMSCHAPv2' - AuthenticationMethod AuthenticationMethod `json:"authenticationMethod,omitempty"` - // RadiusServerAuthCertificate - The public certificate data for the radius server authentication certificate as a Base-64 encoded string. Required only if external radius authentication has been configured with EAPTLS authentication. - RadiusServerAuthCertificate *string `json:"radiusServerAuthCertificate,omitempty"` - // ClientRootCertificates - A list of client root certificates public certificate data encoded as Base-64 strings. Optional parameter for external radius based authentication with EAPTLS. - ClientRootCertificates *[]string `json:"clientRootCertificates,omitempty"` -} - -// VpnClientRevokedCertificate VPN client revoked certificate of virtual network gateway. -type VpnClientRevokedCertificate struct { - // VpnClientRevokedCertificatePropertiesFormat - Properties of the vpn client revoked certificate. - *VpnClientRevokedCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnClientRevokedCertificate. -func (vcrc VpnClientRevokedCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vcrc.VpnClientRevokedCertificatePropertiesFormat != nil { - objectMap["properties"] = vcrc.VpnClientRevokedCertificatePropertiesFormat - } - if vcrc.Name != nil { - objectMap["name"] = vcrc.Name - } - if vcrc.ID != nil { - objectMap["id"] = vcrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnClientRevokedCertificate struct. -func (vcrc *VpnClientRevokedCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnClientRevokedCertificatePropertiesFormat VpnClientRevokedCertificatePropertiesFormat - err = json.Unmarshal(*v, &vpnClientRevokedCertificatePropertiesFormat) - if err != nil { - return err - } - vcrc.VpnClientRevokedCertificatePropertiesFormat = &vpnClientRevokedCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vcrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vcrc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vcrc.ID = &ID - } - } - } - - return nil -} - -// VpnClientRevokedCertificatePropertiesFormat properties of the revoked VPN client certificate of virtual -// network gateway. -type VpnClientRevokedCertificatePropertiesFormat struct { - // Thumbprint - The revoked VPN client certificate thumbprint. - Thumbprint *string `json:"thumbprint,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VPN client revoked certificate resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnClientRevokedCertificatePropertiesFormat. -func (vcrcpf VpnClientRevokedCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vcrcpf.Thumbprint != nil { - objectMap["thumbprint"] = vcrcpf.Thumbprint - } - return json.Marshal(objectMap) -} - -// VpnClientRootCertificate VPN client root certificate of virtual network gateway. -type VpnClientRootCertificate struct { - // VpnClientRootCertificatePropertiesFormat - Properties of the vpn client root certificate. - *VpnClientRootCertificatePropertiesFormat `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnClientRootCertificate. -func (vcrc VpnClientRootCertificate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vcrc.VpnClientRootCertificatePropertiesFormat != nil { - objectMap["properties"] = vcrc.VpnClientRootCertificatePropertiesFormat - } - if vcrc.Name != nil { - objectMap["name"] = vcrc.Name - } - if vcrc.ID != nil { - objectMap["id"] = vcrc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnClientRootCertificate struct. -func (vcrc *VpnClientRootCertificate) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnClientRootCertificatePropertiesFormat VpnClientRootCertificatePropertiesFormat - err = json.Unmarshal(*v, &vpnClientRootCertificatePropertiesFormat) - if err != nil { - return err - } - vcrc.VpnClientRootCertificatePropertiesFormat = &vpnClientRootCertificatePropertiesFormat - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vcrc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vcrc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vcrc.ID = &ID - } - } - } - - return nil -} - -// VpnClientRootCertificatePropertiesFormat properties of SSL certificates of application gateway. -type VpnClientRootCertificatePropertiesFormat struct { - // PublicCertData - The certificate public data. - PublicCertData *string `json:"publicCertData,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VPN client root certificate resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnClientRootCertificatePropertiesFormat. -func (vcrcpf VpnClientRootCertificatePropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vcrcpf.PublicCertData != nil { - objectMap["publicCertData"] = vcrcpf.PublicCertData - } - return json.Marshal(objectMap) -} - -// VpnConnection vpnConnection Resource. -type VpnConnection struct { - autorest.Response `json:"-"` - // VpnConnectionProperties - Properties of the VPN connection. - *VpnConnectionProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnConnection. -func (vc VpnConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vc.VpnConnectionProperties != nil { - objectMap["properties"] = vc.VpnConnectionProperties - } - if vc.Name != nil { - objectMap["name"] = vc.Name - } - if vc.ID != nil { - objectMap["id"] = vc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnConnection struct. -func (vc *VpnConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnConnectionProperties VpnConnectionProperties - err = json.Unmarshal(*v, &vpnConnectionProperties) - if err != nil { - return err - } - vc.VpnConnectionProperties = &vpnConnectionProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vc.ID = &ID - } - } - } - - return nil -} - -// VpnConnectionPacketCaptureStartParameters vpn Connection packet capture parameters supplied to start -// packet capture on gateway connection. -type VpnConnectionPacketCaptureStartParameters struct { - // FilterData - Start Packet capture parameters on vpn connection. - FilterData *string `json:"filterData,omitempty"` - // LinkConnectionNames - List of site link connection names. - LinkConnectionNames *[]string `json:"linkConnectionNames,omitempty"` -} - -// VpnConnectionPacketCaptureStopParameters vpn Connection packet capture parameters supplied to stop -// packet capture on gateway connection. -type VpnConnectionPacketCaptureStopParameters struct { - // SasURL - SAS url for packet capture on vpn connection. - SasURL *string `json:"sasUrl,omitempty"` - // LinkConnectionNames - List of site link connection names. - LinkConnectionNames *[]string `json:"linkConnectionNames,omitempty"` -} - -// VpnConnectionProperties parameters for VpnConnection. -type VpnConnectionProperties struct { - // RemoteVpnSite - Id of the connected vpn site. - RemoteVpnSite *SubResource `json:"remoteVpnSite,omitempty"` - // RoutingWeight - Routing weight for vpn connection. - RoutingWeight *int32 `json:"routingWeight,omitempty"` - // DpdTimeoutSeconds - DPD timeout in seconds for vpn connection. - DpdTimeoutSeconds *int32 `json:"dpdTimeoutSeconds,omitempty"` - // ConnectionStatus - The connection status. Possible values include: 'VpnConnectionStatusUnknown', 'VpnConnectionStatusConnecting', 'VpnConnectionStatusConnected', 'VpnConnectionStatusNotConnected' - ConnectionStatus VpnConnectionStatus `json:"connectionStatus,omitempty"` - // VpnConnectionProtocolType - Connection protocol used for this connection. Possible values include: 'IKEv2', 'IKEv1' - VpnConnectionProtocolType VirtualNetworkGatewayConnectionProtocol `json:"vpnConnectionProtocolType,omitempty"` - // IngressBytesTransferred - READ-ONLY; Ingress bytes transferred. - IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` - // EgressBytesTransferred - READ-ONLY; Egress bytes transferred. - EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` - // ConnectionBandwidth - Expected bandwidth in MBPS. - ConnectionBandwidth *int32 `json:"connectionBandwidth,omitempty"` - // SharedKey - SharedKey for the vpn connection. - SharedKey *string `json:"sharedKey,omitempty"` - // EnableBgp - EnableBgp flag. - EnableBgp *bool `json:"enableBgp,omitempty"` - // UsePolicyBasedTrafficSelectors - Enable policy-based traffic selectors. - UsePolicyBasedTrafficSelectors *bool `json:"usePolicyBasedTrafficSelectors,omitempty"` - // IpsecPolicies - The IPSec Policies to be considered by this connection. - IpsecPolicies *[]IpsecPolicy `json:"ipsecPolicies,omitempty"` - // TrafficSelectorPolicies - The Traffic Selector Policies to be considered by this connection. - TrafficSelectorPolicies *[]TrafficSelectorPolicy `json:"trafficSelectorPolicies,omitempty"` - // EnableRateLimiting - EnableBgp flag. - EnableRateLimiting *bool `json:"enableRateLimiting,omitempty"` - // EnableInternetSecurity - Enable internet security. - EnableInternetSecurity *bool `json:"enableInternetSecurity,omitempty"` - // UseLocalAzureIPAddress - Use local azure ip to initiate connection. - UseLocalAzureIPAddress *bool `json:"useLocalAzureIpAddress,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VPN connection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // VpnLinkConnections - List of all vpn site link connections to the gateway. - VpnLinkConnections *[]VpnSiteLinkConnection `json:"vpnLinkConnections,omitempty"` - // RoutingConfiguration - The Routing Configuration indicating the associated and propagated route tables on this connection. - RoutingConfiguration *RoutingConfiguration `json:"routingConfiguration,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnConnectionProperties. -func (vcp VpnConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vcp.RemoteVpnSite != nil { - objectMap["remoteVpnSite"] = vcp.RemoteVpnSite - } - if vcp.RoutingWeight != nil { - objectMap["routingWeight"] = vcp.RoutingWeight - } - if vcp.DpdTimeoutSeconds != nil { - objectMap["dpdTimeoutSeconds"] = vcp.DpdTimeoutSeconds - } - if vcp.ConnectionStatus != "" { - objectMap["connectionStatus"] = vcp.ConnectionStatus - } - if vcp.VpnConnectionProtocolType != "" { - objectMap["vpnConnectionProtocolType"] = vcp.VpnConnectionProtocolType - } - if vcp.ConnectionBandwidth != nil { - objectMap["connectionBandwidth"] = vcp.ConnectionBandwidth - } - if vcp.SharedKey != nil { - objectMap["sharedKey"] = vcp.SharedKey - } - if vcp.EnableBgp != nil { - objectMap["enableBgp"] = vcp.EnableBgp - } - if vcp.UsePolicyBasedTrafficSelectors != nil { - objectMap["usePolicyBasedTrafficSelectors"] = vcp.UsePolicyBasedTrafficSelectors - } - if vcp.IpsecPolicies != nil { - objectMap["ipsecPolicies"] = vcp.IpsecPolicies - } - if vcp.TrafficSelectorPolicies != nil { - objectMap["trafficSelectorPolicies"] = vcp.TrafficSelectorPolicies - } - if vcp.EnableRateLimiting != nil { - objectMap["enableRateLimiting"] = vcp.EnableRateLimiting - } - if vcp.EnableInternetSecurity != nil { - objectMap["enableInternetSecurity"] = vcp.EnableInternetSecurity - } - if vcp.UseLocalAzureIPAddress != nil { - objectMap["useLocalAzureIpAddress"] = vcp.UseLocalAzureIPAddress - } - if vcp.VpnLinkConnections != nil { - objectMap["vpnLinkConnections"] = vcp.VpnLinkConnections - } - if vcp.RoutingConfiguration != nil { - objectMap["routingConfiguration"] = vcp.RoutingConfiguration - } - return json.Marshal(objectMap) -} - -// VpnConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VpnConnectionsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnConnectionsClient) (VpnConnection, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnConnectionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnConnectionsCreateOrUpdateFuture.Result. -func (future *VpnConnectionsCreateOrUpdateFuture) result(client VpnConnectionsClient) (vc VpnConnection, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnConnectionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vc.Response.Response, err = future.GetResult(sender); err == nil && vc.Response.Response.StatusCode != http.StatusNoContent { - vc, err = client.CreateOrUpdateResponder(vc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsCreateOrUpdateFuture", "Result", vc.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VpnConnectionsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnConnectionsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnConnectionsDeleteFuture.Result. -func (future *VpnConnectionsDeleteFuture) result(client VpnConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnConnectionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VpnConnectionsStartPacketCaptureFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VpnConnectionsStartPacketCaptureFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnConnectionsClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnConnectionsStartPacketCaptureFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnConnectionsStartPacketCaptureFuture.Result. -func (future *VpnConnectionsStartPacketCaptureFuture) result(client VpnConnectionsClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsStartPacketCaptureFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnConnectionsStartPacketCaptureFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.StartPacketCaptureResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsStartPacketCaptureFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnConnectionsStopPacketCaptureFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VpnConnectionsStopPacketCaptureFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnConnectionsClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnConnectionsStopPacketCaptureFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnConnectionsStopPacketCaptureFuture.Result. -func (future *VpnConnectionsStopPacketCaptureFuture) result(client VpnConnectionsClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsStopPacketCaptureFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnConnectionsStopPacketCaptureFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.StopPacketCaptureResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsStopPacketCaptureFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnDeviceScriptParameters vpn device configuration script generation parameters. -type VpnDeviceScriptParameters struct { - // Vendor - The vendor for the vpn device. - Vendor *string `json:"vendor,omitempty"` - // DeviceFamily - The device family for the vpn device. - DeviceFamily *string `json:"deviceFamily,omitempty"` - // FirmwareVersion - The firmware version for the vpn device. - FirmwareVersion *string `json:"firmwareVersion,omitempty"` -} - -// VpnGateway vpnGateway Resource. -type VpnGateway struct { - autorest.Response `json:"-"` - // VpnGatewayProperties - Properties of the VPN gateway. - *VpnGatewayProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VpnGateway. -func (vg VpnGateway) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vg.VpnGatewayProperties != nil { - objectMap["properties"] = vg.VpnGatewayProperties - } - if vg.ID != nil { - objectMap["id"] = vg.ID - } - if vg.Location != nil { - objectMap["location"] = vg.Location - } - if vg.Tags != nil { - objectMap["tags"] = vg.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnGateway struct. -func (vg *VpnGateway) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnGatewayProperties VpnGatewayProperties - err = json.Unmarshal(*v, &vpnGatewayProperties) - if err != nil { - return err - } - vg.VpnGatewayProperties = &vpnGatewayProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vg.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vg.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vg.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vg.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vg.Tags = tags - } - } - } - - return nil -} - -// VpnGatewayIPConfiguration IP Configuration of a VPN Gateway Resource. -type VpnGatewayIPConfiguration struct { - // ID - The identifier of the IP configuration for a VPN Gateway. - ID *string `json:"id,omitempty"` - // PublicIPAddress - The public IP address of this IP configuration. - PublicIPAddress *string `json:"publicIpAddress,omitempty"` - // PrivateIPAddress - The private IP address of this IP configuration. - PrivateIPAddress *string `json:"privateIpAddress,omitempty"` -} - -// VpnGatewayNatRule vpnGatewayNatRule Resource. -type VpnGatewayNatRule struct { - autorest.Response `json:"-"` - // VpnGatewayNatRuleProperties - Properties of the VpnGateway NAT rule. - *VpnGatewayNatRuleProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnGatewayNatRule. -func (vgnr VpnGatewayNatRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vgnr.VpnGatewayNatRuleProperties != nil { - objectMap["properties"] = vgnr.VpnGatewayNatRuleProperties - } - if vgnr.Name != nil { - objectMap["name"] = vgnr.Name - } - if vgnr.ID != nil { - objectMap["id"] = vgnr.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnGatewayNatRule struct. -func (vgnr *VpnGatewayNatRule) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnGatewayNatRuleProperties VpnGatewayNatRuleProperties - err = json.Unmarshal(*v, &vpnGatewayNatRuleProperties) - if err != nil { - return err - } - vgnr.VpnGatewayNatRuleProperties = &vpnGatewayNatRuleProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vgnr.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vgnr.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vgnr.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vgnr.ID = &ID - } - } - } - - return nil -} - -// VpnGatewayNatRuleProperties parameters for VpnGatewayNatRule. -type VpnGatewayNatRuleProperties struct { - // ProvisioningState - READ-ONLY; The provisioning state of the NAT Rule resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // Type - The type of NAT rule for VPN NAT. Possible values include: 'VpnNatRuleTypeStatic', 'VpnNatRuleTypeDynamic' - Type VpnNatRuleType `json:"type,omitempty"` - // Mode - The Source NAT direction of a VPN NAT. Possible values include: 'EgressSnat', 'IngressSnat' - Mode VpnNatRuleMode `json:"mode,omitempty"` - // InternalMappings - The private IP address internal mapping for NAT. - InternalMappings *[]VpnNatRuleMapping `json:"internalMappings,omitempty"` - // ExternalMappings - The private IP address external mapping for NAT. - ExternalMappings *[]VpnNatRuleMapping `json:"externalMappings,omitempty"` - // IPConfigurationID - The IP Configuration ID this NAT rule applies to. - IPConfigurationID *string `json:"ipConfigurationId,omitempty"` - // EgressVpnSiteLinkConnections - READ-ONLY; List of egress VpnSiteLinkConnections. - EgressVpnSiteLinkConnections *[]SubResource `json:"egressVpnSiteLinkConnections,omitempty"` - // IngressVpnSiteLinkConnections - READ-ONLY; List of ingress VpnSiteLinkConnections. - IngressVpnSiteLinkConnections *[]SubResource `json:"ingressVpnSiteLinkConnections,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnGatewayNatRuleProperties. -func (vgnrp VpnGatewayNatRuleProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vgnrp.Type != "" { - objectMap["type"] = vgnrp.Type - } - if vgnrp.Mode != "" { - objectMap["mode"] = vgnrp.Mode - } - if vgnrp.InternalMappings != nil { - objectMap["internalMappings"] = vgnrp.InternalMappings - } - if vgnrp.ExternalMappings != nil { - objectMap["externalMappings"] = vgnrp.ExternalMappings - } - if vgnrp.IPConfigurationID != nil { - objectMap["ipConfigurationId"] = vgnrp.IPConfigurationID - } - return json.Marshal(objectMap) -} - -// VpnGatewayPacketCaptureStartParameters start packet capture parameters. -type VpnGatewayPacketCaptureStartParameters struct { - // FilterData - Start Packet capture parameters on vpn gateway. - FilterData *string `json:"filterData,omitempty"` -} - -// VpnGatewayPacketCaptureStopParameters stop packet capture parameters. -type VpnGatewayPacketCaptureStopParameters struct { - // SasURL - SAS url for packet capture on vpn gateway. - SasURL *string `json:"sasUrl,omitempty"` -} - -// VpnGatewayProperties parameters for VpnGateway. -type VpnGatewayProperties struct { - // VirtualHub - The VirtualHub to which the gateway belongs. - VirtualHub *SubResource `json:"virtualHub,omitempty"` - // Connections - List of all vpn connections to the gateway. - Connections *[]VpnConnection `json:"connections,omitempty"` - // BgpSettings - Local network gateway's BGP speaker settings. - BgpSettings *BgpSettings `json:"bgpSettings,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VPN gateway resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // VpnGatewayScaleUnit - The scale unit for this vpn gateway. - VpnGatewayScaleUnit *int32 `json:"vpnGatewayScaleUnit,omitempty"` - // IPConfigurations - READ-ONLY; List of all IPs configured on the gateway. - IPConfigurations *[]VpnGatewayIPConfiguration `json:"ipConfigurations,omitempty"` - // EnableBgpRouteTranslationForNat - Enable BGP routes translation for NAT on this VpnGateway. - EnableBgpRouteTranslationForNat *bool `json:"enableBgpRouteTranslationForNat,omitempty"` - // IsRoutingPreferenceInternet - Enable Routing Preference property for the Public IP Interface of the VpnGateway. - IsRoutingPreferenceInternet *bool `json:"isRoutingPreferenceInternet,omitempty"` - // NatRules - List of all the nat Rules associated with the gateway. - NatRules *[]VpnGatewayNatRule `json:"natRules,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnGatewayProperties. -func (vgp VpnGatewayProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vgp.VirtualHub != nil { - objectMap["virtualHub"] = vgp.VirtualHub - } - if vgp.Connections != nil { - objectMap["connections"] = vgp.Connections - } - if vgp.BgpSettings != nil { - objectMap["bgpSettings"] = vgp.BgpSettings - } - if vgp.VpnGatewayScaleUnit != nil { - objectMap["vpnGatewayScaleUnit"] = vgp.VpnGatewayScaleUnit - } - if vgp.EnableBgpRouteTranslationForNat != nil { - objectMap["enableBgpRouteTranslationForNat"] = vgp.EnableBgpRouteTranslationForNat - } - if vgp.IsRoutingPreferenceInternet != nil { - objectMap["isRoutingPreferenceInternet"] = vgp.IsRoutingPreferenceInternet - } - if vgp.NatRules != nil { - objectMap["natRules"] = vgp.NatRules - } - return json.Marshal(objectMap) -} - -// VpnGatewaysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VpnGatewaysCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnGatewaysClient) (VpnGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnGatewaysCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnGatewaysCreateOrUpdateFuture.Result. -func (future *VpnGatewaysCreateOrUpdateFuture) result(client VpnGatewaysClient) (vg VpnGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnGatewaysCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vg.Response.Response, err = future.GetResult(sender); err == nil && vg.Response.Response.StatusCode != http.StatusNoContent { - vg, err = client.CreateOrUpdateResponder(vg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysCreateOrUpdateFuture", "Result", vg.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnGatewaysDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VpnGatewaysDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnGatewaysClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnGatewaysDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnGatewaysDeleteFuture.Result. -func (future *VpnGatewaysDeleteFuture) result(client VpnGatewaysClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnGatewaysDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VpnGatewaysResetFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VpnGatewaysResetFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnGatewaysClient) (VpnGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnGatewaysResetFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnGatewaysResetFuture.Result. -func (future *VpnGatewaysResetFuture) result(client VpnGatewaysClient) (vg VpnGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysResetFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnGatewaysResetFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vg.Response.Response, err = future.GetResult(sender); err == nil && vg.Response.Response.StatusCode != http.StatusNoContent { - vg, err = client.ResetResponder(vg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysResetFuture", "Result", vg.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnGatewaysStartPacketCaptureFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VpnGatewaysStartPacketCaptureFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnGatewaysClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnGatewaysStartPacketCaptureFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnGatewaysStartPacketCaptureFuture.Result. -func (future *VpnGatewaysStartPacketCaptureFuture) result(client VpnGatewaysClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysStartPacketCaptureFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnGatewaysStartPacketCaptureFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.StartPacketCaptureResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysStartPacketCaptureFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnGatewaysStopPacketCaptureFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VpnGatewaysStopPacketCaptureFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnGatewaysClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnGatewaysStopPacketCaptureFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnGatewaysStopPacketCaptureFuture.Result. -func (future *VpnGatewaysStopPacketCaptureFuture) result(client VpnGatewaysClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysStopPacketCaptureFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnGatewaysStopPacketCaptureFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.StopPacketCaptureResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysStopPacketCaptureFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnGatewaysUpdateTagsFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VpnGatewaysUpdateTagsFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnGatewaysClient) (VpnGateway, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnGatewaysUpdateTagsFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnGatewaysUpdateTagsFuture.Result. -func (future *VpnGatewaysUpdateTagsFuture) result(client VpnGatewaysClient) (vg VpnGateway, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysUpdateTagsFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vg.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnGatewaysUpdateTagsFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vg.Response.Response, err = future.GetResult(sender); err == nil && vg.Response.Response.StatusCode != http.StatusNoContent { - vg, err = client.UpdateTagsResponder(vg.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysUpdateTagsFuture", "Result", vg.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnLinkBgpSettings BGP settings details for a link. -type VpnLinkBgpSettings struct { - // Asn - The BGP speaker's ASN. - Asn *int64 `json:"asn,omitempty"` - // BgpPeeringAddress - The BGP peering address and BGP identifier of this BGP speaker. - BgpPeeringAddress *string `json:"bgpPeeringAddress,omitempty"` -} - -// VpnLinkConnectionsGetIkeSasFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VpnLinkConnectionsGetIkeSasFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnLinkConnectionsClient) (String, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnLinkConnectionsGetIkeSasFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnLinkConnectionsGetIkeSasFuture.Result. -func (future *VpnLinkConnectionsGetIkeSasFuture) result(client VpnLinkConnectionsClient) (s String, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnLinkConnectionsGetIkeSasFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - s.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnLinkConnectionsGetIkeSasFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { - s, err = client.GetIkeSasResponder(s.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnLinkConnectionsGetIkeSasFuture", "Result", s.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnLinkConnectionsResetConnectionFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VpnLinkConnectionsResetConnectionFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnLinkConnectionsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnLinkConnectionsResetConnectionFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnLinkConnectionsResetConnectionFuture.Result. -func (future *VpnLinkConnectionsResetConnectionFuture) result(client VpnLinkConnectionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnLinkConnectionsResetConnectionFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnLinkConnectionsResetConnectionFuture") - return - } - ar.Response = future.Response() - return -} - -// VpnLinkProviderProperties list of properties of a link provider. -type VpnLinkProviderProperties struct { - // LinkProviderName - Name of the link provider. - LinkProviderName *string `json:"linkProviderName,omitempty"` - // LinkSpeedInMbps - Link speed. - LinkSpeedInMbps *int32 `json:"linkSpeedInMbps,omitempty"` -} - -// VpnNatRuleMapping vpn NatRule mapping. -type VpnNatRuleMapping struct { - // AddressSpace - Address space for Vpn NatRule mapping. - AddressSpace *string `json:"addressSpace,omitempty"` - // PortRange - Port range for Vpn NatRule mapping. - PortRange *string `json:"portRange,omitempty"` -} - -// VpnPacketCaptureStartParameters start packet capture parameters on virtual network gateway. -type VpnPacketCaptureStartParameters struct { - // FilterData - Start Packet capture parameters. - FilterData *string `json:"filterData,omitempty"` -} - -// VpnPacketCaptureStopParameters stop packet capture parameters. -type VpnPacketCaptureStopParameters struct { - // SasURL - SAS url for packet capture on virtual network gateway. - SasURL *string `json:"sasUrl,omitempty"` -} - -// VpnProfileResponse vpn Profile Response for package generation. -type VpnProfileResponse struct { - autorest.Response `json:"-"` - // ProfileURL - URL to the VPN profile. - ProfileURL *string `json:"profileUrl,omitempty"` -} - -// VpnServerConfigRadiusClientRootCertificate properties of the Radius client root certificate of -// VpnServerConfiguration. -type VpnServerConfigRadiusClientRootCertificate struct { - // Name - The certificate name. - Name *string `json:"name,omitempty"` - // Thumbprint - The Radius client root certificate thumbprint. - Thumbprint *string `json:"thumbprint,omitempty"` -} - -// VpnServerConfigRadiusServerRootCertificate properties of Radius Server root certificate of -// VpnServerConfiguration. -type VpnServerConfigRadiusServerRootCertificate struct { - // Name - The certificate name. - Name *string `json:"name,omitempty"` - // PublicCertData - The certificate public data. - PublicCertData *string `json:"publicCertData,omitempty"` -} - -// VpnServerConfiguration vpnServerConfiguration Resource. -type VpnServerConfiguration struct { - autorest.Response `json:"-"` - // VpnServerConfigurationProperties - Properties of the P2SVpnServer configuration. - *VpnServerConfigurationProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VpnServerConfiguration. -func (vsc VpnServerConfiguration) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vsc.VpnServerConfigurationProperties != nil { - objectMap["properties"] = vsc.VpnServerConfigurationProperties - } - if vsc.ID != nil { - objectMap["id"] = vsc.ID - } - if vsc.Location != nil { - objectMap["location"] = vsc.Location - } - if vsc.Tags != nil { - objectMap["tags"] = vsc.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnServerConfiguration struct. -func (vsc *VpnServerConfiguration) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnServerConfigurationProperties VpnServerConfigurationProperties - err = json.Unmarshal(*v, &vpnServerConfigurationProperties) - if err != nil { - return err - } - vsc.VpnServerConfigurationProperties = &vpnServerConfigurationProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vsc.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vsc.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vsc.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vsc.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vsc.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vsc.Tags = tags - } - } - } - - return nil -} - -// VpnServerConfigurationPolicyGroup vpnServerConfigurationPolicyGroup Resource. -type VpnServerConfigurationPolicyGroup struct { - autorest.Response `json:"-"` - // VpnServerConfigurationPolicyGroupProperties - Properties of the VpnServerConfigurationPolicyGroup. - *VpnServerConfigurationPolicyGroupProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnServerConfigurationPolicyGroup. -func (vscpg VpnServerConfigurationPolicyGroup) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vscpg.VpnServerConfigurationPolicyGroupProperties != nil { - objectMap["properties"] = vscpg.VpnServerConfigurationPolicyGroupProperties - } - if vscpg.Name != nil { - objectMap["name"] = vscpg.Name - } - if vscpg.ID != nil { - objectMap["id"] = vscpg.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnServerConfigurationPolicyGroup struct. -func (vscpg *VpnServerConfigurationPolicyGroup) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnServerConfigurationPolicyGroupProperties VpnServerConfigurationPolicyGroupProperties - err = json.Unmarshal(*v, &vpnServerConfigurationPolicyGroupProperties) - if err != nil { - return err - } - vscpg.VpnServerConfigurationPolicyGroupProperties = &vpnServerConfigurationPolicyGroupProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vscpg.Etag = &etag - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vscpg.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vscpg.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vscpg.ID = &ID - } - } - } - - return nil -} - -// VpnServerConfigurationPolicyGroupMember vpnServerConfiguration PolicyGroup member -type VpnServerConfigurationPolicyGroupMember struct { - // Name - Name of the VpnServerConfigurationPolicyGroupMember. - Name *string `json:"name,omitempty"` - // AttributeType - The Vpn Policy member attribute type. Possible values include: 'CertificateGroupID', 'AADGroupID', 'RadiusAzureGroupID' - AttributeType VpnPolicyMemberAttributeType `json:"attributeType,omitempty"` - // AttributeValue - The value of Attribute used for this VpnServerConfigurationPolicyGroupMember. - AttributeValue *string `json:"attributeValue,omitempty"` -} - -// VpnServerConfigurationPolicyGroupProperties parameters for VpnServerConfigurationPolicyGroup. -type VpnServerConfigurationPolicyGroupProperties struct { - // IsDefault - Shows if this is a Default VpnServerConfigurationPolicyGroup or not. - IsDefault *bool `json:"isDefault,omitempty"` - // Priority - Priority for VpnServerConfigurationPolicyGroup. - Priority *int32 `json:"priority,omitempty"` - // PolicyMembers - Multiple PolicyMembers for VpnServerConfigurationPolicyGroup. - PolicyMembers *[]VpnServerConfigurationPolicyGroupMember `json:"policyMembers,omitempty"` - // P2SConnectionConfigurations - READ-ONLY; List of references to P2SConnectionConfigurations. - P2SConnectionConfigurations *[]SubResource `json:"p2SConnectionConfigurations,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VpnServerConfigurationPolicyGroup resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnServerConfigurationPolicyGroupProperties. -func (vscpgp VpnServerConfigurationPolicyGroupProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vscpgp.IsDefault != nil { - objectMap["isDefault"] = vscpgp.IsDefault - } - if vscpgp.Priority != nil { - objectMap["priority"] = vscpgp.Priority - } - if vscpgp.PolicyMembers != nil { - objectMap["policyMembers"] = vscpgp.PolicyMembers - } - return json.Marshal(objectMap) -} - -// VpnServerConfigurationProperties parameters for VpnServerConfiguration. -type VpnServerConfigurationProperties struct { - // Name - The name of the VpnServerConfiguration that is unique within a resource group. - Name *string `json:"name,omitempty"` - // VpnProtocols - VPN protocols for the VpnServerConfiguration. - VpnProtocols *[]VpnGatewayTunnelingProtocol `json:"vpnProtocols,omitempty"` - // VpnAuthenticationTypes - VPN authentication types for the VpnServerConfiguration. - VpnAuthenticationTypes *[]VpnAuthenticationType `json:"vpnAuthenticationTypes,omitempty"` - // VpnClientRootCertificates - VPN client root certificate of VpnServerConfiguration. - VpnClientRootCertificates *[]VpnServerConfigVpnClientRootCertificate `json:"vpnClientRootCertificates,omitempty"` - // VpnClientRevokedCertificates - VPN client revoked certificate of VpnServerConfiguration. - VpnClientRevokedCertificates *[]VpnServerConfigVpnClientRevokedCertificate `json:"vpnClientRevokedCertificates,omitempty"` - // RadiusServerRootCertificates - Radius Server root certificate of VpnServerConfiguration. - RadiusServerRootCertificates *[]VpnServerConfigRadiusServerRootCertificate `json:"radiusServerRootCertificates,omitempty"` - // RadiusClientRootCertificates - Radius client root certificate of VpnServerConfiguration. - RadiusClientRootCertificates *[]VpnServerConfigRadiusClientRootCertificate `json:"radiusClientRootCertificates,omitempty"` - // VpnClientIpsecPolicies - VpnClientIpsecPolicies for VpnServerConfiguration. - VpnClientIpsecPolicies *[]IpsecPolicy `json:"vpnClientIpsecPolicies,omitempty"` - // RadiusServerAddress - The radius server address property of the VpnServerConfiguration resource for point to site client connection. - RadiusServerAddress *string `json:"radiusServerAddress,omitempty"` - // RadiusServerSecret - The radius secret property of the VpnServerConfiguration resource for point to site client connection. - RadiusServerSecret *string `json:"radiusServerSecret,omitempty"` - // RadiusServers - Multiple Radius Server configuration for VpnServerConfiguration. - RadiusServers *[]RadiusServer `json:"radiusServers,omitempty"` - // AadAuthenticationParameters - The set of aad vpn authentication parameters. - AadAuthenticationParameters *AadAuthenticationParameters `json:"aadAuthenticationParameters,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VpnServerConfiguration resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. - ProvisioningState *string `json:"provisioningState,omitempty"` - // P2SVpnGateways - READ-ONLY; List of references to P2SVpnGateways. - P2SVpnGateways *[]P2SVpnGateway `json:"p2SVpnGateways,omitempty"` - // ConfigurationPolicyGroups - List of all VpnServerConfigurationPolicyGroups. - ConfigurationPolicyGroups *[]VpnServerConfigurationPolicyGroup `json:"configurationPolicyGroups,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnServerConfigurationProperties. -func (vscp VpnServerConfigurationProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vscp.Name != nil { - objectMap["name"] = vscp.Name - } - if vscp.VpnProtocols != nil { - objectMap["vpnProtocols"] = vscp.VpnProtocols - } - if vscp.VpnAuthenticationTypes != nil { - objectMap["vpnAuthenticationTypes"] = vscp.VpnAuthenticationTypes - } - if vscp.VpnClientRootCertificates != nil { - objectMap["vpnClientRootCertificates"] = vscp.VpnClientRootCertificates - } - if vscp.VpnClientRevokedCertificates != nil { - objectMap["vpnClientRevokedCertificates"] = vscp.VpnClientRevokedCertificates - } - if vscp.RadiusServerRootCertificates != nil { - objectMap["radiusServerRootCertificates"] = vscp.RadiusServerRootCertificates - } - if vscp.RadiusClientRootCertificates != nil { - objectMap["radiusClientRootCertificates"] = vscp.RadiusClientRootCertificates - } - if vscp.VpnClientIpsecPolicies != nil { - objectMap["vpnClientIpsecPolicies"] = vscp.VpnClientIpsecPolicies - } - if vscp.RadiusServerAddress != nil { - objectMap["radiusServerAddress"] = vscp.RadiusServerAddress - } - if vscp.RadiusServerSecret != nil { - objectMap["radiusServerSecret"] = vscp.RadiusServerSecret - } - if vscp.RadiusServers != nil { - objectMap["radiusServers"] = vscp.RadiusServers - } - if vscp.AadAuthenticationParameters != nil { - objectMap["aadAuthenticationParameters"] = vscp.AadAuthenticationParameters - } - if vscp.ConfigurationPolicyGroups != nil { - objectMap["configurationPolicyGroups"] = vscp.ConfigurationPolicyGroups - } - return json.Marshal(objectMap) -} - -// VpnServerConfigurationsAssociatedWithVirtualWanListFuture an abstraction for monitoring and retrieving -// the results of a long-running operation. -type VpnServerConfigurationsAssociatedWithVirtualWanListFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnServerConfigurationsAssociatedWithVirtualWanClient) (VpnServerConfigurationsResponse, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnServerConfigurationsAssociatedWithVirtualWanListFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnServerConfigurationsAssociatedWithVirtualWanListFuture.Result. -func (future *VpnServerConfigurationsAssociatedWithVirtualWanListFuture) result(client VpnServerConfigurationsAssociatedWithVirtualWanClient) (vscr VpnServerConfigurationsResponse, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsAssociatedWithVirtualWanListFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vscr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnServerConfigurationsAssociatedWithVirtualWanListFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vscr.Response.Response, err = future.GetResult(sender); err == nil && vscr.Response.Response.StatusCode != http.StatusNoContent { - vscr, err = client.ListResponder(vscr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsAssociatedWithVirtualWanListFuture", "Result", vscr.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnServerConfigurationsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of -// a long-running operation. -type VpnServerConfigurationsCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnServerConfigurationsClient) (VpnServerConfiguration, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnServerConfigurationsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnServerConfigurationsCreateOrUpdateFuture.Result. -func (future *VpnServerConfigurationsCreateOrUpdateFuture) result(client VpnServerConfigurationsClient) (vsc VpnServerConfiguration, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vsc.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnServerConfigurationsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vsc.Response.Response, err = future.GetResult(sender); err == nil && vsc.Response.Response.StatusCode != http.StatusNoContent { - vsc, err = client.CreateOrUpdateResponder(vsc.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsCreateOrUpdateFuture", "Result", vsc.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnServerConfigurationsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VpnServerConfigurationsDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnServerConfigurationsClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnServerConfigurationsDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnServerConfigurationsDeleteFuture.Result. -func (future *VpnServerConfigurationsDeleteFuture) result(client VpnServerConfigurationsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnServerConfigurationsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// VpnServerConfigurationsResponse vpnServerConfigurations list associated with VirtualWan Response. -type VpnServerConfigurationsResponse struct { - autorest.Response `json:"-"` - // VpnServerConfigurationResourceIds - List of VpnServerConfigurations associated with VirtualWan. - VpnServerConfigurationResourceIds *[]string `json:"vpnServerConfigurationResourceIds,omitempty"` -} - -// VpnServerConfigVpnClientRevokedCertificate properties of the revoked VPN client certificate of -// VpnServerConfiguration. -type VpnServerConfigVpnClientRevokedCertificate struct { - // Name - The certificate name. - Name *string `json:"name,omitempty"` - // Thumbprint - The revoked VPN client certificate thumbprint. - Thumbprint *string `json:"thumbprint,omitempty"` -} - -// VpnServerConfigVpnClientRootCertificate properties of VPN client root certificate of -// VpnServerConfiguration. -type VpnServerConfigVpnClientRootCertificate struct { - // Name - The certificate name. - Name *string `json:"name,omitempty"` - // PublicCertData - The certificate public data. - PublicCertData *string `json:"publicCertData,omitempty"` -} - -// VpnSite vpnSite Resource. -type VpnSite struct { - autorest.Response `json:"-"` - // VpnSiteProperties - Properties of the VPN site. - *VpnSiteProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for VpnSite. -func (vs VpnSite) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vs.VpnSiteProperties != nil { - objectMap["properties"] = vs.VpnSiteProperties - } - if vs.ID != nil { - objectMap["id"] = vs.ID - } - if vs.Location != nil { - objectMap["location"] = vs.Location - } - if vs.Tags != nil { - objectMap["tags"] = vs.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnSite struct. -func (vs *VpnSite) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnSiteProperties VpnSiteProperties - err = json.Unmarshal(*v, &vpnSiteProperties) - if err != nil { - return err - } - vs.VpnSiteProperties = &vpnSiteProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vs.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vs.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vs.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vs.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - vs.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - vs.Tags = tags - } - } - } - - return nil -} - -// VpnSiteID vpnSite Resource. -type VpnSiteID struct { - // VpnSite - READ-ONLY; The resource-uri of the vpn-site for which config is to be fetched. - VpnSite *string `json:"vpnSite,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnSiteID. -func (vsi VpnSiteID) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// VpnSiteLink vpnSiteLink Resource. -type VpnSiteLink struct { - autorest.Response `json:"-"` - // VpnSiteLinkProperties - Properties of the VPN site link. - *VpnSiteLinkProperties `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnSiteLink. -func (vsl VpnSiteLink) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vsl.VpnSiteLinkProperties != nil { - objectMap["properties"] = vsl.VpnSiteLinkProperties - } - if vsl.Name != nil { - objectMap["name"] = vsl.Name - } - if vsl.ID != nil { - objectMap["id"] = vsl.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnSiteLink struct. -func (vsl *VpnSiteLink) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnSiteLinkProperties VpnSiteLinkProperties - err = json.Unmarshal(*v, &vpnSiteLinkProperties) - if err != nil { - return err - } - vsl.VpnSiteLinkProperties = &vpnSiteLinkProperties - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vsl.Etag = &etag - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vsl.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vsl.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vsl.ID = &ID - } - } - } - - return nil -} - -// VpnSiteLinkConnection vpnSiteLinkConnection Resource. -type VpnSiteLinkConnection struct { - autorest.Response `json:"-"` - // VpnSiteLinkConnectionProperties - Properties of the VPN site link connection. - *VpnSiteLinkConnectionProperties `json:"properties,omitempty"` - // Name - The name of the resource that is unique within a resource group. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnSiteLinkConnection. -func (vslc VpnSiteLinkConnection) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vslc.VpnSiteLinkConnectionProperties != nil { - objectMap["properties"] = vslc.VpnSiteLinkConnectionProperties - } - if vslc.Name != nil { - objectMap["name"] = vslc.Name - } - if vslc.ID != nil { - objectMap["id"] = vslc.ID - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for VpnSiteLinkConnection struct. -func (vslc *VpnSiteLinkConnection) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var vpnSiteLinkConnectionProperties VpnSiteLinkConnectionProperties - err = json.Unmarshal(*v, &vpnSiteLinkConnectionProperties) - if err != nil { - return err - } - vslc.VpnSiteLinkConnectionProperties = &vpnSiteLinkConnectionProperties - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - vslc.Name = &name - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - vslc.Etag = &etag - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - vslc.Type = &typeVar - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - vslc.ID = &ID - } - } - } - - return nil -} - -// VpnSiteLinkConnectionProperties parameters for VpnConnection. -type VpnSiteLinkConnectionProperties struct { - // VpnSiteLink - Id of the connected vpn site link. - VpnSiteLink *SubResource `json:"vpnSiteLink,omitempty"` - // RoutingWeight - Routing weight for vpn connection. - RoutingWeight *int32 `json:"routingWeight,omitempty"` - // VpnLinkConnectionMode - Vpn link connection mode. Possible values include: 'VpnLinkConnectionModeDefault', 'VpnLinkConnectionModeResponderOnly', 'VpnLinkConnectionModeInitiatorOnly' - VpnLinkConnectionMode VpnLinkConnectionMode `json:"vpnLinkConnectionMode,omitempty"` - // ConnectionStatus - The connection status. Possible values include: 'VpnConnectionStatusUnknown', 'VpnConnectionStatusConnecting', 'VpnConnectionStatusConnected', 'VpnConnectionStatusNotConnected' - ConnectionStatus VpnConnectionStatus `json:"connectionStatus,omitempty"` - // VpnConnectionProtocolType - Connection protocol used for this connection. Possible values include: 'IKEv2', 'IKEv1' - VpnConnectionProtocolType VirtualNetworkGatewayConnectionProtocol `json:"vpnConnectionProtocolType,omitempty"` - // IngressBytesTransferred - READ-ONLY; Ingress bytes transferred. - IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` - // EgressBytesTransferred - READ-ONLY; Egress bytes transferred. - EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` - // ConnectionBandwidth - Expected bandwidth in MBPS. - ConnectionBandwidth *int32 `json:"connectionBandwidth,omitempty"` - // SharedKey - SharedKey for the vpn connection. - SharedKey *string `json:"sharedKey,omitempty"` - // EnableBgp - EnableBgp flag. - EnableBgp *bool `json:"enableBgp,omitempty"` - // VpnGatewayCustomBgpAddresses - vpnGatewayCustomBgpAddresses used by this connection. - VpnGatewayCustomBgpAddresses *[]GatewayCustomBgpIPAddressIPConfiguration `json:"vpnGatewayCustomBgpAddresses,omitempty"` - // UsePolicyBasedTrafficSelectors - Enable policy-based traffic selectors. - UsePolicyBasedTrafficSelectors *bool `json:"usePolicyBasedTrafficSelectors,omitempty"` - // IpsecPolicies - The IPSec Policies to be considered by this connection. - IpsecPolicies *[]IpsecPolicy `json:"ipsecPolicies,omitempty"` - // EnableRateLimiting - EnableBgp flag. - EnableRateLimiting *bool `json:"enableRateLimiting,omitempty"` - // UseLocalAzureIPAddress - Use local azure ip to initiate connection. - UseLocalAzureIPAddress *bool `json:"useLocalAzureIpAddress,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VPN site link connection resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // IngressNatRules - List of ingress NatRules. - IngressNatRules *[]SubResource `json:"ingressNatRules,omitempty"` - // EgressNatRules - List of egress NatRules. - EgressNatRules *[]SubResource `json:"egressNatRules,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnSiteLinkConnectionProperties. -func (vslcp VpnSiteLinkConnectionProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vslcp.VpnSiteLink != nil { - objectMap["vpnSiteLink"] = vslcp.VpnSiteLink - } - if vslcp.RoutingWeight != nil { - objectMap["routingWeight"] = vslcp.RoutingWeight - } - if vslcp.VpnLinkConnectionMode != "" { - objectMap["vpnLinkConnectionMode"] = vslcp.VpnLinkConnectionMode - } - if vslcp.ConnectionStatus != "" { - objectMap["connectionStatus"] = vslcp.ConnectionStatus - } - if vslcp.VpnConnectionProtocolType != "" { - objectMap["vpnConnectionProtocolType"] = vslcp.VpnConnectionProtocolType - } - if vslcp.ConnectionBandwidth != nil { - objectMap["connectionBandwidth"] = vslcp.ConnectionBandwidth - } - if vslcp.SharedKey != nil { - objectMap["sharedKey"] = vslcp.SharedKey - } - if vslcp.EnableBgp != nil { - objectMap["enableBgp"] = vslcp.EnableBgp - } - if vslcp.VpnGatewayCustomBgpAddresses != nil { - objectMap["vpnGatewayCustomBgpAddresses"] = vslcp.VpnGatewayCustomBgpAddresses - } - if vslcp.UsePolicyBasedTrafficSelectors != nil { - objectMap["usePolicyBasedTrafficSelectors"] = vslcp.UsePolicyBasedTrafficSelectors - } - if vslcp.IpsecPolicies != nil { - objectMap["ipsecPolicies"] = vslcp.IpsecPolicies - } - if vslcp.EnableRateLimiting != nil { - objectMap["enableRateLimiting"] = vslcp.EnableRateLimiting - } - if vslcp.UseLocalAzureIPAddress != nil { - objectMap["useLocalAzureIpAddress"] = vslcp.UseLocalAzureIPAddress - } - if vslcp.IngressNatRules != nil { - objectMap["ingressNatRules"] = vslcp.IngressNatRules - } - if vslcp.EgressNatRules != nil { - objectMap["egressNatRules"] = vslcp.EgressNatRules - } - return json.Marshal(objectMap) -} - -// VpnSiteLinkProperties parameters for VpnSite. -type VpnSiteLinkProperties struct { - // LinkProperties - The link provider properties. - LinkProperties *VpnLinkProviderProperties `json:"linkProperties,omitempty"` - // IPAddress - The ip-address for the vpn-site-link. - IPAddress *string `json:"ipAddress,omitempty"` - // Fqdn - FQDN of vpn-site-link. - Fqdn *string `json:"fqdn,omitempty"` - // BgpProperties - The set of bgp properties. - BgpProperties *VpnLinkBgpSettings `json:"bgpProperties,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VPN site link resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnSiteLinkProperties. -func (vslp VpnSiteLinkProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vslp.LinkProperties != nil { - objectMap["linkProperties"] = vslp.LinkProperties - } - if vslp.IPAddress != nil { - objectMap["ipAddress"] = vslp.IPAddress - } - if vslp.Fqdn != nil { - objectMap["fqdn"] = vslp.Fqdn - } - if vslp.BgpProperties != nil { - objectMap["bgpProperties"] = vslp.BgpProperties - } - return json.Marshal(objectMap) -} - -// VpnSiteProperties parameters for VpnSite. -type VpnSiteProperties struct { - // VirtualWan - The VirtualWAN to which the vpnSite belongs. - VirtualWan *SubResource `json:"virtualWan,omitempty"` - // DeviceProperties - The device properties. - DeviceProperties *DeviceProperties `json:"deviceProperties,omitempty"` - // IPAddress - The ip-address for the vpn-site. - IPAddress *string `json:"ipAddress,omitempty"` - // SiteKey - The key for vpn-site that can be used for connections. - SiteKey *string `json:"siteKey,omitempty"` - // AddressSpace - The AddressSpace that contains an array of IP address ranges. - AddressSpace *AddressSpace `json:"addressSpace,omitempty"` - // BgpProperties - The set of bgp properties. - BgpProperties *BgpSettings `json:"bgpProperties,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the VPN site resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // IsSecuritySite - IsSecuritySite flag. - IsSecuritySite *bool `json:"isSecuritySite,omitempty"` - // VpnSiteLinks - List of all vpn site links. - VpnSiteLinks *[]VpnSiteLink `json:"vpnSiteLinks,omitempty"` - // O365Policy - Office365 Policy. - O365Policy *O365PolicyProperties `json:"o365Policy,omitempty"` -} - -// MarshalJSON is the custom marshaler for VpnSiteProperties. -func (vsp VpnSiteProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if vsp.VirtualWan != nil { - objectMap["virtualWan"] = vsp.VirtualWan - } - if vsp.DeviceProperties != nil { - objectMap["deviceProperties"] = vsp.DeviceProperties - } - if vsp.IPAddress != nil { - objectMap["ipAddress"] = vsp.IPAddress - } - if vsp.SiteKey != nil { - objectMap["siteKey"] = vsp.SiteKey - } - if vsp.AddressSpace != nil { - objectMap["addressSpace"] = vsp.AddressSpace - } - if vsp.BgpProperties != nil { - objectMap["bgpProperties"] = vsp.BgpProperties - } - if vsp.IsSecuritySite != nil { - objectMap["isSecuritySite"] = vsp.IsSecuritySite - } - if vsp.VpnSiteLinks != nil { - objectMap["vpnSiteLinks"] = vsp.VpnSiteLinks - } - if vsp.O365Policy != nil { - objectMap["o365Policy"] = vsp.O365Policy - } - return json.Marshal(objectMap) -} - -// VpnSitesConfigurationDownloadFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type VpnSitesConfigurationDownloadFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnSitesConfigurationClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnSitesConfigurationDownloadFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnSitesConfigurationDownloadFuture.Result. -func (future *VpnSitesConfigurationDownloadFuture) result(client VpnSitesConfigurationClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesConfigurationDownloadFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnSitesConfigurationDownloadFuture") - return - } - ar.Response = future.Response() - return -} - -// VpnSitesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VpnSitesCreateOrUpdateFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnSitesClient) (VpnSite, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnSitesCreateOrUpdateFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnSitesCreateOrUpdateFuture.Result. -func (future *VpnSitesCreateOrUpdateFuture) result(client VpnSitesClient) (vs VpnSite, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vs.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnSitesCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vs.Response.Response, err = future.GetResult(sender); err == nil && vs.Response.Response.StatusCode != http.StatusNoContent { - vs, err = client.CreateOrUpdateResponder(vs.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesCreateOrUpdateFuture", "Result", vs.Response.Response, "Failure responding to request") - } - } - return -} - -// VpnSitesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type VpnSitesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(VpnSitesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *VpnSitesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for VpnSitesDeleteFuture.Result. -func (future *VpnSitesDeleteFuture) result(client VpnSitesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.VpnSitesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// Watcher network watcher in a resource group. -type Watcher struct { - autorest.Response `json:"-"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // WatcherPropertiesFormat - Properties of the network watcher. - *WatcherPropertiesFormat `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Watcher. -func (w Watcher) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if w.WatcherPropertiesFormat != nil { - objectMap["properties"] = w.WatcherPropertiesFormat - } - if w.ID != nil { - objectMap["id"] = w.ID - } - if w.Location != nil { - objectMap["location"] = w.Location - } - if w.Tags != nil { - objectMap["tags"] = w.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Watcher struct. -func (w *Watcher) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - w.Etag = &etag - } - case "properties": - if v != nil { - var watcherPropertiesFormat WatcherPropertiesFormat - err = json.Unmarshal(*v, &watcherPropertiesFormat) - if err != nil { - return err - } - w.WatcherPropertiesFormat = &watcherPropertiesFormat - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - w.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - w.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - w.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - w.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - w.Tags = tags - } - } - } - - return nil -} - -// WatcherListResult response for ListNetworkWatchers API service call. -type WatcherListResult struct { - autorest.Response `json:"-"` - // Value - List of network watcher resources. - Value *[]Watcher `json:"value,omitempty"` -} - -// WatcherPropertiesFormat the network watcher properties. -type WatcherPropertiesFormat struct { - // ProvisioningState - READ-ONLY; The provisioning state of the network watcher resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` -} - -// MarshalJSON is the custom marshaler for WatcherPropertiesFormat. -func (wpf WatcherPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// WatchersCheckConnectivityFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersCheckConnectivityFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (ConnectivityInformation, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersCheckConnectivityFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersCheckConnectivityFuture.Result. -func (future *WatchersCheckConnectivityFuture) result(client WatchersClient) (ci ConnectivityInformation, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersCheckConnectivityFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ci.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersCheckConnectivityFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if ci.Response.Response, err = future.GetResult(sender); err == nil && ci.Response.Response.StatusCode != http.StatusNoContent { - ci, err = client.CheckConnectivityResponder(ci.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersCheckConnectivityFuture", "Result", ci.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type WatchersDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersDeleteFuture.Result. -func (future *WatchersDeleteFuture) result(client WatchersClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// WatchersGetAzureReachabilityReportFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersGetAzureReachabilityReportFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (AzureReachabilityReport, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetAzureReachabilityReportFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetAzureReachabilityReportFuture.Result. -func (future *WatchersGetAzureReachabilityReportFuture) result(client WatchersClient) (arr AzureReachabilityReport, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetAzureReachabilityReportFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - arr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetAzureReachabilityReportFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if arr.Response.Response, err = future.GetResult(sender); err == nil && arr.Response.Response.StatusCode != http.StatusNoContent { - arr, err = client.GetAzureReachabilityReportResponder(arr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetAzureReachabilityReportFuture", "Result", arr.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersGetFlowLogStatusFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersGetFlowLogStatusFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (FlowLogInformation, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetFlowLogStatusFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetFlowLogStatusFuture.Result. -func (future *WatchersGetFlowLogStatusFuture) result(client WatchersClient) (fli FlowLogInformation, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetFlowLogStatusFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - fli.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetFlowLogStatusFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if fli.Response.Response, err = future.GetResult(sender); err == nil && fli.Response.Response.StatusCode != http.StatusNoContent { - fli, err = client.GetFlowLogStatusResponder(fli.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetFlowLogStatusFuture", "Result", fli.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersGetNetworkConfigurationDiagnosticFuture an abstraction for monitoring and retrieving the results -// of a long-running operation. -type WatchersGetNetworkConfigurationDiagnosticFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (ConfigurationDiagnosticResponse, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetNetworkConfigurationDiagnosticFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetNetworkConfigurationDiagnosticFuture.Result. -func (future *WatchersGetNetworkConfigurationDiagnosticFuture) result(client WatchersClient) (cdr ConfigurationDiagnosticResponse, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetNetworkConfigurationDiagnosticFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - cdr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetNetworkConfigurationDiagnosticFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if cdr.Response.Response, err = future.GetResult(sender); err == nil && cdr.Response.Response.StatusCode != http.StatusNoContent { - cdr, err = client.GetNetworkConfigurationDiagnosticResponder(cdr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetNetworkConfigurationDiagnosticFuture", "Result", cdr.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersGetNextHopFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type WatchersGetNextHopFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (NextHopResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetNextHopFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetNextHopFuture.Result. -func (future *WatchersGetNextHopFuture) result(client WatchersClient) (nhr NextHopResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetNextHopFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - nhr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetNextHopFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if nhr.Response.Response, err = future.GetResult(sender); err == nil && nhr.Response.Response.StatusCode != http.StatusNoContent { - nhr, err = client.GetNextHopResponder(nhr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetNextHopFuture", "Result", nhr.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersGetTroubleshootingFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersGetTroubleshootingFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (TroubleshootingResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetTroubleshootingFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetTroubleshootingFuture.Result. -func (future *WatchersGetTroubleshootingFuture) result(client WatchersClient) (tr TroubleshootingResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetTroubleshootingFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - tr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetTroubleshootingFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if tr.Response.Response, err = future.GetResult(sender); err == nil && tr.Response.Response.StatusCode != http.StatusNoContent { - tr, err = client.GetTroubleshootingResponder(tr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetTroubleshootingFuture", "Result", tr.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersGetTroubleshootingResultFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersGetTroubleshootingResultFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (TroubleshootingResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetTroubleshootingResultFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetTroubleshootingResultFuture.Result. -func (future *WatchersGetTroubleshootingResultFuture) result(client WatchersClient) (tr TroubleshootingResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetTroubleshootingResultFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - tr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetTroubleshootingResultFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if tr.Response.Response, err = future.GetResult(sender); err == nil && tr.Response.Response.StatusCode != http.StatusNoContent { - tr, err = client.GetTroubleshootingResultResponder(tr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetTroubleshootingResultFuture", "Result", tr.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersGetVMSecurityRulesFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersGetVMSecurityRulesFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (SecurityGroupViewResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersGetVMSecurityRulesFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersGetVMSecurityRulesFuture.Result. -func (future *WatchersGetVMSecurityRulesFuture) result(client WatchersClient) (sgvr SecurityGroupViewResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetVMSecurityRulesFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - sgvr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersGetVMSecurityRulesFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if sgvr.Response.Response, err = future.GetResult(sender); err == nil && sgvr.Response.Response.StatusCode != http.StatusNoContent { - sgvr, err = client.GetVMSecurityRulesResponder(sgvr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersGetVMSecurityRulesFuture", "Result", sgvr.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersListAvailableProvidersFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersListAvailableProvidersFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (AvailableProvidersList, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersListAvailableProvidersFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersListAvailableProvidersFuture.Result. -func (future *WatchersListAvailableProvidersFuture) result(client WatchersClient) (apl AvailableProvidersList, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersListAvailableProvidersFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - apl.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersListAvailableProvidersFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if apl.Response.Response, err = future.GetResult(sender); err == nil && apl.Response.Response.StatusCode != http.StatusNoContent { - apl, err = client.ListAvailableProvidersResponder(apl.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersListAvailableProvidersFuture", "Result", apl.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersSetFlowLogConfigurationFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WatchersSetFlowLogConfigurationFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (FlowLogInformation, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersSetFlowLogConfigurationFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersSetFlowLogConfigurationFuture.Result. -func (future *WatchersSetFlowLogConfigurationFuture) result(client WatchersClient) (fli FlowLogInformation, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersSetFlowLogConfigurationFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - fli.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersSetFlowLogConfigurationFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if fli.Response.Response, err = future.GetResult(sender); err == nil && fli.Response.Response.StatusCode != http.StatusNoContent { - fli, err = client.SetFlowLogConfigurationResponder(fli.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersSetFlowLogConfigurationFuture", "Result", fli.Response.Response, "Failure responding to request") - } - } - return -} - -// WatchersVerifyIPFlowFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type WatchersVerifyIPFlowFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WatchersClient) (VerificationIPFlowResult, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WatchersVerifyIPFlowFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WatchersVerifyIPFlowFuture.Result. -func (future *WatchersVerifyIPFlowFuture) result(client WatchersClient) (vifr VerificationIPFlowResult, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersVerifyIPFlowFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - vifr.Response.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WatchersVerifyIPFlowFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if vifr.Response.Response, err = future.GetResult(sender); err == nil && vifr.Response.Response.StatusCode != http.StatusNoContent { - vifr, err = client.VerifyIPFlowResponder(vifr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersVerifyIPFlowFuture", "Result", vifr.Response.Response, "Failure responding to request") - } - } - return -} - -// WebApplicationFirewallCustomRule defines contents of a web application rule. -type WebApplicationFirewallCustomRule struct { - // Name - The name of the resource that is unique within a policy. This name can be used to access the resource. - Name *string `json:"name,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // Priority - Priority of the rule. Rules with a lower value will be evaluated before rules with a higher value. - Priority *int32 `json:"priority,omitempty"` - // RuleType - The rule type. Possible values include: 'WebApplicationFirewallRuleTypeMatchRule', 'WebApplicationFirewallRuleTypeInvalid' - RuleType WebApplicationFirewallRuleType `json:"ruleType,omitempty"` - // MatchConditions - List of match conditions. - MatchConditions *[]MatchCondition `json:"matchConditions,omitempty"` - // Action - Type of Actions. Possible values include: 'WebApplicationFirewallActionAllow', 'WebApplicationFirewallActionBlock', 'WebApplicationFirewallActionLog' - Action WebApplicationFirewallAction `json:"action,omitempty"` -} - -// MarshalJSON is the custom marshaler for WebApplicationFirewallCustomRule. -func (wafcr WebApplicationFirewallCustomRule) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if wafcr.Name != nil { - objectMap["name"] = wafcr.Name - } - if wafcr.Priority != nil { - objectMap["priority"] = wafcr.Priority - } - if wafcr.RuleType != "" { - objectMap["ruleType"] = wafcr.RuleType - } - if wafcr.MatchConditions != nil { - objectMap["matchConditions"] = wafcr.MatchConditions - } - if wafcr.Action != "" { - objectMap["action"] = wafcr.Action - } - return json.Marshal(objectMap) -} - -// WebApplicationFirewallPoliciesDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type WebApplicationFirewallPoliciesDeleteFuture struct { - azure.FutureAPI - // Result returns the result of the asynchronous operation. - // If the operation has not completed it will return an error. - Result func(WebApplicationFirewallPoliciesClient) (autorest.Response, error) -} - -// UnmarshalJSON is the custom unmarshaller for CreateFuture. -func (future *WebApplicationFirewallPoliciesDeleteFuture) UnmarshalJSON(body []byte) error { - var azFuture azure.Future - if err := json.Unmarshal(body, &azFuture); err != nil { - return err - } - future.FutureAPI = &azFuture - future.Result = future.result - return nil -} - -// result is the default implementation for WebApplicationFirewallPoliciesDeleteFuture.Result. -func (future *WebApplicationFirewallPoliciesDeleteFuture) result(client WebApplicationFirewallPoliciesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - ar.Response = future.Response() - err = azure.NewAsyncOpIncompleteError("network.WebApplicationFirewallPoliciesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// WebApplicationFirewallPolicy defines web application firewall policy. -type WebApplicationFirewallPolicy struct { - autorest.Response `json:"-"` - // WebApplicationFirewallPolicyPropertiesFormat - Properties of the web application firewall policy. - *WebApplicationFirewallPolicyPropertiesFormat `json:"properties,omitempty"` - // Etag - READ-ONLY; A unique read-only string that changes whenever the resource is updated. - Etag *string `json:"etag,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Resource name. - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for WebApplicationFirewallPolicy. -func (wafp WebApplicationFirewallPolicy) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if wafp.WebApplicationFirewallPolicyPropertiesFormat != nil { - objectMap["properties"] = wafp.WebApplicationFirewallPolicyPropertiesFormat - } - if wafp.ID != nil { - objectMap["id"] = wafp.ID - } - if wafp.Location != nil { - objectMap["location"] = wafp.Location - } - if wafp.Tags != nil { - objectMap["tags"] = wafp.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for WebApplicationFirewallPolicy struct. -func (wafp *WebApplicationFirewallPolicy) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "properties": - if v != nil { - var webApplicationFirewallPolicyPropertiesFormat WebApplicationFirewallPolicyPropertiesFormat - err = json.Unmarshal(*v, &webApplicationFirewallPolicyPropertiesFormat) - if err != nil { - return err - } - wafp.WebApplicationFirewallPolicyPropertiesFormat = &webApplicationFirewallPolicyPropertiesFormat - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - wafp.Etag = &etag - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - wafp.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - wafp.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - wafp.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - wafp.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - wafp.Tags = tags - } - } - } - - return nil -} - -// WebApplicationFirewallPolicyListResult result of the request to list WebApplicationFirewallPolicies. It -// contains a list of WebApplicationFirewallPolicy objects and a URL link to get the next set of results. -type WebApplicationFirewallPolicyListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; List of WebApplicationFirewallPolicies within a resource group. - Value *[]WebApplicationFirewallPolicy `json:"value,omitempty"` - // NextLink - READ-ONLY; URL to get the next set of WebApplicationFirewallPolicy objects if there are any. - NextLink *string `json:"nextLink,omitempty"` -} - -// MarshalJSON is the custom marshaler for WebApplicationFirewallPolicyListResult. -func (wafplr WebApplicationFirewallPolicyListResult) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// WebApplicationFirewallPolicyListResultIterator provides access to a complete listing of -// WebApplicationFirewallPolicy values. -type WebApplicationFirewallPolicyListResultIterator struct { - i int - page WebApplicationFirewallPolicyListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *WebApplicationFirewallPolicyListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPolicyListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *WebApplicationFirewallPolicyListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter WebApplicationFirewallPolicyListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter WebApplicationFirewallPolicyListResultIterator) Response() WebApplicationFirewallPolicyListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter WebApplicationFirewallPolicyListResultIterator) Value() WebApplicationFirewallPolicy { - if !iter.page.NotDone() { - return WebApplicationFirewallPolicy{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the WebApplicationFirewallPolicyListResultIterator type. -func NewWebApplicationFirewallPolicyListResultIterator(page WebApplicationFirewallPolicyListResultPage) WebApplicationFirewallPolicyListResultIterator { - return WebApplicationFirewallPolicyListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (wafplr WebApplicationFirewallPolicyListResult) IsEmpty() bool { - return wafplr.Value == nil || len(*wafplr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (wafplr WebApplicationFirewallPolicyListResult) hasNextLink() bool { - return wafplr.NextLink != nil && len(*wafplr.NextLink) != 0 -} - -// webApplicationFirewallPolicyListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (wafplr WebApplicationFirewallPolicyListResult) webApplicationFirewallPolicyListResultPreparer(ctx context.Context) (*http.Request, error) { - if !wafplr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(wafplr.NextLink))) -} - -// WebApplicationFirewallPolicyListResultPage contains a page of WebApplicationFirewallPolicy values. -type WebApplicationFirewallPolicyListResultPage struct { - fn func(context.Context, WebApplicationFirewallPolicyListResult) (WebApplicationFirewallPolicyListResult, error) - wafplr WebApplicationFirewallPolicyListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *WebApplicationFirewallPolicyListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPolicyListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.wafplr) - if err != nil { - return err - } - page.wafplr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *WebApplicationFirewallPolicyListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page WebApplicationFirewallPolicyListResultPage) NotDone() bool { - return !page.wafplr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page WebApplicationFirewallPolicyListResultPage) Response() WebApplicationFirewallPolicyListResult { - return page.wafplr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page WebApplicationFirewallPolicyListResultPage) Values() []WebApplicationFirewallPolicy { - if page.wafplr.IsEmpty() { - return nil - } - return *page.wafplr.Value -} - -// Creates a new instance of the WebApplicationFirewallPolicyListResultPage type. -func NewWebApplicationFirewallPolicyListResultPage(cur WebApplicationFirewallPolicyListResult, getNextPage func(context.Context, WebApplicationFirewallPolicyListResult) (WebApplicationFirewallPolicyListResult, error)) WebApplicationFirewallPolicyListResultPage { - return WebApplicationFirewallPolicyListResultPage{ - fn: getNextPage, - wafplr: cur, - } -} - -// WebApplicationFirewallPolicyPropertiesFormat defines web application firewall policy properties. -type WebApplicationFirewallPolicyPropertiesFormat struct { - // PolicySettings - The PolicySettings for policy. - PolicySettings *PolicySettings `json:"policySettings,omitempty"` - // CustomRules - The custom rules inside the policy. - CustomRules *[]WebApplicationFirewallCustomRule `json:"customRules,omitempty"` - // ApplicationGateways - READ-ONLY; A collection of references to application gateways. - ApplicationGateways *[]ApplicationGateway `json:"applicationGateways,omitempty"` - // ProvisioningState - READ-ONLY; The provisioning state of the web application firewall policy resource. Possible values include: 'ProvisioningStateSucceeded', 'ProvisioningStateUpdating', 'ProvisioningStateDeleting', 'ProvisioningStateFailed' - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - // ResourceState - READ-ONLY; Resource status of the policy. Possible values include: 'WebApplicationFirewallPolicyResourceStateCreating', 'WebApplicationFirewallPolicyResourceStateEnabling', 'WebApplicationFirewallPolicyResourceStateEnabled', 'WebApplicationFirewallPolicyResourceStateDisabling', 'WebApplicationFirewallPolicyResourceStateDisabled', 'WebApplicationFirewallPolicyResourceStateDeleting' - ResourceState WebApplicationFirewallPolicyResourceState `json:"resourceState,omitempty"` - // ManagedRules - Describes the managedRules structure. - ManagedRules *ManagedRulesDefinition `json:"managedRules,omitempty"` - // HTTPListeners - READ-ONLY; A collection of references to application gateway http listeners. - HTTPListeners *[]SubResource `json:"httpListeners,omitempty"` - // PathBasedRules - READ-ONLY; A collection of references to application gateway path rules. - PathBasedRules *[]SubResource `json:"pathBasedRules,omitempty"` -} - -// MarshalJSON is the custom marshaler for WebApplicationFirewallPolicyPropertiesFormat. -func (wafppf WebApplicationFirewallPolicyPropertiesFormat) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if wafppf.PolicySettings != nil { - objectMap["policySettings"] = wafppf.PolicySettings - } - if wafppf.CustomRules != nil { - objectMap["customRules"] = wafppf.CustomRules - } - if wafppf.ManagedRules != nil { - objectMap["managedRules"] = wafppf.ManagedRules - } - return json.Marshal(objectMap) -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/natgateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/natgateways.go deleted file mode 100644 index b64e8d6210..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/natgateways.go +++ /dev/null @@ -1,580 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// NatGatewaysClient is the network Client -type NatGatewaysClient struct { - BaseClient -} - -// NewNatGatewaysClient creates an instance of the NatGatewaysClient client. -func NewNatGatewaysClient(subscriptionID string) NatGatewaysClient { - return NewNatGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewNatGatewaysClientWithBaseURI creates an instance of the NatGatewaysClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewNatGatewaysClientWithBaseURI(baseURI string, subscriptionID string) NatGatewaysClient { - return NatGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a nat gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// natGatewayName - the name of the nat gateway. -// parameters - parameters supplied to the create or update nat gateway operation. -func (client NatGatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, natGatewayName string, parameters NatGateway) (result NatGatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatGatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, natGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client NatGatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, natGatewayName string, parameters NatGateway) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "natGatewayName": autorest.Encode("path", natGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/natGateways/{natGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client NatGatewaysClient) CreateOrUpdateSender(req *http.Request) (future NatGatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client NatGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result NatGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified nat gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// natGatewayName - the name of the nat gateway. -func (client NatGatewaysClient) Delete(ctx context.Context, resourceGroupName string, natGatewayName string) (result NatGatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatGatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, natGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client NatGatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, natGatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "natGatewayName": autorest.Encode("path", natGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/natGateways/{natGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client NatGatewaysClient) DeleteSender(req *http.Request) (future NatGatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client NatGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified nat gateway in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// natGatewayName - the name of the nat gateway. -// expand - expands referenced resources. -func (client NatGatewaysClient) Get(ctx context.Context, resourceGroupName string, natGatewayName string, expand string) (result NatGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatGatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, natGatewayName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "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.NatGatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client NatGatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, natGatewayName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "natGatewayName": autorest.Encode("path", natGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/natGateways/{natGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client NatGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client NatGatewaysClient) GetResponder(resp *http.Response) (result NatGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all nat gateways in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client NatGatewaysClient) List(ctx context.Context, resourceGroupName string) (result NatGatewayListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatGatewaysClient.List") - defer func() { - sc := -1 - if result.nglr.Response.Response != nil { - sc = result.nglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.nglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "List", resp, "Failure sending request") - return - } - - result.nglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "List", resp, "Failure responding to request") - return - } - if result.nglr.hasNextLink() && result.nglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client NatGatewaysClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/natGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client NatGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client NatGatewaysClient) ListResponder(resp *http.Response) (result NatGatewayListResult, err error) { - err = autorest.Respond( - resp, - 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 NatGatewaysClient) listNextResults(ctx context.Context, lastResults NatGatewayListResult) (result NatGatewayListResult, err error) { - req, err := lastResults.natGatewayListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.NatGatewaysClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.NatGatewaysClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client NatGatewaysClient) ListComplete(ctx context.Context, resourceGroupName string) (result NatGatewayListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatGatewaysClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the Nat Gateways in a subscription. -func (client NatGatewaysClient) ListAll(ctx context.Context) (result NatGatewayListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatGatewaysClient.ListAll") - defer func() { - sc := -1 - if result.nglr.Response.Response != nil { - sc = result.nglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.nglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "ListAll", resp, "Failure sending request") - return - } - - result.nglr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "ListAll", resp, "Failure responding to request") - return - } - if result.nglr.hasNextLink() && result.nglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client NatGatewaysClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/natGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client NatGatewaysClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client NatGatewaysClient) ListAllResponder(resp *http.Response) (result NatGatewayListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client NatGatewaysClient) listAllNextResults(ctx context.Context, lastResults NatGatewayListResult) (result NatGatewayListResult, err error) { - req, err := lastResults.natGatewayListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.NatGatewaysClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.NatGatewaysClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client NatGatewaysClient) ListAllComplete(ctx context.Context) (result NatGatewayListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatGatewaysClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// UpdateTags updates nat gateway tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// natGatewayName - the name of the nat gateway. -// parameters - parameters supplied to update nat gateway tags. -func (client NatGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, natGatewayName string, parameters TagsObject) (result NatGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatGatewaysClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, natGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatGatewaysClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client NatGatewaysClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, natGatewayName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "natGatewayName": autorest.Encode("path", natGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/natGateways/{natGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client NatGatewaysClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client NatGatewaysClient) UpdateTagsResponder(resp *http.Response) (result NatGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/natrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/natrules.go deleted file mode 100644 index 4def3d0c5e..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/natrules.go +++ /dev/null @@ -1,393 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// NatRulesClient is the network Client -type NatRulesClient struct { - BaseClient -} - -// NewNatRulesClient creates an instance of the NatRulesClient client. -func NewNatRulesClient(subscriptionID string) NatRulesClient { - return NewNatRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewNatRulesClientWithBaseURI creates an instance of the NatRulesClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewNatRulesClientWithBaseURI(baseURI string, subscriptionID string) NatRulesClient { - return NatRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a nat rule to a scalable vpn gateway if it doesn't exist else updates the existing nat rules. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// natRuleName - the name of the nat rule. -// natRuleParameters - parameters supplied to create or Update a Nat Rule. -func (client NatRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string, natRuleParameters VpnGatewayNatRule) (result NatRulesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatRulesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, gatewayName, natRuleName, natRuleParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatRulesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatRulesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client NatRulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string, natRuleParameters VpnGatewayNatRule) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "natRuleName": autorest.Encode("path", natRuleName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - natRuleParameters.Etag = nil - natRuleParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/natRules/{natRuleName}", pathParameters), - autorest.WithJSON(natRuleParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client NatRulesClient) CreateOrUpdateSender(req *http.Request) (future NatRulesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client NatRulesClient) CreateOrUpdateResponder(resp *http.Response) (result VpnGatewayNatRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a nat rule. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// natRuleName - the name of the nat rule. -func (client NatRulesClient) Delete(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string) (result NatRulesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatRulesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, gatewayName, natRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatRulesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatRulesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client NatRulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "natRuleName": autorest.Encode("path", natRuleName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways/{gatewayName}/natRules/{natRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client NatRulesClient) DeleteSender(req *http.Request) (future NatRulesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client NatRulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a nat ruleGet. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// natRuleName - the name of the nat rule. -func (client NatRulesClient) Get(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string) (result VpnGatewayNatRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, gatewayName, natRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatRulesClient", "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.NatRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client NatRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, gatewayName string, natRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "natRuleName": autorest.Encode("path", natRuleName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways/{gatewayName}/natRules/{natRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client NatRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client NatRulesClient) GetResponder(resp *http.Response) (result VpnGatewayNatRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByVpnGateway retrieves all nat rules for a particular virtual wan vpn gateway. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -func (client NatRulesClient) ListByVpnGateway(ctx context.Context, resourceGroupName string, gatewayName string) (result ListVpnGatewayNatRulesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatRulesClient.ListByVpnGateway") - defer func() { - sc := -1 - if result.lvgnrr.Response.Response != nil { - sc = result.lvgnrr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByVpnGatewayNextResults - req, err := client.ListByVpnGatewayPreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatRulesClient", "ListByVpnGateway", nil, "Failure preparing request") - return - } - - resp, err := client.ListByVpnGatewaySender(req) - if err != nil { - result.lvgnrr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.NatRulesClient", "ListByVpnGateway", resp, "Failure sending request") - return - } - - result.lvgnrr, err = client.ListByVpnGatewayResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatRulesClient", "ListByVpnGateway", resp, "Failure responding to request") - return - } - if result.lvgnrr.hasNextLink() && result.lvgnrr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByVpnGatewayPreparer prepares the ListByVpnGateway request. -func (client NatRulesClient) ListByVpnGatewayPreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways/{gatewayName}/natRules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByVpnGatewaySender sends the ListByVpnGateway request. The method will close the -// http.Response Body if it receives an error. -func (client NatRulesClient) ListByVpnGatewaySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByVpnGatewayResponder handles the response to the ListByVpnGateway request. The method always -// closes the http.Response Body. -func (client NatRulesClient) ListByVpnGatewayResponder(resp *http.Response) (result ListVpnGatewayNatRulesResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByVpnGatewayNextResults retrieves the next set of results, if any. -func (client NatRulesClient) listByVpnGatewayNextResults(ctx context.Context, lastResults ListVpnGatewayNatRulesResult) (result ListVpnGatewayNatRulesResult, err error) { - req, err := lastResults.listVpnGatewayNatRulesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.NatRulesClient", "listByVpnGatewayNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByVpnGatewaySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.NatRulesClient", "listByVpnGatewayNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByVpnGatewayResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.NatRulesClient", "listByVpnGatewayNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByVpnGatewayComplete enumerates all values, automatically crossing page boundaries as required. -func (client NatRulesClient) ListByVpnGatewayComplete(ctx context.Context, resourceGroupName string, gatewayName string) (result ListVpnGatewayNatRulesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/NatRulesClient.ListByVpnGateway") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByVpnGateway(ctx, resourceGroupName, gatewayName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/operations.go deleted file mode 100644 index 3c3c885537..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/operations.go +++ /dev/null @@ -1,140 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// OperationsClient is the network Client -type OperationsClient struct { - BaseClient -} - -// NewOperationsClient creates an instance of the OperationsClient client. -func NewOperationsClient(subscriptionID string) OperationsClient { - return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { - return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List lists all of the available Network Rest API operations. -func (client OperationsClient) List(ctx context.Context) (result OperationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.olr.Response.Response != nil { - sc = result.olr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.OperationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.olr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.OperationsClient", "List", resp, "Failure sending request") - return - } - - result.olr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.OperationsClient", "List", resp, "Failure responding to request") - return - } - if result.olr.hasNextLink() && result.olr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/providers/Microsoft.Network/operations"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) { - err = autorest.Respond( - resp, - 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(ctx context.Context, lastResults OperationListResult) (result OperationListResult, err error) { - req, err := lastResults.operationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.OperationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.OperationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.OperationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client OperationsClient) ListComplete(ctx context.Context) (result OperationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/p2svpngateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/p2svpngateways.go deleted file mode 100644 index 446ce1cafd..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/p2svpngateways.go +++ /dev/null @@ -1,985 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// P2sVpnGatewaysClient is the network Client -type P2sVpnGatewaysClient struct { - BaseClient -} - -// NewP2sVpnGatewaysClient creates an instance of the P2sVpnGatewaysClient client. -func NewP2sVpnGatewaysClient(subscriptionID string) P2sVpnGatewaysClient { - return NewP2sVpnGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewP2sVpnGatewaysClientWithBaseURI creates an instance of the P2sVpnGatewaysClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewP2sVpnGatewaysClientWithBaseURI(baseURI string, subscriptionID string) P2sVpnGatewaysClient { - return P2sVpnGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a virtual wan p2s vpn gateway if it doesn't exist else updates the existing gateway. -// Parameters: -// resourceGroupName - the resource group name of the P2SVpnGateway. -// gatewayName - the name of the gateway. -// p2SVpnGatewayParameters - parameters supplied to create or Update a virtual wan p2s vpn gateway. -func (client P2sVpnGatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, p2SVpnGatewayParameters P2SVpnGateway) (result P2sVpnGatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, gatewayName, p2SVpnGatewayParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client P2sVpnGatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, gatewayName string, p2SVpnGatewayParameters P2SVpnGateway) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - p2SVpnGatewayParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}", pathParameters), - autorest.WithJSON(p2SVpnGatewayParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) CreateOrUpdateSender(req *http.Request) (future P2sVpnGatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result P2SVpnGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a virtual wan p2s vpn gateway. -// Parameters: -// resourceGroupName - the resource group name of the P2SVpnGateway. -// gatewayName - the name of the gateway. -func (client P2sVpnGatewaysClient) Delete(ctx context.Context, resourceGroupName string, gatewayName string) (result P2sVpnGatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client P2sVpnGatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/p2svpnGateways/{gatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) DeleteSender(req *http.Request) (future P2sVpnGatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// DisconnectP2sVpnConnections disconnect P2S vpn connections of the virtual wan P2SVpnGateway in the specified -// resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// p2sVpnGatewayName - the name of the P2S Vpn Gateway. -// request - the parameters are supplied to disconnect p2s vpn connections. -func (client P2sVpnGatewaysClient) DisconnectP2sVpnConnections(ctx context.Context, resourceGroupName string, p2sVpnGatewayName string, request P2SVpnConnectionRequest) (result P2sVpnGatewaysDisconnectP2sVpnConnectionsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.DisconnectP2sVpnConnections") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DisconnectP2sVpnConnectionsPreparer(ctx, resourceGroupName, p2sVpnGatewayName, request) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "DisconnectP2sVpnConnections", nil, "Failure preparing request") - return - } - - result, err = client.DisconnectP2sVpnConnectionsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "DisconnectP2sVpnConnections", result.Response(), "Failure sending request") - return - } - - return -} - -// DisconnectP2sVpnConnectionsPreparer prepares the DisconnectP2sVpnConnections request. -func (client P2sVpnGatewaysClient) DisconnectP2sVpnConnectionsPreparer(ctx context.Context, resourceGroupName string, p2sVpnGatewayName string, request P2SVpnConnectionRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "p2sVpnGatewayName": autorest.Encode("path", p2sVpnGatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{p2sVpnGatewayName}/disconnectP2sVpnConnections", pathParameters), - autorest.WithJSON(request), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DisconnectP2sVpnConnectionsSender sends the DisconnectP2sVpnConnections request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) DisconnectP2sVpnConnectionsSender(req *http.Request) (future P2sVpnGatewaysDisconnectP2sVpnConnectionsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DisconnectP2sVpnConnectionsResponder handles the response to the DisconnectP2sVpnConnections request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) DisconnectP2sVpnConnectionsResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// GenerateVpnProfile generates VPN profile for P2S client of the P2SVpnGateway in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// gatewayName - the name of the P2SVpnGateway. -// parameters - parameters supplied to the generate P2SVpnGateway VPN client package operation. -func (client P2sVpnGatewaysClient) GenerateVpnProfile(ctx context.Context, resourceGroupName string, gatewayName string, parameters P2SVpnProfileParameters) (result P2sVpnGatewaysGenerateVpnProfileFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.GenerateVpnProfile") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GenerateVpnProfilePreparer(ctx, resourceGroupName, gatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "GenerateVpnProfile", nil, "Failure preparing request") - return - } - - result, err = client.GenerateVpnProfileSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "GenerateVpnProfile", result.Response(), "Failure sending request") - return - } - - return -} - -// GenerateVpnProfilePreparer prepares the GenerateVpnProfile request. -func (client P2sVpnGatewaysClient) GenerateVpnProfilePreparer(ctx context.Context, resourceGroupName string, gatewayName string, parameters P2SVpnProfileParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/generatevpnprofile", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GenerateVpnProfileSender sends the GenerateVpnProfile request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) GenerateVpnProfileSender(req *http.Request) (future P2sVpnGatewaysGenerateVpnProfileFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GenerateVpnProfileResponder handles the response to the GenerateVpnProfile request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) GenerateVpnProfileResponder(resp *http.Response) (result VpnProfileResponse, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get retrieves the details of a virtual wan p2s vpn gateway. -// Parameters: -// resourceGroupName - the resource group name of the P2SVpnGateway. -// gatewayName - the name of the gateway. -func (client P2sVpnGatewaysClient) Get(ctx context.Context, resourceGroupName string, gatewayName string) (result P2SVpnGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "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.P2sVpnGatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client P2sVpnGatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/p2svpnGateways/{gatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) GetResponder(resp *http.Response) (result P2SVpnGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetP2sVpnConnectionHealth gets the connection health of P2S clients of the virtual wan P2SVpnGateway in the -// specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// gatewayName - the name of the P2SVpnGateway. -func (client P2sVpnGatewaysClient) GetP2sVpnConnectionHealth(ctx context.Context, resourceGroupName string, gatewayName string) (result P2sVpnGatewaysGetP2sVpnConnectionHealthFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.GetP2sVpnConnectionHealth") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetP2sVpnConnectionHealthPreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "GetP2sVpnConnectionHealth", nil, "Failure preparing request") - return - } - - result, err = client.GetP2sVpnConnectionHealthSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "GetP2sVpnConnectionHealth", result.Response(), "Failure sending request") - return - } - - return -} - -// GetP2sVpnConnectionHealthPreparer prepares the GetP2sVpnConnectionHealth request. -func (client P2sVpnGatewaysClient) GetP2sVpnConnectionHealthPreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/p2svpnGateways/{gatewayName}/getP2sVpnConnectionHealth", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetP2sVpnConnectionHealthSender sends the GetP2sVpnConnectionHealth request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) GetP2sVpnConnectionHealthSender(req *http.Request) (future P2sVpnGatewaysGetP2sVpnConnectionHealthFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetP2sVpnConnectionHealthResponder handles the response to the GetP2sVpnConnectionHealth request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) GetP2sVpnConnectionHealthResponder(resp *http.Response) (result P2SVpnGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetP2sVpnConnectionHealthDetailed gets the sas url to get the connection health detail of P2S clients of the virtual -// wan P2SVpnGateway in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// gatewayName - the name of the P2SVpnGateway. -// request - request parameters supplied to get p2s vpn connections detailed health. -func (client P2sVpnGatewaysClient) GetP2sVpnConnectionHealthDetailed(ctx context.Context, resourceGroupName string, gatewayName string, request P2SVpnConnectionHealthRequest) (result P2sVpnGatewaysGetP2sVpnConnectionHealthDetailedFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.GetP2sVpnConnectionHealthDetailed") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetP2sVpnConnectionHealthDetailedPreparer(ctx, resourceGroupName, gatewayName, request) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "GetP2sVpnConnectionHealthDetailed", nil, "Failure preparing request") - return - } - - result, err = client.GetP2sVpnConnectionHealthDetailedSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "GetP2sVpnConnectionHealthDetailed", result.Response(), "Failure sending request") - return - } - - return -} - -// GetP2sVpnConnectionHealthDetailedPreparer prepares the GetP2sVpnConnectionHealthDetailed request. -func (client P2sVpnGatewaysClient) GetP2sVpnConnectionHealthDetailedPreparer(ctx context.Context, resourceGroupName string, gatewayName string, request P2SVpnConnectionHealthRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}/getP2sVpnConnectionHealthDetailed", pathParameters), - autorest.WithJSON(request), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetP2sVpnConnectionHealthDetailedSender sends the GetP2sVpnConnectionHealthDetailed request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) GetP2sVpnConnectionHealthDetailedSender(req *http.Request) (future P2sVpnGatewaysGetP2sVpnConnectionHealthDetailedFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetP2sVpnConnectionHealthDetailedResponder handles the response to the GetP2sVpnConnectionHealthDetailed request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) GetP2sVpnConnectionHealthDetailedResponder(resp *http.Response) (result P2SVpnConnectionHealth, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the P2SVpnGateways in a subscription. -func (client P2sVpnGatewaysClient) List(ctx context.Context) (result ListP2SVpnGatewaysResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.List") - defer func() { - sc := -1 - if result.lpvgr.Response.Response != nil { - sc = result.lpvgr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lpvgr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "List", resp, "Failure sending request") - return - } - - result.lpvgr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "List", resp, "Failure responding to request") - return - } - if result.lpvgr.hasNextLink() && result.lpvgr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client P2sVpnGatewaysClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/p2svpnGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) ListResponder(resp *http.Response) (result ListP2SVpnGatewaysResult, err error) { - err = autorest.Respond( - resp, - 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 P2sVpnGatewaysClient) listNextResults(ctx context.Context, lastResults ListP2SVpnGatewaysResult) (result ListP2SVpnGatewaysResult, err error) { - req, err := lastResults.listP2SVpnGatewaysResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client P2sVpnGatewaysClient) ListComplete(ctx context.Context) (result ListP2SVpnGatewaysResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all the P2SVpnGateways in a resource group. -// Parameters: -// resourceGroupName - the resource group name of the P2SVpnGateway. -func (client P2sVpnGatewaysClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListP2SVpnGatewaysResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.lpvgr.Response.Response != nil { - sc = result.lpvgr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.lpvgr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.lpvgr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.lpvgr.hasNextLink() && result.lpvgr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client P2sVpnGatewaysClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/p2svpnGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) ListByResourceGroupResponder(resp *http.Response) (result ListP2SVpnGatewaysResult, err error) { - err = autorest.Respond( - resp, - 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 P2sVpnGatewaysClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListP2SVpnGatewaysResult) (result ListP2SVpnGatewaysResult, err error) { - req, err := lastResults.listP2SVpnGatewaysResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client P2sVpnGatewaysClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListP2SVpnGatewaysResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// Reset resets the primary of the p2s vpn gateway in the specified resource group. -// Parameters: -// resourceGroupName - the resource group name of the P2SVpnGateway. -// gatewayName - the name of the gateway. -func (client P2sVpnGatewaysClient) Reset(ctx context.Context, resourceGroupName string, gatewayName string) (result P2SVpnGatewaysResetFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.Reset") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ResetPreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "Reset", nil, "Failure preparing request") - return - } - - result, err = client.ResetSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "Reset", result.Response(), "Failure sending request") - return - } - - return -} - -// ResetPreparer prepares the Reset request. -func (client P2sVpnGatewaysClient) ResetPreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/p2svpnGateways/{gatewayName}/reset", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ResetSender sends the Reset request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) ResetSender(req *http.Request) (future P2SVpnGatewaysResetFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ResetResponder handles the response to the Reset request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) ResetResponder(resp *http.Response) (result P2SVpnGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates virtual wan p2s vpn gateway tags. -// Parameters: -// resourceGroupName - the resource group name of the P2SVpnGateway. -// gatewayName - the name of the gateway. -// p2SVpnGatewayParameters - parameters supplied to update a virtual wan p2s vpn gateway tags. -func (client P2sVpnGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, gatewayName string, p2SVpnGatewayParameters TagsObject) (result P2sVpnGatewaysUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/P2sVpnGatewaysClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, gatewayName, p2SVpnGatewayParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.P2sVpnGatewaysClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client P2sVpnGatewaysClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, gatewayName string, p2SVpnGatewayParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/p2svpnGateways/{gatewayName}", pathParameters), - autorest.WithJSON(p2SVpnGatewayParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client P2sVpnGatewaysClient) UpdateTagsSender(req *http.Request) (future P2sVpnGatewaysUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client P2sVpnGatewaysClient) UpdateTagsResponder(resp *http.Response) (result P2SVpnGateway, err error) { - err = autorest.Respond( - resp, - 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/services/network/mgmt/2022-07-01/network/packetcaptures.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/packetcaptures.go deleted file mode 100644 index d6998421de..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/packetcaptures.go +++ /dev/null @@ -1,532 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PacketCapturesClient is the network Client -type PacketCapturesClient struct { - BaseClient -} - -// 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 using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewPacketCapturesClientWithBaseURI(baseURI string, subscriptionID string) PacketCapturesClient { - return PacketCapturesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Create create and start a packet capture on the specified VM. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// packetCaptureName - the name of the packet capture session. -// parameters - parameters that define the create packet capture operation. -func (client PacketCapturesClient) Create(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, parameters PacketCapture) (result PacketCapturesCreateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PacketCapturesClient.Create") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.BytesToCapturePerPacket", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PacketCaptureParameters.BytesToCapturePerPacket", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "parameters.PacketCaptureParameters.BytesToCapturePerPacket", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - {Target: "parameters.PacketCaptureParameters.TotalBytesPerSession", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PacketCaptureParameters.TotalBytesPerSession", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "parameters.PacketCaptureParameters.TotalBytesPerSession", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - {Target: "parameters.PacketCaptureParameters.TimeLimitInSeconds", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PacketCaptureParameters.TimeLimitInSeconds", Name: validation.InclusiveMaximum, Rule: int64(18000), Chain: nil}, - {Target: "parameters.PacketCaptureParameters.TimeLimitInSeconds", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - {Target: "parameters.PacketCaptureParameters.StorageLocation", Name: validation.Null, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.PacketCapturesClient", "Create", err.Error()) - } - - req, err := client.CreatePreparer(ctx, resourceGroupName, networkWatcherName, packetCaptureName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Create", nil, "Failure preparing request") - return - } - - result, err = client.CreateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Create", result.Response(), "Failure sending request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client PacketCapturesClient) CreatePreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string, parameters PacketCapture) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client PacketCapturesClient) CreateSender(req *http.Request) (future PacketCapturesCreateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// packetCaptureName - the name of the packet capture session. -func (client PacketCapturesClient) Delete(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string) (result PacketCapturesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PacketCapturesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkWatcherName, packetCaptureName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client PacketCapturesClient) DeletePreparer(ctx context.Context, 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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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) (future PacketCapturesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a packet capture session by name. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// packetCaptureName - the name of the packet capture session. -func (client PacketCapturesClient) Get(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string) (result PacketCaptureResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PacketCapturesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, 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 - } - - return -} - -// GetPreparer prepares the Get request. -func (client PacketCapturesClient) GetPreparer(ctx context.Context, 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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the Network Watcher resource. -// packetCaptureName - the name given to the packet capture session. -func (client PacketCapturesClient) GetStatus(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string) (result PacketCapturesGetStatusFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PacketCapturesClient.GetStatus") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetStatusPreparer(ctx, resourceGroupName, networkWatcherName, packetCaptureName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "GetStatus", nil, "Failure preparing request") - return - } - - result, err = client.GetStatusSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "GetStatus", result.Response(), "Failure sending request") - return - } - - return -} - -// GetStatusPreparer prepares the GetStatus request. -func (client PacketCapturesClient) GetStatusPreparer(ctx context.Context, 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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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) (future PacketCapturesGetStatusFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the Network Watcher resource. -func (client PacketCapturesClient) List(ctx context.Context, resourceGroupName string, networkWatcherName string) (result PacketCaptureListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PacketCapturesClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, 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 - } - - return -} - -// ListPreparer prepares the List request. -func (client PacketCapturesClient) ListPreparer(ctx context.Context, 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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Stop stops a specified packet capture session. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// packetCaptureName - the name of the packet capture session. -func (client PacketCapturesClient) Stop(ctx context.Context, resourceGroupName string, networkWatcherName string, packetCaptureName string) (result PacketCapturesStopFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PacketCapturesClient.Stop") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPreparer(ctx, resourceGroupName, networkWatcherName, packetCaptureName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Stop", nil, "Failure preparing request") - return - } - - result, err = client.StopSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Stop", result.Response(), "Failure sending request") - return - } - - return -} - -// StopPreparer prepares the Stop request. -func (client PacketCapturesClient) StopPreparer(ctx context.Context, 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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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) (future PacketCapturesStopFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/peerexpressroutecircuitconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/peerexpressroutecircuitconnections.go deleted file mode 100644 index dca72d3ce7..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/peerexpressroutecircuitconnections.go +++ /dev/null @@ -1,233 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PeerExpressRouteCircuitConnectionsClient is the network Client -type PeerExpressRouteCircuitConnectionsClient struct { - BaseClient -} - -// NewPeerExpressRouteCircuitConnectionsClient creates an instance of the PeerExpressRouteCircuitConnectionsClient -// client. -func NewPeerExpressRouteCircuitConnectionsClient(subscriptionID string) PeerExpressRouteCircuitConnectionsClient { - return NewPeerExpressRouteCircuitConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPeerExpressRouteCircuitConnectionsClientWithBaseURI creates an instance of the -// PeerExpressRouteCircuitConnectionsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewPeerExpressRouteCircuitConnectionsClientWithBaseURI(baseURI string, subscriptionID string) PeerExpressRouteCircuitConnectionsClient { - return PeerExpressRouteCircuitConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets the specified Peer Express Route Circuit Connection from the specified express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the express route circuit. -// peeringName - the name of the peering. -// connectionName - the name of the peer express route circuit connection. -func (client PeerExpressRouteCircuitConnectionsClient) Get(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (result PeerExpressRouteCircuitConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PeerExpressRouteCircuitConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, circuitName, peeringName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PeerExpressRouteCircuitConnectionsClient", "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.PeerExpressRouteCircuitConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PeerExpressRouteCircuitConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PeerExpressRouteCircuitConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "connectionName": autorest.Encode("path", connectionName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/peerings/{peeringName}/peerConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client PeerExpressRouteCircuitConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PeerExpressRouteCircuitConnectionsClient) GetResponder(resp *http.Response) (result PeerExpressRouteCircuitConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all global reach peer connections associated with a private peering in an express route circuit. -// Parameters: -// resourceGroupName - the name of the resource group. -// circuitName - the name of the circuit. -// peeringName - the name of the peering. -func (client PeerExpressRouteCircuitConnectionsClient) List(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result PeerExpressRouteCircuitConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PeerExpressRouteCircuitConnectionsClient.List") - defer func() { - sc := -1 - if result.percclr.Response.Response != nil { - sc = result.percclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, circuitName, peeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PeerExpressRouteCircuitConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.percclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PeerExpressRouteCircuitConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.percclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PeerExpressRouteCircuitConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.percclr.hasNextLink() && result.percclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PeerExpressRouteCircuitConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "circuitName": autorest.Encode("path", circuitName), - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/expressRouteCircuits/{circuitName}/peerings/{peeringName}/peerConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client PeerExpressRouteCircuitConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client PeerExpressRouteCircuitConnectionsClient) ListResponder(resp *http.Response) (result PeerExpressRouteCircuitConnectionListResult, err error) { - err = autorest.Respond( - resp, - 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 PeerExpressRouteCircuitConnectionsClient) listNextResults(ctx context.Context, lastResults PeerExpressRouteCircuitConnectionListResult) (result PeerExpressRouteCircuitConnectionListResult, err error) { - req, err := lastResults.peerExpressRouteCircuitConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PeerExpressRouteCircuitConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PeerExpressRouteCircuitConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PeerExpressRouteCircuitConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client PeerExpressRouteCircuitConnectionsClient) ListComplete(ctx context.Context, resourceGroupName string, circuitName string, peeringName string) (result PeerExpressRouteCircuitConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PeerExpressRouteCircuitConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, circuitName, peeringName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/privatednszonegroups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/privatednszonegroups.go deleted file mode 100644 index 362708731b..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/privatednszonegroups.go +++ /dev/null @@ -1,393 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PrivateDNSZoneGroupsClient is the network Client -type PrivateDNSZoneGroupsClient struct { - BaseClient -} - -// NewPrivateDNSZoneGroupsClient creates an instance of the PrivateDNSZoneGroupsClient client. -func NewPrivateDNSZoneGroupsClient(subscriptionID string) PrivateDNSZoneGroupsClient { - return NewPrivateDNSZoneGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPrivateDNSZoneGroupsClientWithBaseURI creates an instance of the PrivateDNSZoneGroupsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewPrivateDNSZoneGroupsClientWithBaseURI(baseURI string, subscriptionID string) PrivateDNSZoneGroupsClient { - return PrivateDNSZoneGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a private dns zone group in the specified private endpoint. -// Parameters: -// resourceGroupName - the name of the resource group. -// privateEndpointName - the name of the private endpoint. -// privateDNSZoneGroupName - the name of the private dns zone group. -// parameters - parameters supplied to the create or update private dns zone group operation. -func (client PrivateDNSZoneGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, parameters PrivateDNSZoneGroup) (result PrivateDNSZoneGroupsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateDNSZoneGroupsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, privateEndpointName, privateDNSZoneGroupName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client PrivateDNSZoneGroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, parameters PrivateDNSZoneGroup) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "privateDnsZoneGroupName": autorest.Encode("path", privateDNSZoneGroupName), - "privateEndpointName": autorest.Encode("path", privateEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateDNSZoneGroupsClient) CreateOrUpdateSender(req *http.Request) (future PrivateDNSZoneGroupsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client PrivateDNSZoneGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result PrivateDNSZoneGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified private dns zone group. -// Parameters: -// resourceGroupName - the name of the resource group. -// privateEndpointName - the name of the private endpoint. -// privateDNSZoneGroupName - the name of the private dns zone group. -func (client PrivateDNSZoneGroupsClient) Delete(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string) (result PrivateDNSZoneGroupsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateDNSZoneGroupsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, privateEndpointName, privateDNSZoneGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client PrivateDNSZoneGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "privateDnsZoneGroupName": autorest.Encode("path", privateDNSZoneGroupName), - "privateEndpointName": autorest.Encode("path", privateEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateDNSZoneGroupsClient) DeleteSender(req *http.Request) (future PrivateDNSZoneGroupsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client PrivateDNSZoneGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the private dns zone group resource by specified private dns zone group name. -// Parameters: -// resourceGroupName - the name of the resource group. -// privateEndpointName - the name of the private endpoint. -// privateDNSZoneGroupName - the name of the private dns zone group. -func (client PrivateDNSZoneGroupsClient) Get(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string) (result PrivateDNSZoneGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateDNSZoneGroupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, privateEndpointName, privateDNSZoneGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsClient", "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.PrivateDNSZoneGroupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PrivateDNSZoneGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "privateDnsZoneGroupName": autorest.Encode("path", privateDNSZoneGroupName), - "privateEndpointName": autorest.Encode("path", privateEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateDNSZoneGroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PrivateDNSZoneGroupsClient) GetResponder(resp *http.Response) (result PrivateDNSZoneGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all private dns zone groups in a private endpoint. -// Parameters: -// privateEndpointName - the name of the private endpoint. -// resourceGroupName - the name of the resource group. -func (client PrivateDNSZoneGroupsClient) List(ctx context.Context, privateEndpointName string, resourceGroupName string) (result PrivateDNSZoneGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateDNSZoneGroupsClient.List") - defer func() { - sc := -1 - if result.pdzglr.Response.Response != nil { - sc = result.pdzglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, privateEndpointName, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.pdzglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsClient", "List", resp, "Failure sending request") - return - } - - result.pdzglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsClient", "List", resp, "Failure responding to request") - return - } - if result.pdzglr.hasNextLink() && result.pdzglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PrivateDNSZoneGroupsClient) ListPreparer(ctx context.Context, privateEndpointName string, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "privateEndpointName": autorest.Encode("path", privateEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateDNSZoneGroupsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client PrivateDNSZoneGroupsClient) ListResponder(resp *http.Response) (result PrivateDNSZoneGroupListResult, err error) { - err = autorest.Respond( - resp, - 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 PrivateDNSZoneGroupsClient) listNextResults(ctx context.Context, lastResults PrivateDNSZoneGroupListResult) (result PrivateDNSZoneGroupListResult, err error) { - req, err := lastResults.privateDNSZoneGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateDNSZoneGroupsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client PrivateDNSZoneGroupsClient) ListComplete(ctx context.Context, privateEndpointName string, resourceGroupName string) (result PrivateDNSZoneGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateDNSZoneGroupsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, privateEndpointName, resourceGroupName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/privateendpoints.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/privateendpoints.go deleted file mode 100644 index f85e9b3022..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/privateendpoints.go +++ /dev/null @@ -1,502 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PrivateEndpointsClient is the network Client -type PrivateEndpointsClient struct { - BaseClient -} - -// NewPrivateEndpointsClient creates an instance of the PrivateEndpointsClient client. -func NewPrivateEndpointsClient(subscriptionID string) PrivateEndpointsClient { - return NewPrivateEndpointsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPrivateEndpointsClientWithBaseURI creates an instance of the PrivateEndpointsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewPrivateEndpointsClientWithBaseURI(baseURI string, subscriptionID string) PrivateEndpointsClient { - return PrivateEndpointsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates an private endpoint in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// privateEndpointName - the name of the private endpoint. -// parameters - parameters supplied to the create or update private endpoint operation. -func (client PrivateEndpointsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, privateEndpointName string, parameters PrivateEndpoint) (result PrivateEndpointsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, privateEndpointName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client PrivateEndpointsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, privateEndpointName string, parameters PrivateEndpoint) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "privateEndpointName": autorest.Encode("path", privateEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateEndpointsClient) CreateOrUpdateSender(req *http.Request) (future PrivateEndpointsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client PrivateEndpointsClient) CreateOrUpdateResponder(resp *http.Response) (result PrivateEndpoint, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified private endpoint. -// Parameters: -// resourceGroupName - the name of the resource group. -// privateEndpointName - the name of the private endpoint. -func (client PrivateEndpointsClient) Delete(ctx context.Context, resourceGroupName string, privateEndpointName string) (result PrivateEndpointsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, privateEndpointName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client PrivateEndpointsClient) DeletePreparer(ctx context.Context, resourceGroupName string, privateEndpointName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "privateEndpointName": autorest.Encode("path", privateEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/privateEndpoints/{privateEndpointName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateEndpointsClient) DeleteSender(req *http.Request) (future PrivateEndpointsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client PrivateEndpointsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified private endpoint by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// privateEndpointName - the name of the private endpoint. -// expand - expands referenced resources. -func (client PrivateEndpointsClient) Get(ctx context.Context, resourceGroupName string, privateEndpointName string, expand string) (result PrivateEndpoint, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, privateEndpointName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "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.PrivateEndpointsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PrivateEndpointsClient) GetPreparer(ctx context.Context, resourceGroupName string, privateEndpointName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "privateEndpointName": autorest.Encode("path", privateEndpointName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/privateEndpoints/{privateEndpointName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateEndpointsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PrivateEndpointsClient) GetResponder(resp *http.Response) (result PrivateEndpoint, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all private endpoints in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client PrivateEndpointsClient) List(ctx context.Context, resourceGroupName string) (result PrivateEndpointListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointsClient.List") - defer func() { - sc := -1 - if result.pelr.Response.Response != nil { - sc = result.pelr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.pelr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "List", resp, "Failure sending request") - return - } - - result.pelr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "List", resp, "Failure responding to request") - return - } - if result.pelr.hasNextLink() && result.pelr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PrivateEndpointsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/privateEndpoints", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateEndpointsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client PrivateEndpointsClient) ListResponder(resp *http.Response) (result PrivateEndpointListResult, err error) { - err = autorest.Respond( - resp, - 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 PrivateEndpointsClient) listNextResults(ctx context.Context, lastResults PrivateEndpointListResult) (result PrivateEndpointListResult, err error) { - req, err := lastResults.privateEndpointListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client PrivateEndpointsClient) ListComplete(ctx context.Context, resourceGroupName string) (result PrivateEndpointListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListBySubscription gets all private endpoints in a subscription. -func (client PrivateEndpointsClient) ListBySubscription(ctx context.Context) (result PrivateEndpointListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointsClient.ListBySubscription") - defer func() { - sc := -1 - if result.pelr.Response.Response != nil { - sc = result.pelr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listBySubscriptionNextResults - req, err := client.ListBySubscriptionPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "ListBySubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.pelr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "ListBySubscription", resp, "Failure sending request") - return - } - - result.pelr, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "ListBySubscription", resp, "Failure responding to request") - return - } - if result.pelr.hasNextLink() && result.pelr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client PrivateEndpointsClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/privateEndpoints", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBySubscriptionSender sends the ListBySubscription request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateEndpointsClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always -// closes the http.Response Body. -func (client PrivateEndpointsClient) ListBySubscriptionResponder(resp *http.Response) (result PrivateEndpointListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listBySubscriptionNextResults retrieves the next set of results, if any. -func (client PrivateEndpointsClient) listBySubscriptionNextResults(ctx context.Context, lastResults PrivateEndpointListResult) (result PrivateEndpointListResult, err error) { - req, err := lastResults.privateEndpointListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateEndpointsClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client PrivateEndpointsClient) ListBySubscriptionComplete(ctx context.Context) (result PrivateEndpointListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointsClient.ListBySubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListBySubscription(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/privatelinkservices.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/privatelinkservices.go deleted file mode 100644 index 15ddba895d..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/privatelinkservices.go +++ /dev/null @@ -1,1266 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PrivateLinkServicesClient is the network Client -type PrivateLinkServicesClient struct { - BaseClient -} - -// NewPrivateLinkServicesClient creates an instance of the PrivateLinkServicesClient client. -func NewPrivateLinkServicesClient(subscriptionID string) PrivateLinkServicesClient { - return NewPrivateLinkServicesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPrivateLinkServicesClientWithBaseURI creates an instance of the PrivateLinkServicesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewPrivateLinkServicesClientWithBaseURI(baseURI string, subscriptionID string) PrivateLinkServicesClient { - return PrivateLinkServicesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CheckPrivateLinkServiceVisibility checks whether the subscription is visible to private link service. -// Parameters: -// location - the location of the domain name. -// parameters - the request body of CheckPrivateLinkService API call. -func (client PrivateLinkServicesClient) CheckPrivateLinkServiceVisibility(ctx context.Context, location string, parameters CheckPrivateLinkServiceVisibilityRequest) (result PrivateLinkServicesCheckPrivateLinkServiceVisibilityFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.CheckPrivateLinkServiceVisibility") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CheckPrivateLinkServiceVisibilityPreparer(ctx, location, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "CheckPrivateLinkServiceVisibility", nil, "Failure preparing request") - return - } - - result, err = client.CheckPrivateLinkServiceVisibilitySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "CheckPrivateLinkServiceVisibility", result.Response(), "Failure sending request") - return - } - - return -} - -// CheckPrivateLinkServiceVisibilityPreparer prepares the CheckPrivateLinkServiceVisibility request. -func (client PrivateLinkServicesClient) CheckPrivateLinkServiceVisibilityPreparer(ctx context.Context, location string, parameters CheckPrivateLinkServiceVisibilityRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/checkPrivateLinkServiceVisibility", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckPrivateLinkServiceVisibilitySender sends the CheckPrivateLinkServiceVisibility request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateLinkServicesClient) CheckPrivateLinkServiceVisibilitySender(req *http.Request) (future PrivateLinkServicesCheckPrivateLinkServiceVisibilityFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CheckPrivateLinkServiceVisibilityResponder handles the response to the CheckPrivateLinkServiceVisibility request. The method always -// closes the http.Response Body. -func (client PrivateLinkServicesClient) CheckPrivateLinkServiceVisibilityResponder(resp *http.Response) (result PrivateLinkServiceVisibility, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CheckPrivateLinkServiceVisibilityByResourceGroup checks whether the subscription is visible to private link service -// in the specified resource group. -// Parameters: -// location - the location of the domain name. -// resourceGroupName - the name of the resource group. -// parameters - the request body of CheckPrivateLinkService API call. -func (client PrivateLinkServicesClient) CheckPrivateLinkServiceVisibilityByResourceGroup(ctx context.Context, location string, resourceGroupName string, parameters CheckPrivateLinkServiceVisibilityRequest) (result PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.CheckPrivateLinkServiceVisibilityByResourceGroup") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CheckPrivateLinkServiceVisibilityByResourceGroupPreparer(ctx, location, resourceGroupName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "CheckPrivateLinkServiceVisibilityByResourceGroup", nil, "Failure preparing request") - return - } - - result, err = client.CheckPrivateLinkServiceVisibilityByResourceGroupSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "CheckPrivateLinkServiceVisibilityByResourceGroup", result.Response(), "Failure sending request") - return - } - - return -} - -// CheckPrivateLinkServiceVisibilityByResourceGroupPreparer prepares the CheckPrivateLinkServiceVisibilityByResourceGroup request. -func (client PrivateLinkServicesClient) CheckPrivateLinkServiceVisibilityByResourceGroupPreparer(ctx context.Context, location string, resourceGroupName string, parameters CheckPrivateLinkServiceVisibilityRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/locations/{location}/checkPrivateLinkServiceVisibility", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckPrivateLinkServiceVisibilityByResourceGroupSender sends the CheckPrivateLinkServiceVisibilityByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateLinkServicesClient) CheckPrivateLinkServiceVisibilityByResourceGroupSender(req *http.Request) (future PrivateLinkServicesCheckPrivateLinkServiceVisibilityByResourceGroupFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CheckPrivateLinkServiceVisibilityByResourceGroupResponder handles the response to the CheckPrivateLinkServiceVisibilityByResourceGroup request. The method always -// closes the http.Response Body. -func (client PrivateLinkServicesClient) CheckPrivateLinkServiceVisibilityByResourceGroupResponder(resp *http.Response) (result PrivateLinkServiceVisibility, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate creates or updates an private link service in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceName - the name of the private link service. -// parameters - parameters supplied to the create or update private link service operation. -func (client PrivateLinkServicesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, parameters PrivateLinkService) (result PrivateLinkServicesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client PrivateLinkServicesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, parameters PrivateLinkService) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateLinkServicesClient) CreateOrUpdateSender(req *http.Request) (future PrivateLinkServicesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client PrivateLinkServicesClient) CreateOrUpdateResponder(resp *http.Response) (result PrivateLinkService, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified private link service. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceName - the name of the private link service. -func (client PrivateLinkServicesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string) (result PrivateLinkServicesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client PrivateLinkServicesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/privateLinkServices/{serviceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateLinkServicesClient) DeleteSender(req *http.Request) (future PrivateLinkServicesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client PrivateLinkServicesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// DeletePrivateEndpointConnection delete private end point connection for a private link service in a subscription. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceName - the name of the private link service. -// peConnectionName - the name of the private end point connection. -func (client PrivateLinkServicesClient) DeletePrivateEndpointConnection(ctx context.Context, resourceGroupName string, serviceName string, peConnectionName string) (result PrivateLinkServicesDeletePrivateEndpointConnectionFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.DeletePrivateEndpointConnection") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePrivateEndpointConnectionPreparer(ctx, resourceGroupName, serviceName, peConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "DeletePrivateEndpointConnection", nil, "Failure preparing request") - return - } - - result, err = client.DeletePrivateEndpointConnectionSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "DeletePrivateEndpointConnection", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePrivateEndpointConnectionPreparer prepares the DeletePrivateEndpointConnection request. -func (client PrivateLinkServicesClient) DeletePrivateEndpointConnectionPreparer(ctx context.Context, resourceGroupName string, serviceName string, peConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "peConnectionName": autorest.Encode("path", peConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/privateLinkServices/{serviceName}/privateEndpointConnections/{peConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeletePrivateEndpointConnectionSender sends the DeletePrivateEndpointConnection request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateLinkServicesClient) DeletePrivateEndpointConnectionSender(req *http.Request) (future PrivateLinkServicesDeletePrivateEndpointConnectionFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeletePrivateEndpointConnectionResponder handles the response to the DeletePrivateEndpointConnection request. The method always -// closes the http.Response Body. -func (client PrivateLinkServicesClient) DeletePrivateEndpointConnectionResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified private link service by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceName - the name of the private link service. -// expand - expands referenced resources. -func (client PrivateLinkServicesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, expand string) (result PrivateLinkService, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "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.PrivateLinkServicesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PrivateLinkServicesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/privateLinkServices/{serviceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateLinkServicesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PrivateLinkServicesClient) GetResponder(resp *http.Response) (result PrivateLinkService, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetPrivateEndpointConnection get the specific private end point connection by specific private link service in the -// resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceName - the name of the private link service. -// peConnectionName - the name of the private end point connection. -// expand - expands referenced resources. -func (client PrivateLinkServicesClient) GetPrivateEndpointConnection(ctx context.Context, resourceGroupName string, serviceName string, peConnectionName string, expand string) (result PrivateEndpointConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.GetPrivateEndpointConnection") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPrivateEndpointConnectionPreparer(ctx, resourceGroupName, serviceName, peConnectionName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "GetPrivateEndpointConnection", nil, "Failure preparing request") - return - } - - resp, err := client.GetPrivateEndpointConnectionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "GetPrivateEndpointConnection", resp, "Failure sending request") - return - } - - result, err = client.GetPrivateEndpointConnectionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "GetPrivateEndpointConnection", resp, "Failure responding to request") - return - } - - return -} - -// GetPrivateEndpointConnectionPreparer prepares the GetPrivateEndpointConnection request. -func (client PrivateLinkServicesClient) GetPrivateEndpointConnectionPreparer(ctx context.Context, resourceGroupName string, serviceName string, peConnectionName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "peConnectionName": autorest.Encode("path", peConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/privateLinkServices/{serviceName}/privateEndpointConnections/{peConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetPrivateEndpointConnectionSender sends the GetPrivateEndpointConnection request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateLinkServicesClient) GetPrivateEndpointConnectionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetPrivateEndpointConnectionResponder handles the response to the GetPrivateEndpointConnection request. The method always -// closes the http.Response Body. -func (client PrivateLinkServicesClient) GetPrivateEndpointConnectionResponder(resp *http.Response) (result PrivateEndpointConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all private link services in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client PrivateLinkServicesClient) List(ctx context.Context, resourceGroupName string) (result PrivateLinkServiceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.List") - defer func() { - sc := -1 - if result.plslr.Response.Response != nil { - sc = result.plslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.plslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "List", resp, "Failure sending request") - return - } - - result.plslr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "List", resp, "Failure responding to request") - return - } - if result.plslr.hasNextLink() && result.plslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PrivateLinkServicesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/privateLinkServices", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateLinkServicesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client PrivateLinkServicesClient) ListResponder(resp *http.Response) (result PrivateLinkServiceListResult, err error) { - err = autorest.Respond( - resp, - 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 PrivateLinkServicesClient) listNextResults(ctx context.Context, lastResults PrivateLinkServiceListResult) (result PrivateLinkServiceListResult, err error) { - req, err := lastResults.privateLinkServiceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client PrivateLinkServicesClient) ListComplete(ctx context.Context, resourceGroupName string) (result PrivateLinkServiceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAutoApprovedPrivateLinkServices returns all of the private link service ids that can be linked to a Private -// Endpoint with auto approved in this subscription in this region. -// Parameters: -// location - the location of the domain name. -func (client PrivateLinkServicesClient) ListAutoApprovedPrivateLinkServices(ctx context.Context, location string) (result AutoApprovedPrivateLinkServicesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.ListAutoApprovedPrivateLinkServices") - defer func() { - sc := -1 - if result.aaplsr.Response.Response != nil { - sc = result.aaplsr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAutoApprovedPrivateLinkServicesNextResults - req, err := client.ListAutoApprovedPrivateLinkServicesPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "ListAutoApprovedPrivateLinkServices", nil, "Failure preparing request") - return - } - - resp, err := client.ListAutoApprovedPrivateLinkServicesSender(req) - if err != nil { - result.aaplsr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "ListAutoApprovedPrivateLinkServices", resp, "Failure sending request") - return - } - - result.aaplsr, err = client.ListAutoApprovedPrivateLinkServicesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "ListAutoApprovedPrivateLinkServices", resp, "Failure responding to request") - return - } - if result.aaplsr.hasNextLink() && result.aaplsr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAutoApprovedPrivateLinkServicesPreparer prepares the ListAutoApprovedPrivateLinkServices request. -func (client PrivateLinkServicesClient) ListAutoApprovedPrivateLinkServicesPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/autoApprovedPrivateLinkServices", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAutoApprovedPrivateLinkServicesSender sends the ListAutoApprovedPrivateLinkServices request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateLinkServicesClient) ListAutoApprovedPrivateLinkServicesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAutoApprovedPrivateLinkServicesResponder handles the response to the ListAutoApprovedPrivateLinkServices request. The method always -// closes the http.Response Body. -func (client PrivateLinkServicesClient) ListAutoApprovedPrivateLinkServicesResponder(resp *http.Response) (result AutoApprovedPrivateLinkServicesResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAutoApprovedPrivateLinkServicesNextResults retrieves the next set of results, if any. -func (client PrivateLinkServicesClient) listAutoApprovedPrivateLinkServicesNextResults(ctx context.Context, lastResults AutoApprovedPrivateLinkServicesResult) (result AutoApprovedPrivateLinkServicesResult, err error) { - req, err := lastResults.autoApprovedPrivateLinkServicesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listAutoApprovedPrivateLinkServicesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAutoApprovedPrivateLinkServicesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listAutoApprovedPrivateLinkServicesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAutoApprovedPrivateLinkServicesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listAutoApprovedPrivateLinkServicesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAutoApprovedPrivateLinkServicesComplete enumerates all values, automatically crossing page boundaries as required. -func (client PrivateLinkServicesClient) ListAutoApprovedPrivateLinkServicesComplete(ctx context.Context, location string) (result AutoApprovedPrivateLinkServicesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.ListAutoApprovedPrivateLinkServices") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAutoApprovedPrivateLinkServices(ctx, location) - return -} - -// ListAutoApprovedPrivateLinkServicesByResourceGroup returns all of the private link service ids that can be linked to -// a Private Endpoint with auto approved in this subscription in this region. -// Parameters: -// location - the location of the domain name. -// resourceGroupName - the name of the resource group. -func (client PrivateLinkServicesClient) ListAutoApprovedPrivateLinkServicesByResourceGroup(ctx context.Context, location string, resourceGroupName string) (result AutoApprovedPrivateLinkServicesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.ListAutoApprovedPrivateLinkServicesByResourceGroup") - defer func() { - sc := -1 - if result.aaplsr.Response.Response != nil { - sc = result.aaplsr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAutoApprovedPrivateLinkServicesByResourceGroupNextResults - req, err := client.ListAutoApprovedPrivateLinkServicesByResourceGroupPreparer(ctx, location, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "ListAutoApprovedPrivateLinkServicesByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListAutoApprovedPrivateLinkServicesByResourceGroupSender(req) - if err != nil { - result.aaplsr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "ListAutoApprovedPrivateLinkServicesByResourceGroup", resp, "Failure sending request") - return - } - - result.aaplsr, err = client.ListAutoApprovedPrivateLinkServicesByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "ListAutoApprovedPrivateLinkServicesByResourceGroup", resp, "Failure responding to request") - return - } - if result.aaplsr.hasNextLink() && result.aaplsr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAutoApprovedPrivateLinkServicesByResourceGroupPreparer prepares the ListAutoApprovedPrivateLinkServicesByResourceGroup request. -func (client PrivateLinkServicesClient) ListAutoApprovedPrivateLinkServicesByResourceGroupPreparer(ctx context.Context, location string, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/locations/{location}/autoApprovedPrivateLinkServices", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAutoApprovedPrivateLinkServicesByResourceGroupSender sends the ListAutoApprovedPrivateLinkServicesByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateLinkServicesClient) ListAutoApprovedPrivateLinkServicesByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAutoApprovedPrivateLinkServicesByResourceGroupResponder handles the response to the ListAutoApprovedPrivateLinkServicesByResourceGroup request. The method always -// closes the http.Response Body. -func (client PrivateLinkServicesClient) ListAutoApprovedPrivateLinkServicesByResourceGroupResponder(resp *http.Response) (result AutoApprovedPrivateLinkServicesResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAutoApprovedPrivateLinkServicesByResourceGroupNextResults retrieves the next set of results, if any. -func (client PrivateLinkServicesClient) listAutoApprovedPrivateLinkServicesByResourceGroupNextResults(ctx context.Context, lastResults AutoApprovedPrivateLinkServicesResult) (result AutoApprovedPrivateLinkServicesResult, err error) { - req, err := lastResults.autoApprovedPrivateLinkServicesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listAutoApprovedPrivateLinkServicesByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAutoApprovedPrivateLinkServicesByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listAutoApprovedPrivateLinkServicesByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAutoApprovedPrivateLinkServicesByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listAutoApprovedPrivateLinkServicesByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAutoApprovedPrivateLinkServicesByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client PrivateLinkServicesClient) ListAutoApprovedPrivateLinkServicesByResourceGroupComplete(ctx context.Context, location string, resourceGroupName string) (result AutoApprovedPrivateLinkServicesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.ListAutoApprovedPrivateLinkServicesByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAutoApprovedPrivateLinkServicesByResourceGroup(ctx, location, resourceGroupName) - return -} - -// ListBySubscription gets all private link service in a subscription. -func (client PrivateLinkServicesClient) ListBySubscription(ctx context.Context) (result PrivateLinkServiceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.ListBySubscription") - defer func() { - sc := -1 - if result.plslr.Response.Response != nil { - sc = result.plslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listBySubscriptionNextResults - req, err := client.ListBySubscriptionPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "ListBySubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.plslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "ListBySubscription", resp, "Failure sending request") - return - } - - result.plslr, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "ListBySubscription", resp, "Failure responding to request") - return - } - if result.plslr.hasNextLink() && result.plslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client PrivateLinkServicesClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/privateLinkServices", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBySubscriptionSender sends the ListBySubscription request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateLinkServicesClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always -// closes the http.Response Body. -func (client PrivateLinkServicesClient) ListBySubscriptionResponder(resp *http.Response) (result PrivateLinkServiceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listBySubscriptionNextResults retrieves the next set of results, if any. -func (client PrivateLinkServicesClient) listBySubscriptionNextResults(ctx context.Context, lastResults PrivateLinkServiceListResult) (result PrivateLinkServiceListResult, err error) { - req, err := lastResults.privateLinkServiceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client PrivateLinkServicesClient) ListBySubscriptionComplete(ctx context.Context) (result PrivateLinkServiceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.ListBySubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListBySubscription(ctx) - return -} - -// ListPrivateEndpointConnections gets all private end point connections for a specific private link service. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceName - the name of the private link service. -func (client PrivateLinkServicesClient) ListPrivateEndpointConnections(ctx context.Context, resourceGroupName string, serviceName string) (result PrivateEndpointConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.ListPrivateEndpointConnections") - defer func() { - sc := -1 - if result.peclr.Response.Response != nil { - sc = result.peclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listPrivateEndpointConnectionsNextResults - req, err := client.ListPrivateEndpointConnectionsPreparer(ctx, resourceGroupName, serviceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "ListPrivateEndpointConnections", nil, "Failure preparing request") - return - } - - resp, err := client.ListPrivateEndpointConnectionsSender(req) - if err != nil { - result.peclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "ListPrivateEndpointConnections", resp, "Failure sending request") - return - } - - result.peclr, err = client.ListPrivateEndpointConnectionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "ListPrivateEndpointConnections", resp, "Failure responding to request") - return - } - if result.peclr.hasNextLink() && result.peclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPrivateEndpointConnectionsPreparer prepares the ListPrivateEndpointConnections request. -func (client PrivateLinkServicesClient) ListPrivateEndpointConnectionsPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/privateLinkServices/{serviceName}/privateEndpointConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListPrivateEndpointConnectionsSender sends the ListPrivateEndpointConnections request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateLinkServicesClient) ListPrivateEndpointConnectionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListPrivateEndpointConnectionsResponder handles the response to the ListPrivateEndpointConnections request. The method always -// closes the http.Response Body. -func (client PrivateLinkServicesClient) ListPrivateEndpointConnectionsResponder(resp *http.Response) (result PrivateEndpointConnectionListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listPrivateEndpointConnectionsNextResults retrieves the next set of results, if any. -func (client PrivateLinkServicesClient) listPrivateEndpointConnectionsNextResults(ctx context.Context, lastResults PrivateEndpointConnectionListResult) (result PrivateEndpointConnectionListResult, err error) { - req, err := lastResults.privateEndpointConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listPrivateEndpointConnectionsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListPrivateEndpointConnectionsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listPrivateEndpointConnectionsNextResults", resp, "Failure sending next results request") - } - result, err = client.ListPrivateEndpointConnectionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "listPrivateEndpointConnectionsNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListPrivateEndpointConnectionsComplete enumerates all values, automatically crossing page boundaries as required. -func (client PrivateLinkServicesClient) ListPrivateEndpointConnectionsComplete(ctx context.Context, resourceGroupName string, serviceName string) (result PrivateEndpointConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.ListPrivateEndpointConnections") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListPrivateEndpointConnections(ctx, resourceGroupName, serviceName) - return -} - -// UpdatePrivateEndpointConnection approve or reject private end point connection for a private link service in a -// subscription. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceName - the name of the private link service. -// peConnectionName - the name of the private end point connection. -// parameters - parameters supplied to approve or reject the private end point connection. -func (client PrivateLinkServicesClient) UpdatePrivateEndpointConnection(ctx context.Context, resourceGroupName string, serviceName string, peConnectionName string, parameters PrivateEndpointConnection) (result PrivateEndpointConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkServicesClient.UpdatePrivateEndpointConnection") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdatePrivateEndpointConnectionPreparer(ctx, resourceGroupName, serviceName, peConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "UpdatePrivateEndpointConnection", nil, "Failure preparing request") - return - } - - resp, err := client.UpdatePrivateEndpointConnectionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "UpdatePrivateEndpointConnection", resp, "Failure sending request") - return - } - - result, err = client.UpdatePrivateEndpointConnectionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PrivateLinkServicesClient", "UpdatePrivateEndpointConnection", resp, "Failure responding to request") - return - } - - return -} - -// UpdatePrivateEndpointConnectionPreparer prepares the UpdatePrivateEndpointConnection request. -func (client PrivateLinkServicesClient) UpdatePrivateEndpointConnectionPreparer(ctx context.Context, resourceGroupName string, serviceName string, peConnectionName string, parameters PrivateEndpointConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "peConnectionName": autorest.Encode("path", peConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceName": autorest.Encode("path", serviceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Type = nil - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}/privateEndpointConnections/{peConnectionName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdatePrivateEndpointConnectionSender sends the UpdatePrivateEndpointConnection request. The method will close the -// http.Response Body if it receives an error. -func (client PrivateLinkServicesClient) UpdatePrivateEndpointConnectionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdatePrivateEndpointConnectionResponder handles the response to the UpdatePrivateEndpointConnection request. The method always -// closes the http.Response Body. -func (client PrivateLinkServicesClient) UpdatePrivateEndpointConnectionResponder(resp *http.Response) (result PrivateEndpointConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/profiles.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/profiles.go deleted file mode 100644 index 59e825dab1..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/profiles.go +++ /dev/null @@ -1,577 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ProfilesClient is the network Client -type ProfilesClient struct { - BaseClient -} - -// NewProfilesClient creates an instance of the ProfilesClient client. -func NewProfilesClient(subscriptionID string) ProfilesClient { - return NewProfilesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewProfilesClientWithBaseURI creates an instance of the ProfilesClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewProfilesClientWithBaseURI(baseURI string, subscriptionID string) ProfilesClient { - return ProfilesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a network profile. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkProfileName - the name of the network profile. -// parameters - parameters supplied to the create or update network profile operation. -func (client ProfilesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkProfileName string, parameters Profile) (result Profile, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkProfileName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "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.ProfilesClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ProfilesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkProfileName string, parameters Profile) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkProfileName": autorest.Encode("path", networkProfileName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ProfilesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ProfilesClient) CreateOrUpdateResponder(resp *http.Response) (result Profile, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified network profile. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkProfileName - the name of the NetworkProfile. -func (client ProfilesClient) Delete(ctx context.Context, resourceGroupName string, networkProfileName string) (result ProfilesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkProfileName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ProfilesClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkProfileName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkProfileName": autorest.Encode("path", networkProfileName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkProfiles/{networkProfileName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ProfilesClient) DeleteSender(req *http.Request) (future ProfilesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ProfilesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified network profile in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkProfileName - the name of the public IP prefix. -// expand - expands referenced resources. -func (client ProfilesClient) Get(ctx context.Context, resourceGroupName string, networkProfileName string, expand string) (result Profile, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkProfileName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "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.ProfilesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ProfilesClient) GetPreparer(ctx context.Context, resourceGroupName string, networkProfileName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkProfileName": autorest.Encode("path", networkProfileName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkProfiles/{networkProfileName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ProfilesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ProfilesClient) GetResponder(resp *http.Response) (result Profile, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all network profiles in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ProfilesClient) List(ctx context.Context, resourceGroupName string) (result ProfileListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.List") - defer func() { - sc := -1 - if result.plr.Response.Response != nil { - sc = result.plr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.plr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "List", resp, "Failure sending request") - return - } - - result.plr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "List", resp, "Failure responding to request") - return - } - if result.plr.hasNextLink() && result.plr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ProfilesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkProfiles", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ProfilesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ProfilesClient) ListResponder(resp *http.Response) (result ProfileListResult, err error) { - err = autorest.Respond( - resp, - 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 ProfilesClient) listNextResults(ctx context.Context, lastResults ProfileListResult) (result ProfileListResult, err error) { - req, err := lastResults.profileListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ProfilesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ProfilesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ProfilesClient) ListComplete(ctx context.Context, resourceGroupName string) (result ProfileListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the network profiles in a subscription. -func (client ProfilesClient) ListAll(ctx context.Context) (result ProfileListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.ListAll") - defer func() { - sc := -1 - if result.plr.Response.Response != nil { - sc = result.plr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.plr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "ListAll", resp, "Failure sending request") - return - } - - result.plr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.plr.hasNextLink() && result.plr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client ProfilesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkProfiles", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client ProfilesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client ProfilesClient) ListAllResponder(resp *http.Response) (result ProfileListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client ProfilesClient) listAllNextResults(ctx context.Context, lastResults ProfileListResult) (result ProfileListResult, err error) { - req, err := lastResults.profileListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ProfilesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ProfilesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client ProfilesClient) ListAllComplete(ctx context.Context) (result ProfileListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// UpdateTags updates network profile tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkProfileName - the name of the network profile. -// parameters - parameters supplied to update network profile tags. -func (client ProfilesClient) UpdateTags(ctx context.Context, resourceGroupName string, networkProfileName string, parameters TagsObject) (result Profile, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ProfilesClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, networkProfileName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ProfilesClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ProfilesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, networkProfileName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkProfileName": autorest.Encode("path", networkProfileName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ProfilesClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ProfilesClient) UpdateTagsResponder(resp *http.Response) (result Profile, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/publicipaddresses.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/publicipaddresses.go deleted file mode 100644 index 1e29520f86..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/publicipaddresses.go +++ /dev/null @@ -1,1337 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PublicIPAddressesClient is the network Client -type PublicIPAddressesClient struct { - BaseClient -} - -// NewPublicIPAddressesClient creates an instance of the PublicIPAddressesClient client. -func NewPublicIPAddressesClient(subscriptionID string) PublicIPAddressesClient { - return NewPublicIPAddressesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPublicIPAddressesClientWithBaseURI creates an instance of the PublicIPAddressesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewPublicIPAddressesClientWithBaseURI(baseURI string, subscriptionID string) PublicIPAddressesClient { - return PublicIPAddressesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a static or dynamic public IP address. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPAddressName - the name of the public IP address. -// parameters - parameters supplied to the create or update public IP address operation. -func (client PublicIPAddressesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress) (result PublicIPAddressesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, - }}, - {Target: "parameters.PublicIPAddressPropertiesFormat.ServicePublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - {Target: "parameters.PublicIPAddressPropertiesFormat.LinkedPublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.PublicIPAddressesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, publicIPAddressName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client PublicIPAddressesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpAddressName": autorest.Encode("path", publicIPAddressName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) CreateOrUpdateSender(req *http.Request) (future PublicIPAddressesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) CreateOrUpdateResponder(resp *http.Response) (result PublicIPAddress, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DdosProtectionStatus gets the Ddos Protection Status of a Public IP Address -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPAddressName - the name of the public IP address. -func (client PublicIPAddressesClient) DdosProtectionStatus(ctx context.Context, resourceGroupName string, publicIPAddressName string) (result PublicIPAddressesDdosProtectionStatusFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.DdosProtectionStatus") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DdosProtectionStatusPreparer(ctx, resourceGroupName, publicIPAddressName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "DdosProtectionStatus", nil, "Failure preparing request") - return - } - - result, err = client.DdosProtectionStatusSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "DdosProtectionStatus", result.Response(), "Failure sending request") - return - } - - return -} - -// DdosProtectionStatusPreparer prepares the DdosProtectionStatus request. -func (client PublicIPAddressesClient) DdosProtectionStatusPreparer(ctx context.Context, resourceGroupName string, publicIPAddressName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpAddressName": autorest.Encode("path", publicIPAddressName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/publicIPAddresses/{publicIpAddressName}/ddosProtectionStatus", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DdosProtectionStatusSender sends the DdosProtectionStatus request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) DdosProtectionStatusSender(req *http.Request) (future PublicIPAddressesDdosProtectionStatusFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DdosProtectionStatusResponder handles the response to the DdosProtectionStatus request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) DdosProtectionStatusResponder(resp *http.Response) (result PublicIPDdosProtectionStatusResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified public IP address. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPAddressName - the name of the public IP address. -func (client PublicIPAddressesClient) Delete(ctx context.Context, resourceGroupName string, publicIPAddressName string) (result PublicIPAddressesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, publicIPAddressName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client PublicIPAddressesClient) DeletePreparer(ctx context.Context, resourceGroupName string, publicIPAddressName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpAddressName": autorest.Encode("path", publicIPAddressName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/publicIPAddresses/{publicIpAddressName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) DeleteSender(req *http.Request) (future PublicIPAddressesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified public IP address in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPAddressName - the name of the public IP address. -// expand - expands referenced resources. -func (client PublicIPAddressesClient) Get(ctx context.Context, resourceGroupName string, publicIPAddressName string, expand string) (result PublicIPAddress, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, publicIPAddressName, expand) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PublicIPAddressesClient) GetPreparer(ctx context.Context, resourceGroupName string, publicIPAddressName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpAddressName": autorest.Encode("path", publicIPAddressName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/publicIPAddresses/{publicIpAddressName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) GetResponder(resp *http.Response) (result PublicIPAddress, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetCloudServicePublicIPAddress get the specified public IP address in a cloud service. -// Parameters: -// resourceGroupName - the name of the resource group. -// cloudServiceName - the name of the cloud service. -// roleInstanceName - the role instance name. -// networkInterfaceName - the name of the network interface. -// IPConfigurationName - the name of the IP configuration. -// publicIPAddressName - the name of the public IP Address. -// expand - expands referenced resources. -func (client PublicIPAddressesClient) GetCloudServicePublicIPAddress(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string, expand string) (result PublicIPAddress, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.GetCloudServicePublicIPAddress") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetCloudServicePublicIPAddressPreparer(ctx, resourceGroupName, cloudServiceName, roleInstanceName, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "GetCloudServicePublicIPAddress", nil, "Failure preparing request") - return - } - - resp, err := client.GetCloudServicePublicIPAddressSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "GetCloudServicePublicIPAddress", resp, "Failure sending request") - return - } - - result, err = client.GetCloudServicePublicIPAddressResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "GetCloudServicePublicIPAddress", resp, "Failure responding to request") - return - } - - return -} - -// GetCloudServicePublicIPAddressPreparer prepares the GetCloudServicePublicIPAddress request. -func (client PublicIPAddressesClient) GetCloudServicePublicIPAddressPreparer(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "cloudServiceName": autorest.Encode("path", cloudServiceName), - "ipConfigurationName": autorest.Encode("path", IPConfigurationName), - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "publicIpAddressName": autorest.Encode("path", publicIPAddressName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "roleInstanceName": autorest.Encode("path", roleInstanceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses/{publicIpAddressName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetCloudServicePublicIPAddressSender sends the GetCloudServicePublicIPAddress request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) GetCloudServicePublicIPAddressSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetCloudServicePublicIPAddressResponder handles the response to the GetCloudServicePublicIPAddress request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) GetCloudServicePublicIPAddressResponder(resp *http.Response) (result PublicIPAddress, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetVirtualMachineScaleSetPublicIPAddress get the specified public IP address in a virtual machine scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -// virtualmachineIndex - the virtual machine index. -// networkInterfaceName - the name of the network interface. -// IPConfigurationName - the name of the IP configuration. -// publicIPAddressName - the name of the public IP Address. -// expand - expands referenced resources. -func (client PublicIPAddressesClient) GetVirtualMachineScaleSetPublicIPAddress(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string, expand string) (result PublicIPAddress, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.GetVirtualMachineScaleSetPublicIPAddress") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetVirtualMachineScaleSetPublicIPAddressPreparer(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "GetVirtualMachineScaleSetPublicIPAddress", nil, "Failure preparing request") - return - } - - resp, err := client.GetVirtualMachineScaleSetPublicIPAddressSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "GetVirtualMachineScaleSetPublicIPAddress", resp, "Failure sending request") - return - } - - result, err = client.GetVirtualMachineScaleSetPublicIPAddressResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "GetVirtualMachineScaleSetPublicIPAddress", resp, "Failure responding to request") - return - } - - return -} - -// GetVirtualMachineScaleSetPublicIPAddressPreparer prepares the GetVirtualMachineScaleSetPublicIPAddress request. -func (client PublicIPAddressesClient) GetVirtualMachineScaleSetPublicIPAddressPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipConfigurationName": autorest.Encode("path", IPConfigurationName), - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "publicIpAddressName": autorest.Encode("path", publicIPAddressName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2018-10-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.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses/{publicIpAddressName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetVirtualMachineScaleSetPublicIPAddressSender sends the GetVirtualMachineScaleSetPublicIPAddress request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) GetVirtualMachineScaleSetPublicIPAddressSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetVirtualMachineScaleSetPublicIPAddressResponder handles the response to the GetVirtualMachineScaleSetPublicIPAddress request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) GetVirtualMachineScaleSetPublicIPAddressResponder(resp *http.Response) (result PublicIPAddress, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all public IP addresses in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client PublicIPAddressesClient) List(ctx context.Context, resourceGroupName string) (result PublicIPAddressListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.List") - defer func() { - sc := -1 - if result.pialr.Response.Response != nil { - sc = result.pialr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.pialr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure sending request") - return - } - - result.pialr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure responding to request") - return - } - if result.pialr.hasNextLink() && result.pialr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PublicIPAddressesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/publicIPAddresses", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) ListResponder(resp *http.Response) (result PublicIPAddressListResult, err error) { - err = autorest.Respond( - resp, - 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 PublicIPAddressesClient) listNextResults(ctx context.Context, lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { - req, err := lastResults.publicIPAddressListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPAddressesClient) ListComplete(ctx context.Context, resourceGroupName string) (result PublicIPAddressListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the public IP addresses in a subscription. -func (client PublicIPAddressesClient) ListAll(ctx context.Context) (result PublicIPAddressListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListAll") - defer func() { - sc := -1 - if result.pialr.Response.Response != nil { - sc = result.pialr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.pialr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure sending request") - return - } - - result.pialr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.pialr.hasNextLink() && result.pialr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client PublicIPAddressesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPAddresses", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) ListAllResponder(resp *http.Response) (result PublicIPAddressListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client PublicIPAddressesClient) listAllNextResults(ctx context.Context, lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { - req, err := lastResults.publicIPAddressListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPAddressesClient) ListAllComplete(ctx context.Context) (result PublicIPAddressListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListCloudServicePublicIPAddresses gets information about all public IP addresses on a cloud service level. -// Parameters: -// resourceGroupName - the name of the resource group. -// cloudServiceName - the name of the cloud service. -func (client PublicIPAddressesClient) ListCloudServicePublicIPAddresses(ctx context.Context, resourceGroupName string, cloudServiceName string) (result PublicIPAddressListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListCloudServicePublicIPAddresses") - defer func() { - sc := -1 - if result.pialr.Response.Response != nil { - sc = result.pialr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listCloudServicePublicIPAddressesNextResults - req, err := client.ListCloudServicePublicIPAddressesPreparer(ctx, resourceGroupName, cloudServiceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListCloudServicePublicIPAddresses", nil, "Failure preparing request") - return - } - - resp, err := client.ListCloudServicePublicIPAddressesSender(req) - if err != nil { - result.pialr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListCloudServicePublicIPAddresses", resp, "Failure sending request") - return - } - - result.pialr, err = client.ListCloudServicePublicIPAddressesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListCloudServicePublicIPAddresses", resp, "Failure responding to request") - return - } - if result.pialr.hasNextLink() && result.pialr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListCloudServicePublicIPAddressesPreparer prepares the ListCloudServicePublicIPAddresses request. -func (client PublicIPAddressesClient) ListCloudServicePublicIPAddressesPreparer(ctx context.Context, resourceGroupName string, cloudServiceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "cloudServiceName": autorest.Encode("path", cloudServiceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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.Compute/cloudServices/{cloudServiceName}/publicipaddresses", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListCloudServicePublicIPAddressesSender sends the ListCloudServicePublicIPAddresses request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) ListCloudServicePublicIPAddressesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListCloudServicePublicIPAddressesResponder handles the response to the ListCloudServicePublicIPAddresses request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) ListCloudServicePublicIPAddressesResponder(resp *http.Response) (result PublicIPAddressListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listCloudServicePublicIPAddressesNextResults retrieves the next set of results, if any. -func (client PublicIPAddressesClient) listCloudServicePublicIPAddressesNextResults(ctx context.Context, lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { - req, err := lastResults.publicIPAddressListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listCloudServicePublicIPAddressesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListCloudServicePublicIPAddressesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listCloudServicePublicIPAddressesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListCloudServicePublicIPAddressesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listCloudServicePublicIPAddressesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListCloudServicePublicIPAddressesComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPAddressesClient) ListCloudServicePublicIPAddressesComplete(ctx context.Context, resourceGroupName string, cloudServiceName string) (result PublicIPAddressListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListCloudServicePublicIPAddresses") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListCloudServicePublicIPAddresses(ctx, resourceGroupName, cloudServiceName) - return -} - -// ListCloudServiceRoleInstancePublicIPAddresses gets information about all public IP addresses in a role instance IP -// configuration in a cloud service. -// Parameters: -// resourceGroupName - the name of the resource group. -// cloudServiceName - the name of the cloud service. -// roleInstanceName - the name of role instance. -// networkInterfaceName - the network interface name. -// IPConfigurationName - the IP configuration name. -func (client PublicIPAddressesClient) ListCloudServiceRoleInstancePublicIPAddresses(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string, networkInterfaceName string, IPConfigurationName string) (result PublicIPAddressListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListCloudServiceRoleInstancePublicIPAddresses") - defer func() { - sc := -1 - if result.pialr.Response.Response != nil { - sc = result.pialr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listCloudServiceRoleInstancePublicIPAddressesNextResults - req, err := client.ListCloudServiceRoleInstancePublicIPAddressesPreparer(ctx, resourceGroupName, cloudServiceName, roleInstanceName, networkInterfaceName, IPConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListCloudServiceRoleInstancePublicIPAddresses", nil, "Failure preparing request") - return - } - - resp, err := client.ListCloudServiceRoleInstancePublicIPAddressesSender(req) - if err != nil { - result.pialr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListCloudServiceRoleInstancePublicIPAddresses", resp, "Failure sending request") - return - } - - result.pialr, err = client.ListCloudServiceRoleInstancePublicIPAddressesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListCloudServiceRoleInstancePublicIPAddresses", resp, "Failure responding to request") - return - } - if result.pialr.hasNextLink() && result.pialr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListCloudServiceRoleInstancePublicIPAddressesPreparer prepares the ListCloudServiceRoleInstancePublicIPAddresses request. -func (client PublicIPAddressesClient) ListCloudServiceRoleInstancePublicIPAddressesPreparer(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string, networkInterfaceName string, IPConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "cloudServiceName": autorest.Encode("path", cloudServiceName), - "ipConfigurationName": autorest.Encode("path", IPConfigurationName), - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "roleInstanceName": autorest.Encode("path", roleInstanceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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.Compute/cloudServices/{cloudServiceName}/roleInstances/{roleInstanceName}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListCloudServiceRoleInstancePublicIPAddressesSender sends the ListCloudServiceRoleInstancePublicIPAddresses request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) ListCloudServiceRoleInstancePublicIPAddressesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListCloudServiceRoleInstancePublicIPAddressesResponder handles the response to the ListCloudServiceRoleInstancePublicIPAddresses request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) ListCloudServiceRoleInstancePublicIPAddressesResponder(resp *http.Response) (result PublicIPAddressListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listCloudServiceRoleInstancePublicIPAddressesNextResults retrieves the next set of results, if any. -func (client PublicIPAddressesClient) listCloudServiceRoleInstancePublicIPAddressesNextResults(ctx context.Context, lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { - req, err := lastResults.publicIPAddressListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listCloudServiceRoleInstancePublicIPAddressesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListCloudServiceRoleInstancePublicIPAddressesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listCloudServiceRoleInstancePublicIPAddressesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListCloudServiceRoleInstancePublicIPAddressesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listCloudServiceRoleInstancePublicIPAddressesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListCloudServiceRoleInstancePublicIPAddressesComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPAddressesClient) ListCloudServiceRoleInstancePublicIPAddressesComplete(ctx context.Context, resourceGroupName string, cloudServiceName string, roleInstanceName string, networkInterfaceName string, IPConfigurationName string) (result PublicIPAddressListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListCloudServiceRoleInstancePublicIPAddresses") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListCloudServiceRoleInstancePublicIPAddresses(ctx, resourceGroupName, cloudServiceName, roleInstanceName, networkInterfaceName, IPConfigurationName) - return -} - -// ListVirtualMachineScaleSetPublicIPAddresses gets information about all public IP addresses on a virtual machine -// scale set level. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetPublicIPAddresses(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) (result PublicIPAddressListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListVirtualMachineScaleSetPublicIPAddresses") - defer func() { - sc := -1 - if result.pialr.Response.Response != nil { - sc = result.pialr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listVirtualMachineScaleSetPublicIPAddressesNextResults - req, err := client.ListVirtualMachineScaleSetPublicIPAddressesPreparer(ctx, resourceGroupName, virtualMachineScaleSetName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListVirtualMachineScaleSetPublicIPAddresses", nil, "Failure preparing request") - return - } - - resp, err := client.ListVirtualMachineScaleSetPublicIPAddressesSender(req) - if err != nil { - result.pialr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListVirtualMachineScaleSetPublicIPAddresses", resp, "Failure sending request") - return - } - - result.pialr, err = client.ListVirtualMachineScaleSetPublicIPAddressesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListVirtualMachineScaleSetPublicIPAddresses", resp, "Failure responding to request") - return - } - if result.pialr.hasNextLink() && result.pialr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListVirtualMachineScaleSetPublicIPAddressesPreparer prepares the ListVirtualMachineScaleSetPublicIPAddresses request. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetPublicIPAddressesPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2018-10-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.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/publicipaddresses", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListVirtualMachineScaleSetPublicIPAddressesSender sends the ListVirtualMachineScaleSetPublicIPAddresses request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetPublicIPAddressesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListVirtualMachineScaleSetPublicIPAddressesResponder handles the response to the ListVirtualMachineScaleSetPublicIPAddresses request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetPublicIPAddressesResponder(resp *http.Response) (result PublicIPAddressListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listVirtualMachineScaleSetPublicIPAddressesNextResults retrieves the next set of results, if any. -func (client PublicIPAddressesClient) listVirtualMachineScaleSetPublicIPAddressesNextResults(ctx context.Context, lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { - req, err := lastResults.publicIPAddressListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listVirtualMachineScaleSetPublicIPAddressesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListVirtualMachineScaleSetPublicIPAddressesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listVirtualMachineScaleSetPublicIPAddressesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListVirtualMachineScaleSetPublicIPAddressesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listVirtualMachineScaleSetPublicIPAddressesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListVirtualMachineScaleSetPublicIPAddressesComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetPublicIPAddressesComplete(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string) (result PublicIPAddressListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListVirtualMachineScaleSetPublicIPAddresses") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListVirtualMachineScaleSetPublicIPAddresses(ctx, resourceGroupName, virtualMachineScaleSetName) - return -} - -// ListVirtualMachineScaleSetVMPublicIPAddresses gets information about all public IP addresses in a virtual machine IP -// configuration in a virtual machine scale set. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualMachineScaleSetName - the name of the virtual machine scale set. -// virtualmachineIndex - the virtual machine index. -// networkInterfaceName - the network interface name. -// IPConfigurationName - the IP configuration name. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetVMPublicIPAddresses(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string) (result PublicIPAddressListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListVirtualMachineScaleSetVMPublicIPAddresses") - defer func() { - sc := -1 - if result.pialr.Response.Response != nil { - sc = result.pialr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listVirtualMachineScaleSetVMPublicIPAddressesNextResults - req, err := client.ListVirtualMachineScaleSetVMPublicIPAddressesPreparer(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListVirtualMachineScaleSetVMPublicIPAddresses", nil, "Failure preparing request") - return - } - - resp, err := client.ListVirtualMachineScaleSetVMPublicIPAddressesSender(req) - if err != nil { - result.pialr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListVirtualMachineScaleSetVMPublicIPAddresses", resp, "Failure sending request") - return - } - - result.pialr, err = client.ListVirtualMachineScaleSetVMPublicIPAddressesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListVirtualMachineScaleSetVMPublicIPAddresses", resp, "Failure responding to request") - return - } - if result.pialr.hasNextLink() && result.pialr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListVirtualMachineScaleSetVMPublicIPAddressesPreparer prepares the ListVirtualMachineScaleSetVMPublicIPAddresses request. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetVMPublicIPAddressesPreparer(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipConfigurationName": autorest.Encode("path", IPConfigurationName), - "networkInterfaceName": autorest.Encode("path", networkInterfaceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), - "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), - } - - const APIVersion = "2018-10-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.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListVirtualMachineScaleSetVMPublicIPAddressesSender sends the ListVirtualMachineScaleSetVMPublicIPAddresses request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetVMPublicIPAddressesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListVirtualMachineScaleSetVMPublicIPAddressesResponder handles the response to the ListVirtualMachineScaleSetVMPublicIPAddresses request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetVMPublicIPAddressesResponder(resp *http.Response) (result PublicIPAddressListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listVirtualMachineScaleSetVMPublicIPAddressesNextResults retrieves the next set of results, if any. -func (client PublicIPAddressesClient) listVirtualMachineScaleSetVMPublicIPAddressesNextResults(ctx context.Context, lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { - req, err := lastResults.publicIPAddressListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listVirtualMachineScaleSetVMPublicIPAddressesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListVirtualMachineScaleSetVMPublicIPAddressesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listVirtualMachineScaleSetVMPublicIPAddressesNextResults", resp, "Failure sending next results request") - } - result, err = client.ListVirtualMachineScaleSetVMPublicIPAddressesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listVirtualMachineScaleSetVMPublicIPAddressesNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListVirtualMachineScaleSetVMPublicIPAddressesComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPAddressesClient) ListVirtualMachineScaleSetVMPublicIPAddressesComplete(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string) (result PublicIPAddressListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.ListVirtualMachineScaleSetVMPublicIPAddresses") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListVirtualMachineScaleSetVMPublicIPAddresses(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName) - return -} - -// UpdateTags updates public IP address tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPAddressName - the name of the public IP address. -// parameters - parameters supplied to update public IP address tags. -func (client PublicIPAddressesClient) UpdateTags(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters TagsObject) (result PublicIPAddress, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPAddressesClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, publicIPAddressName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client PublicIPAddressesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpAddressName": autorest.Encode("path", publicIPAddressName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPAddressesClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client PublicIPAddressesClient) UpdateTagsResponder(resp *http.Response) (result PublicIPAddress, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/publicipprefixes.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/publicipprefixes.go deleted file mode 100644 index 4b076abe55..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/publicipprefixes.go +++ /dev/null @@ -1,581 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// PublicIPPrefixesClient is the network Client -type PublicIPPrefixesClient struct { - BaseClient -} - -// NewPublicIPPrefixesClient creates an instance of the PublicIPPrefixesClient client. -func NewPublicIPPrefixesClient(subscriptionID string) PublicIPPrefixesClient { - return NewPublicIPPrefixesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewPublicIPPrefixesClientWithBaseURI creates an instance of the PublicIPPrefixesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewPublicIPPrefixesClientWithBaseURI(baseURI string, subscriptionID string) PublicIPPrefixesClient { - return PublicIPPrefixesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a static or dynamic public IP prefix. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPPrefixName - the name of the public IP prefix. -// parameters - parameters supplied to the create or update public IP prefix operation. -func (client PublicIPPrefixesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, publicIPPrefixName string, parameters PublicIPPrefix) (result PublicIPPrefixesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, publicIPPrefixName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client PublicIPPrefixesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, publicIPPrefixName string, parameters PublicIPPrefix) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpPrefixName": autorest.Encode("path", publicIPPrefixName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPPrefixesClient) CreateOrUpdateSender(req *http.Request) (future PublicIPPrefixesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client PublicIPPrefixesClient) CreateOrUpdateResponder(resp *http.Response) (result PublicIPPrefix, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified public IP prefix. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPPrefixName - the name of the PublicIpPrefix. -func (client PublicIPPrefixesClient) Delete(ctx context.Context, resourceGroupName string, publicIPPrefixName string) (result PublicIPPrefixesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, publicIPPrefixName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client PublicIPPrefixesClient) DeletePreparer(ctx context.Context, resourceGroupName string, publicIPPrefixName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpPrefixName": autorest.Encode("path", publicIPPrefixName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/publicIPPrefixes/{publicIpPrefixName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPPrefixesClient) DeleteSender(req *http.Request) (future PublicIPPrefixesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client PublicIPPrefixesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified public IP prefix in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPPrefixName - the name of the public IP prefix. -// expand - expands referenced resources. -func (client PublicIPPrefixesClient) Get(ctx context.Context, resourceGroupName string, publicIPPrefixName string, expand string) (result PublicIPPrefix, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, publicIPPrefixName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "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.PublicIPPrefixesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client PublicIPPrefixesClient) GetPreparer(ctx context.Context, resourceGroupName string, publicIPPrefixName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpPrefixName": autorest.Encode("path", publicIPPrefixName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/publicIPPrefixes/{publicIpPrefixName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPPrefixesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client PublicIPPrefixesClient) GetResponder(resp *http.Response) (result PublicIPPrefix, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all public IP prefixes in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client PublicIPPrefixesClient) List(ctx context.Context, resourceGroupName string) (result PublicIPPrefixListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.List") - defer func() { - sc := -1 - if result.piplr.Response.Response != nil { - sc = result.piplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.piplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "List", resp, "Failure sending request") - return - } - - result.piplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "List", resp, "Failure responding to request") - return - } - if result.piplr.hasNextLink() && result.piplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client PublicIPPrefixesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/publicIPPrefixes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPPrefixesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client PublicIPPrefixesClient) ListResponder(resp *http.Response) (result PublicIPPrefixListResult, err error) { - err = autorest.Respond( - resp, - 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 PublicIPPrefixesClient) listNextResults(ctx context.Context, lastResults PublicIPPrefixListResult) (result PublicIPPrefixListResult, err error) { - req, err := lastResults.publicIPPrefixListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPPrefixesClient) ListComplete(ctx context.Context, resourceGroupName string) (result PublicIPPrefixListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the public IP prefixes in a subscription. -func (client PublicIPPrefixesClient) ListAll(ctx context.Context) (result PublicIPPrefixListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.ListAll") - defer func() { - sc := -1 - if result.piplr.Response.Response != nil { - sc = result.piplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.piplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "ListAll", resp, "Failure sending request") - return - } - - result.piplr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.piplr.hasNextLink() && result.piplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client PublicIPPrefixesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPPrefixes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPPrefixesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client PublicIPPrefixesClient) ListAllResponder(resp *http.Response) (result PublicIPPrefixListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client PublicIPPrefixesClient) listAllNextResults(ctx context.Context, lastResults PublicIPPrefixListResult) (result PublicIPPrefixListResult, err error) { - req, err := lastResults.publicIPPrefixListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client PublicIPPrefixesClient) ListAllComplete(ctx context.Context) (result PublicIPPrefixListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// UpdateTags updates public IP prefix tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// publicIPPrefixName - the name of the public IP prefix. -// parameters - parameters supplied to update public IP prefix tags. -func (client PublicIPPrefixesClient) UpdateTags(ctx context.Context, resourceGroupName string, publicIPPrefixName string, parameters TagsObject) (result PublicIPPrefix, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/PublicIPPrefixesClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, publicIPPrefixName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPPrefixesClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client PublicIPPrefixesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, publicIPPrefixName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "publicIpPrefixName": autorest.Encode("path", publicIPPrefixName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client PublicIPPrefixesClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client PublicIPPrefixesClient) UpdateTagsResponder(resp *http.Response) (result PublicIPPrefix, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/resourcenavigationlinks.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/resourcenavigationlinks.go deleted file mode 100644 index 0ac79d4c49..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/resourcenavigationlinks.go +++ /dev/null @@ -1,110 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ResourceNavigationLinksClient is the network Client -type ResourceNavigationLinksClient struct { - BaseClient -} - -// NewResourceNavigationLinksClient creates an instance of the ResourceNavigationLinksClient client. -func NewResourceNavigationLinksClient(subscriptionID string) ResourceNavigationLinksClient { - return NewResourceNavigationLinksClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewResourceNavigationLinksClientWithBaseURI creates an instance of the ResourceNavigationLinksClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewResourceNavigationLinksClientWithBaseURI(baseURI string, subscriptionID string) ResourceNavigationLinksClient { - return ResourceNavigationLinksClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets a list of resource navigation links for a subnet. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// subnetName - the name of the subnet. -func (client ResourceNavigationLinksClient) List(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) (result ResourceNavigationLinksListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ResourceNavigationLinksClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, virtualNetworkName, subnetName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ResourceNavigationLinksClient", "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.ResourceNavigationLinksClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ResourceNavigationLinksClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ResourceNavigationLinksClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subnetName": autorest.Encode("path", subnetName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2022-07-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/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/ResourceNavigationLinks", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ResourceNavigationLinksClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ResourceNavigationLinksClient) ListResponder(resp *http.Response) (result ResourceNavigationLinksListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routefilterrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routefilterrules.go deleted file mode 100644 index 179b1a7cb2..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routefilterrules.go +++ /dev/null @@ -1,403 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RouteFilterRulesClient is the network Client -type RouteFilterRulesClient struct { - BaseClient -} - -// 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 using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewRouteFilterRulesClientWithBaseURI(baseURI string, subscriptionID string) RouteFilterRulesClient { - return RouteFilterRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a route in the specified route filter. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -// ruleName - the name of the route filter rule. -// routeFilterRuleParameters - parameters supplied to the create or update route filter rule operation. -func (client RouteFilterRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters RouteFilterRule) (result RouteFilterRulesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 { - return result, validation.NewError("network.RouteFilterRulesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RouteFilterRulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters RouteFilterRule) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - routeFilterRuleParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - 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{}).WithContext(ctx)) -} - -// 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) (future RouteFilterRulesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -// ruleName - the name of the rule. -func (client RouteFilterRulesClient) Delete(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string) (result RouteFilterRulesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, routeFilterName, ruleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RouteFilterRulesClient) DeletePreparer(ctx context.Context, 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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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) (future RouteFilterRulesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified rule from a route filter. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -// ruleName - the name of the rule. -func (client RouteFilterRulesClient) Get(ctx context.Context, resourceGroupName string, routeFilterName string, ruleName string) (result RouteFilterRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, 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 - } - - return -} - -// GetPreparer prepares the Get request. -func (client RouteFilterRulesClient) GetPreparer(ctx context.Context, 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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByRouteFilter gets all RouteFilterRules in a route filter. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -func (client RouteFilterRulesClient) ListByRouteFilter(ctx context.Context, resourceGroupName string, routeFilterName string) (result RouteFilterRuleListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.ListByRouteFilter") - defer func() { - sc := -1 - if result.rfrlr.Response.Response != nil { - sc = result.rfrlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByRouteFilterNextResults - req, err := client.ListByRouteFilterPreparer(ctx, 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.rfrlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", resp, "Failure sending request") - return - } - - result.rfrlr, err = client.ListByRouteFilterResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", resp, "Failure responding to request") - return - } - if result.rfrlr.hasNextLink() && result.rfrlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByRouteFilterPreparer prepares the ListByRouteFilter request. -func (client RouteFilterRulesClient) ListByRouteFilterPreparer(ctx context.Context, 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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - 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(ctx context.Context, lastResults RouteFilterRuleListResult) (result RouteFilterRuleListResult, err error) { - req, err := lastResults.routeFilterRuleListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "listByRouteFilterNextResults", 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", "listByRouteFilterNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByRouteFilterResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "listByRouteFilterNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByRouteFilterComplete enumerates all values, automatically crossing page boundaries as required. -func (client RouteFilterRulesClient) ListByRouteFilterComplete(ctx context.Context, resourceGroupName string, routeFilterName string) (result RouteFilterRuleListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFilterRulesClient.ListByRouteFilter") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByRouteFilter(ctx, resourceGroupName, routeFilterName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routefilters.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routefilters.go deleted file mode 100644 index 2f6a25f21b..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routefilters.go +++ /dev/null @@ -1,580 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RouteFiltersClient is the network Client -type RouteFiltersClient struct { - BaseClient -} - -// 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 using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewRouteFiltersClientWithBaseURI(baseURI string, subscriptionID string) RouteFiltersClient { - return RouteFiltersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a route filter in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -// routeFilterParameters - parameters supplied to the create or update route filter operation. -func (client RouteFiltersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, routeFilterName string, routeFilterParameters RouteFilter) (result RouteFiltersCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, routeFilterName, routeFilterParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RouteFiltersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, routeFilterName string, routeFilterParameters RouteFilter) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - routeFilterParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - 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{}).WithContext(ctx)) -} - -// 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) (future RouteFiltersCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified route filter. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -func (client RouteFiltersClient) Delete(ctx context.Context, resourceGroupName string, routeFilterName string) (result RouteFiltersDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, routeFilterName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RouteFiltersClient) DeletePreparer(ctx context.Context, 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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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) (future RouteFiltersDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified route filter. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -// expand - expands referenced express route bgp peering resources. -func (client RouteFiltersClient) Get(ctx context.Context, resourceGroupName string, routeFilterName string, expand string) (result RouteFilter, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, 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 - } - - return -} - -// GetPreparer prepares the Get request. -func (client RouteFiltersClient) GetPreparer(ctx context.Context, 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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - 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(ctx context.Context) (result RouteFilterListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.List") - defer func() { - sc := -1 - if result.rflr.Response.Response != nil { - sc = result.rflr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.rflr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "List", resp, "Failure sending request") - return - } - - result.rflr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "List", resp, "Failure responding to request") - return - } - if result.rflr.hasNextLink() && result.rflr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client RouteFiltersClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - 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(ctx context.Context, lastResults RouteFilterListResult) (result RouteFilterListResult, err error) { - req, err := lastResults.routeFilterListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RouteFiltersClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RouteFiltersClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RouteFiltersClient) ListComplete(ctx context.Context) (result RouteFilterListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup gets all route filters in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client RouteFiltersClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result RouteFilterListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.rflr.Response.Response != nil { - sc = result.rflr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, 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.rflr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.rflr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.rflr.hasNextLink() && result.rflr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client RouteFiltersClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - 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(ctx context.Context, lastResults RouteFilterListResult) (result RouteFilterListResult, err error) { - req, err := lastResults.routeFilterListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RouteFiltersClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RouteFiltersClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client RouteFiltersClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result RouteFilterListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates tags of a route filter. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeFilterName - the name of the route filter. -// parameters - parameters supplied to update route filter tags. -func (client RouteFiltersClient) UpdateTags(ctx context.Context, resourceGroupName string, routeFilterName string, parameters TagsObject) (result RouteFilter, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteFiltersClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, routeFilterName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client RouteFiltersClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, routeFilterName string, parameters TagsObject) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client RouteFiltersClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client RouteFiltersClient) UpdateTagsResponder(resp *http.Response) (result RouteFilter, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routemaps.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routemaps.go deleted file mode 100644 index 1f31d11014..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routemaps.go +++ /dev/null @@ -1,394 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RouteMapsClient is the network Client -type RouteMapsClient struct { - BaseClient -} - -// NewRouteMapsClient creates an instance of the RouteMapsClient client. -func NewRouteMapsClient(subscriptionID string) RouteMapsClient { - return NewRouteMapsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRouteMapsClientWithBaseURI creates an instance of the RouteMapsClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewRouteMapsClientWithBaseURI(baseURI string, subscriptionID string) RouteMapsClient { - return RouteMapsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a RouteMap if it doesn't exist else updates the existing one. -// Parameters: -// resourceGroupName - the resource group name of the RouteMap's resource group. -// virtualHubName - the name of the VirtualHub containing the RouteMap. -// routeMapName - the name of the RouteMap. -// routeMapParameters - parameters supplied to create or update a RouteMap. -func (client RouteMapsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string, routeMapParameters RouteMap) (result RouteMapsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteMapsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualHubName, routeMapName, routeMapParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteMapsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteMapsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RouteMapsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string, routeMapParameters RouteMap) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeMapName": autorest.Encode("path", routeMapName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - routeMapParameters.Name = nil - routeMapParameters.Etag = nil - routeMapParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeMaps/{routeMapName}", pathParameters), - autorest.WithJSON(routeMapParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client RouteMapsClient) CreateOrUpdateSender(req *http.Request) (future RouteMapsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RouteMapsClient) CreateOrUpdateResponder(resp *http.Response) (result RouteMap, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a RouteMap. -// Parameters: -// resourceGroupName - the resource group name of the RouteMap's resource group. -// virtualHubName - the name of the VirtualHub containing the RouteMap. -// routeMapName - the name of the RouteMap. -func (client RouteMapsClient) Delete(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string) (result RouteMapsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteMapsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualHubName, routeMapName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteMapsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteMapsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RouteMapsClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeMapName": autorest.Encode("path", routeMapName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/routeMaps/{routeMapName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RouteMapsClient) DeleteSender(req *http.Request) (future RouteMapsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RouteMapsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a RouteMap. -// Parameters: -// resourceGroupName - the resource group name of the RouteMap's resource group. -// virtualHubName - the name of the VirtualHub containing the RouteMap. -// routeMapName - the name of the RouteMap. -func (client RouteMapsClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string) (result RouteMap, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteMapsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualHubName, routeMapName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteMapsClient", "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.RouteMapsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteMapsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client RouteMapsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, routeMapName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeMapName": autorest.Encode("path", routeMapName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/routeMaps/{routeMapName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RouteMapsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RouteMapsClient) GetResponder(resp *http.Response) (result RouteMap, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List retrieves the details of all RouteMaps. -// Parameters: -// resourceGroupName - the resource group name of the RouteMap's resource group'. -// virtualHubName - the name of the VirtualHub containing the RouteMap. -func (client RouteMapsClient) List(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListRouteMapsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteMapsClient.List") - defer func() { - sc := -1 - if result.lrmr.Response.Response != nil { - sc = result.lrmr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualHubName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteMapsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lrmr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteMapsClient", "List", resp, "Failure sending request") - return - } - - result.lrmr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteMapsClient", "List", resp, "Failure responding to request") - return - } - if result.lrmr.hasNextLink() && result.lrmr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client RouteMapsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/routeMaps", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client RouteMapsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client RouteMapsClient) ListResponder(resp *http.Response) (result ListRouteMapsResult, err error) { - err = autorest.Respond( - resp, - 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 RouteMapsClient) listNextResults(ctx context.Context, lastResults ListRouteMapsResult) (result ListRouteMapsResult, err error) { - req, err := lastResults.listRouteMapsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RouteMapsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RouteMapsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteMapsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RouteMapsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListRouteMapsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteMapsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualHubName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routes.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routes.go deleted file mode 100644 index fc2be63bfe..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routes.go +++ /dev/null @@ -1,392 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RoutesClient is the network Client -type RoutesClient struct { - BaseClient -} - -// NewRoutesClient creates an instance of the RoutesClient client. -func NewRoutesClient(subscriptionID string) RoutesClient { - return NewRoutesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRoutesClientWithBaseURI creates an instance of the RoutesClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewRoutesClientWithBaseURI(baseURI string, subscriptionID string) RoutesClient { - return RoutesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a route in the specified route table. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -// routeName - the name of the route. -// routeParameters - parameters supplied to the create or update route operation. -func (client RoutesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, routeParameters Route) (result RoutesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, routeTableName, routeName, routeParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RoutesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, routeParameters Route) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeName": autorest.Encode("path", routeName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - routeParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}", pathParameters), - autorest.WithJSON(routeParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client RoutesClient) CreateOrUpdateSender(req *http.Request) (future RoutesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RoutesClient) CreateOrUpdateResponder(resp *http.Response) (result Route, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified route from a route table. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -// routeName - the name of the route. -func (client RoutesClient) Delete(ctx context.Context, resourceGroupName string, routeTableName string, routeName string) (result RoutesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, routeTableName, routeName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RoutesClient) DeletePreparer(ctx context.Context, resourceGroupName string, routeTableName string, routeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeName": autorest.Encode("path", routeName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/routeTables/{routeTableName}/routes/{routeName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RoutesClient) DeleteSender(req *http.Request) (future RoutesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RoutesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified route from a route table. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -// routeName - the name of the route. -func (client RoutesClient) Get(ctx context.Context, resourceGroupName string, routeTableName string, routeName string) (result Route, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, routeTableName, routeName) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.RoutesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client RoutesClient) GetPreparer(ctx context.Context, resourceGroupName string, routeTableName string, routeName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeName": autorest.Encode("path", routeName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/routeTables/{routeTableName}/routes/{routeName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RoutesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RoutesClient) GetResponder(resp *http.Response) (result Route, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all routes in a route table. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -func (client RoutesClient) List(ctx context.Context, resourceGroupName string, routeTableName string) (result RouteListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutesClient.List") - defer func() { - sc := -1 - if result.rlr.Response.Response != nil { - sc = result.rlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, routeTableName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.rlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure sending request") - return - } - - result.rlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure responding to request") - return - } - if result.rlr.hasNextLink() && result.rlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client RoutesClient) ListPreparer(ctx context.Context, resourceGroupName string, routeTableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/routeTables/{routeTableName}/routes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client RoutesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client RoutesClient) ListResponder(resp *http.Response) (result RouteListResult, err error) { - err = autorest.Respond( - resp, - 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 RoutesClient) listNextResults(ctx context.Context, lastResults RouteListResult) (result RouteListResult, err error) { - req, err := lastResults.routeListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RoutesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RoutesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RoutesClient) ListComplete(ctx context.Context, resourceGroupName string, routeTableName string) (result RouteListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, routeTableName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routetables.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routetables.go deleted file mode 100644 index 79d8c6e272..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routetables.go +++ /dev/null @@ -1,580 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RouteTablesClient is the network Client -type RouteTablesClient struct { - BaseClient -} - -// NewRouteTablesClient creates an instance of the RouteTablesClient client. -func NewRouteTablesClient(subscriptionID string) RouteTablesClient { - return NewRouteTablesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRouteTablesClientWithBaseURI creates an instance of the RouteTablesClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewRouteTablesClientWithBaseURI(baseURI string, subscriptionID string) RouteTablesClient { - return RouteTablesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create or updates a route table in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -// parameters - parameters supplied to the create or update route table operation. -func (client RouteTablesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, routeTableName string, parameters RouteTable) (result RouteTablesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, routeTableName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RouteTablesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, routeTableName string, parameters RouteTable) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client RouteTablesClient) CreateOrUpdateSender(req *http.Request) (future RouteTablesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RouteTablesClient) CreateOrUpdateResponder(resp *http.Response) (result RouteTable, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified route table. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -func (client RouteTablesClient) Delete(ctx context.Context, resourceGroupName string, routeTableName string) (result RouteTablesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, routeTableName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RouteTablesClient) DeletePreparer(ctx context.Context, resourceGroupName string, routeTableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/routeTables/{routeTableName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RouteTablesClient) DeleteSender(req *http.Request) (future RouteTablesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RouteTablesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified route table. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -// expand - expands referenced resources. -func (client RouteTablesClient) Get(ctx context.Context, resourceGroupName string, routeTableName string, expand string) (result RouteTable, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, routeTableName, expand) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client RouteTablesClient) GetPreparer(ctx context.Context, resourceGroupName string, routeTableName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/routeTables/{routeTableName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RouteTablesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RouteTablesClient) GetResponder(resp *http.Response) (result RouteTable, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all route tables in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client RouteTablesClient) List(ctx context.Context, resourceGroupName string) (result RouteTableListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.List") - defer func() { - sc := -1 - if result.rtlr.Response.Response != nil { - sc = result.rtlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.rtlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure sending request") - return - } - - result.rtlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure responding to request") - return - } - if result.rtlr.hasNextLink() && result.rtlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client RouteTablesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/routeTables", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client RouteTablesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client RouteTablesClient) ListResponder(resp *http.Response) (result RouteTableListResult, err error) { - err = autorest.Respond( - resp, - 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 RouteTablesClient) listNextResults(ctx context.Context, lastResults RouteTableListResult) (result RouteTableListResult, err error) { - req, err := lastResults.routeTableListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RouteTablesClient) ListComplete(ctx context.Context, resourceGroupName string) (result RouteTableListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all route tables in a subscription. -func (client RouteTablesClient) ListAll(ctx context.Context) (result RouteTableListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.ListAll") - defer func() { - sc := -1 - if result.rtlr.Response.Response != nil { - sc = result.rtlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.rtlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure sending request") - return - } - - result.rtlr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.rtlr.hasNextLink() && result.rtlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client RouteTablesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/routeTables", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client RouteTablesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client RouteTablesClient) ListAllResponder(resp *http.Response) (result RouteTableListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client RouteTablesClient) listAllNextResults(ctx context.Context, lastResults RouteTableListResult) (result RouteTableListResult, err error) { - req, err := lastResults.routeTableListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client RouteTablesClient) ListAllComplete(ctx context.Context) (result RouteTableListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// UpdateTags updates a route table tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// routeTableName - the name of the route table. -// parameters - parameters supplied to update route table tags. -func (client RouteTablesClient) UpdateTags(ctx context.Context, resourceGroupName string, routeTableName string, parameters TagsObject) (result RouteTable, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RouteTablesClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, routeTableName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client RouteTablesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, routeTableName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client RouteTablesClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client RouteTablesClient) UpdateTagsResponder(resp *http.Response) (result RouteTable, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routingintent.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routingintent.go deleted file mode 100644 index cafcec1b9f..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/routingintent.go +++ /dev/null @@ -1,393 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// RoutingIntentClient is the network Client -type RoutingIntentClient struct { - BaseClient -} - -// NewRoutingIntentClient creates an instance of the RoutingIntentClient client. -func NewRoutingIntentClient(subscriptionID string) RoutingIntentClient { - return NewRoutingIntentClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRoutingIntentClientWithBaseURI creates an instance of the RoutingIntentClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewRoutingIntentClientWithBaseURI(baseURI string, subscriptionID string) RoutingIntentClient { - return RoutingIntentClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a RoutingIntent resource if it doesn't exist else updates the existing RoutingIntent. -// Parameters: -// resourceGroupName - the resource group name of the RoutingIntent. -// virtualHubName - the name of the VirtualHub. -// routingIntentName - the name of the per VirtualHub singleton Routing Intent resource. -// routingIntentParameters - parameters supplied to create or update RoutingIntent. -func (client RoutingIntentClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string, routingIntentParameters RoutingIntent) (result RoutingIntentCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutingIntentClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualHubName, routingIntentName, routingIntentParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutingIntentClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutingIntentClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RoutingIntentClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string, routingIntentParameters RoutingIntent) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routingIntentName": autorest.Encode("path", routingIntentName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - routingIntentParameters.Etag = nil - routingIntentParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routingIntent/{routingIntentName}", pathParameters), - autorest.WithJSON(routingIntentParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client RoutingIntentClient) CreateOrUpdateSender(req *http.Request) (future RoutingIntentCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RoutingIntentClient) CreateOrUpdateResponder(resp *http.Response) (result RoutingIntent, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a RoutingIntent. -// Parameters: -// resourceGroupName - the resource group name of the RoutingIntent. -// virtualHubName - the name of the VirtualHub. -// routingIntentName - the name of the RoutingIntent. -func (client RoutingIntentClient) Delete(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string) (result RoutingIntentDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutingIntentClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualHubName, routingIntentName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutingIntentClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutingIntentClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RoutingIntentClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routingIntentName": autorest.Encode("path", routingIntentName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/routingIntent/{routingIntentName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RoutingIntentClient) DeleteSender(req *http.Request) (future RoutingIntentDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RoutingIntentClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a RoutingIntent. -// Parameters: -// resourceGroupName - the resource group name of the RoutingIntent. -// virtualHubName - the name of the VirtualHub. -// routingIntentName - the name of the RoutingIntent. -func (client RoutingIntentClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string) (result RoutingIntent, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutingIntentClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualHubName, routingIntentName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutingIntentClient", "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.RoutingIntentClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutingIntentClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client RoutingIntentClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, routingIntentName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routingIntentName": autorest.Encode("path", routingIntentName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/routingIntent/{routingIntentName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RoutingIntentClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RoutingIntentClient) GetResponder(resp *http.Response) (result RoutingIntent, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List retrieves the details of all RoutingIntent child resources of the VirtualHub. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -func (client RoutingIntentClient) List(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListRoutingIntentResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutingIntentClient.List") - defer func() { - sc := -1 - if result.lrir.Response.Response != nil { - sc = result.lrir.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualHubName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutingIntentClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lrir.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.RoutingIntentClient", "List", resp, "Failure sending request") - return - } - - result.lrir, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutingIntentClient", "List", resp, "Failure responding to request") - return - } - if result.lrir.hasNextLink() && result.lrir.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client RoutingIntentClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/routingIntent", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client RoutingIntentClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client RoutingIntentClient) ListResponder(resp *http.Response) (result ListRoutingIntentResult, err error) { - err = autorest.Respond( - resp, - 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 RoutingIntentClient) listNextResults(ctx context.Context, lastResults ListRoutingIntentResult) (result ListRoutingIntentResult, err error) { - req, err := lastResults.listRoutingIntentResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RoutingIntentClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RoutingIntentClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutingIntentClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client RoutingIntentClient) ListComplete(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListRoutingIntentResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/RoutingIntentClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualHubName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/scopeconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/scopeconnections.go deleted file mode 100644 index b08b24b972..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/scopeconnections.go +++ /dev/null @@ -1,408 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ScopeConnectionsClient is the network Client -type ScopeConnectionsClient struct { - BaseClient -} - -// NewScopeConnectionsClient creates an instance of the ScopeConnectionsClient client. -func NewScopeConnectionsClient(subscriptionID string) ScopeConnectionsClient { - return NewScopeConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewScopeConnectionsClientWithBaseURI creates an instance of the ScopeConnectionsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewScopeConnectionsClientWithBaseURI(baseURI string, subscriptionID string) ScopeConnectionsClient { - return ScopeConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates scope connection from Network Manager -// Parameters: -// parameters - scope connection to be created/updated. -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// scopeConnectionName - name for the cross-tenant connection. -func (client ScopeConnectionsClient) CreateOrUpdate(ctx context.Context, parameters ScopeConnection, resourceGroupName string, networkManagerName string, scopeConnectionName string) (result ScopeConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ScopeConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, parameters, resourceGroupName, networkManagerName, scopeConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ScopeConnectionsClient", "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.ScopeConnectionsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ScopeConnectionsClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ScopeConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, parameters ScopeConnection, resourceGroupName string, networkManagerName string, scopeConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "scopeConnectionName": autorest.Encode("path", scopeConnectionName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/scopeConnections/{scopeConnectionName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ScopeConnectionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ScopeConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result ScopeConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete the pending scope connection created by this network manager. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// scopeConnectionName - name for the cross-tenant connection. -func (client ScopeConnectionsClient) Delete(ctx context.Context, resourceGroupName string, networkManagerName string, scopeConnectionName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ScopeConnectionsClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkManagerName, scopeConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ScopeConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "network.ScopeConnectionsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ScopeConnectionsClient", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ScopeConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkManagerName string, scopeConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "scopeConnectionName": autorest.Encode("path", scopeConnectionName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkManagers/{networkManagerName}/scopeConnections/{scopeConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ScopeConnectionsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ScopeConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get specified scope connection created by this Network Manager. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// scopeConnectionName - name for the cross-tenant connection. -func (client ScopeConnectionsClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, scopeConnectionName string) (result ScopeConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ScopeConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkManagerName, scopeConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ScopeConnectionsClient", "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.ScopeConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ScopeConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ScopeConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, scopeConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "scopeConnectionName": autorest.Encode("path", scopeConnectionName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkManagers/{networkManagerName}/scopeConnections/{scopeConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ScopeConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ScopeConnectionsClient) GetResponder(resp *http.Response) (result ScopeConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all scope connections created by this network manager. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -// skipToken - skipToken is only used if a previous operation returned a partial result. If a previous response -// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that -// specifies a starting point to use for subsequent calls. -func (client ScopeConnectionsClient) List(ctx context.Context, resourceGroupName string, networkManagerName string, top *int32, skipToken string) (result ScopeConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ScopeConnectionsClient.List") - defer func() { - sc := -1 - if result.sclr.Response.Response != nil { - sc = result.sclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.ScopeConnectionsClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkManagerName, top, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ScopeConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.sclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ScopeConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.sclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ScopeConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.sclr.hasNextLink() && result.sclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ScopeConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, top *int32, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(skipToken) > 0 { - queryParameters["$skipToken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/scopeConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ScopeConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ScopeConnectionsClient) ListResponder(resp *http.Response) (result ScopeConnectionListResult, err error) { - err = autorest.Respond( - resp, - 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 ScopeConnectionsClient) listNextResults(ctx context.Context, lastResults ScopeConnectionListResult) (result ScopeConnectionListResult, err error) { - req, err := lastResults.scopeConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ScopeConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ScopeConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ScopeConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ScopeConnectionsClient) ListComplete(ctx context.Context, resourceGroupName string, networkManagerName string, top *int32, skipToken string) (result ScopeConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ScopeConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkManagerName, top, skipToken) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/securityadminconfigurations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/securityadminconfigurations.go deleted file mode 100644 index 4bea70a637..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/securityadminconfigurations.go +++ /dev/null @@ -1,416 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SecurityAdminConfigurationsClient is the network Client -type SecurityAdminConfigurationsClient struct { - BaseClient -} - -// NewSecurityAdminConfigurationsClient creates an instance of the SecurityAdminConfigurationsClient client. -func NewSecurityAdminConfigurationsClient(subscriptionID string) SecurityAdminConfigurationsClient { - return NewSecurityAdminConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSecurityAdminConfigurationsClientWithBaseURI creates an instance of the SecurityAdminConfigurationsClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewSecurityAdminConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) SecurityAdminConfigurationsClient { - return SecurityAdminConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a network manager security admin configuration. -// Parameters: -// securityAdminConfiguration - the security admin configuration to create or update -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager Security Configuration. -func (client SecurityAdminConfigurationsClient) CreateOrUpdate(ctx context.Context, securityAdminConfiguration SecurityAdminConfiguration, resourceGroupName string, networkManagerName string, configurationName string) (result SecurityAdminConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityAdminConfigurationsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, securityAdminConfiguration, resourceGroupName, networkManagerName, configurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityAdminConfigurationsClient", "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.SecurityAdminConfigurationsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityAdminConfigurationsClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client SecurityAdminConfigurationsClient) CreateOrUpdatePreparer(ctx context.Context, securityAdminConfiguration SecurityAdminConfiguration, resourceGroupName string, networkManagerName string, configurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - securityAdminConfiguration.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}", pathParameters), - autorest.WithJSON(securityAdminConfiguration), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityAdminConfigurationsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client SecurityAdminConfigurationsClient) CreateOrUpdateResponder(resp *http.Response) (result SecurityAdminConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a network manager security admin configuration. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager Security Configuration. -// force - deletes the resource even if it is part of a deployed configuration. If the configuration has been -// deployed, the service will do a cleanup deployment in the background, prior to the delete. -func (client SecurityAdminConfigurationsClient) Delete(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, force *bool) (result SecurityAdminConfigurationsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityAdminConfigurationsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkManagerName, configurationName, force) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityAdminConfigurationsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityAdminConfigurationsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client SecurityAdminConfigurationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string, force *bool) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if force != nil { - queryParameters["force"] = autorest.Encode("query", *force) - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityAdminConfigurationsClient) DeleteSender(req *http.Request) (future SecurityAdminConfigurationsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client SecurityAdminConfigurationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves a network manager security admin configuration. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// configurationName - the name of the network manager Security Configuration. -func (client SecurityAdminConfigurationsClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string) (result SecurityAdminConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityAdminConfigurationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkManagerName, configurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityAdminConfigurationsClient", "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.SecurityAdminConfigurationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityAdminConfigurationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client SecurityAdminConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, configurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "configurationName": autorest.Encode("path", configurationName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkManagers/{networkManagerName}/securityAdminConfigurations/{configurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityAdminConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client SecurityAdminConfigurationsClient) GetResponder(resp *http.Response) (result SecurityAdminConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the network manager security admin configurations in a network manager, in a paginated format. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -// skipToken - skipToken is only used if a previous operation returned a partial result. If a previous response -// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that -// specifies a starting point to use for subsequent calls. -func (client SecurityAdminConfigurationsClient) List(ctx context.Context, resourceGroupName string, networkManagerName string, top *int32, skipToken string) (result SecurityAdminConfigurationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityAdminConfigurationsClient.List") - defer func() { - sc := -1 - if result.saclr.Response.Response != nil { - sc = result.saclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.SecurityAdminConfigurationsClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkManagerName, top, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityAdminConfigurationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.saclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SecurityAdminConfigurationsClient", "List", resp, "Failure sending request") - return - } - - result.saclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityAdminConfigurationsClient", "List", resp, "Failure responding to request") - return - } - if result.saclr.hasNextLink() && result.saclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client SecurityAdminConfigurationsClient) ListPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, top *int32, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(skipToken) > 0 { - queryParameters["$skipToken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/securityAdminConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityAdminConfigurationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client SecurityAdminConfigurationsClient) ListResponder(resp *http.Response) (result SecurityAdminConfigurationListResult, err error) { - err = autorest.Respond( - resp, - 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 SecurityAdminConfigurationsClient) listNextResults(ctx context.Context, lastResults SecurityAdminConfigurationListResult) (result SecurityAdminConfigurationListResult, err error) { - req, err := lastResults.securityAdminConfigurationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SecurityAdminConfigurationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityAdminConfigurationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityAdminConfigurationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client SecurityAdminConfigurationsClient) ListComplete(ctx context.Context, resourceGroupName string, networkManagerName string, top *int32, skipToken string) (result SecurityAdminConfigurationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityAdminConfigurationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkManagerName, top, skipToken) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/securitygroups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/securitygroups.go deleted file mode 100644 index 365f7f33c5..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/securitygroups.go +++ /dev/null @@ -1,580 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SecurityGroupsClient is the network Client -type SecurityGroupsClient struct { - BaseClient -} - -// NewSecurityGroupsClient creates an instance of the SecurityGroupsClient client. -func NewSecurityGroupsClient(subscriptionID string) SecurityGroupsClient { - return NewSecurityGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSecurityGroupsClientWithBaseURI creates an instance of the SecurityGroupsClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewSecurityGroupsClientWithBaseURI(baseURI string, subscriptionID string) SecurityGroupsClient { - return SecurityGroupsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a network security group in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// parameters - parameters supplied to the create or update network security group operation. -func (client SecurityGroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup) (result SecurityGroupsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkSecurityGroupName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client SecurityGroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityGroupsClient) CreateOrUpdateSender(req *http.Request) (future SecurityGroupsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client SecurityGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result SecurityGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified network security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -func (client SecurityGroupsClient) Delete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (result SecurityGroupsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkSecurityGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client SecurityGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityGroupsClient) DeleteSender(req *http.Request) (future SecurityGroupsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client SecurityGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified network security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// expand - expands referenced resources. -func (client SecurityGroupsClient) Get(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, expand string) (result SecurityGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkSecurityGroupName, expand) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client SecurityGroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityGroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client SecurityGroupsClient) GetResponder(resp *http.Response) (result SecurityGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all network security groups in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client SecurityGroupsClient) List(ctx context.Context, resourceGroupName string) (result SecurityGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.List") - defer func() { - sc := -1 - if result.sglr.Response.Response != nil { - sc = result.sglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.sglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure sending request") - return - } - - result.sglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure responding to request") - return - } - if result.sglr.hasNextLink() && result.sglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client SecurityGroupsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkSecurityGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityGroupsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client SecurityGroupsClient) ListResponder(resp *http.Response) (result SecurityGroupListResult, err error) { - err = autorest.Respond( - resp, - 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 SecurityGroupsClient) listNextResults(ctx context.Context, lastResults SecurityGroupListResult) (result SecurityGroupListResult, err error) { - req, err := lastResults.securityGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client SecurityGroupsClient) ListComplete(ctx context.Context, resourceGroupName string) (result SecurityGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all network security groups in a subscription. -func (client SecurityGroupsClient) ListAll(ctx context.Context) (result SecurityGroupListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.ListAll") - defer func() { - sc := -1 - if result.sglr.Response.Response != nil { - sc = result.sglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.sglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure sending request") - return - } - - result.sglr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure responding to request") - return - } - if result.sglr.hasNextLink() && result.sglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client SecurityGroupsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkSecurityGroups", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityGroupsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client SecurityGroupsClient) ListAllResponder(resp *http.Response) (result SecurityGroupListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client SecurityGroupsClient) listAllNextResults(ctx context.Context, lastResults SecurityGroupListResult) (result SecurityGroupListResult, err error) { - req, err := lastResults.securityGroupListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client SecurityGroupsClient) ListAllComplete(ctx context.Context) (result SecurityGroupListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// UpdateTags updates a network security group tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// parameters - parameters supplied to update network security group tags. -func (client SecurityGroupsClient) UpdateTags(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters TagsObject) (result SecurityGroup, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityGroupsClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, networkSecurityGroupName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client SecurityGroupsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityGroupsClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client SecurityGroupsClient) UpdateTagsResponder(resp *http.Response) (result SecurityGroup, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/securitypartnerproviders.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/securitypartnerproviders.go deleted file mode 100644 index de93a91dff..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/securitypartnerproviders.go +++ /dev/null @@ -1,577 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SecurityPartnerProvidersClient is the network Client -type SecurityPartnerProvidersClient struct { - BaseClient -} - -// NewSecurityPartnerProvidersClient creates an instance of the SecurityPartnerProvidersClient client. -func NewSecurityPartnerProvidersClient(subscriptionID string) SecurityPartnerProvidersClient { - return NewSecurityPartnerProvidersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSecurityPartnerProvidersClientWithBaseURI creates an instance of the SecurityPartnerProvidersClient client using -// a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewSecurityPartnerProvidersClientWithBaseURI(baseURI string, subscriptionID string) SecurityPartnerProvidersClient { - return SecurityPartnerProvidersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates the specified Security Partner Provider. -// Parameters: -// resourceGroupName - the name of the resource group. -// securityPartnerProviderName - the name of the Security Partner Provider. -// parameters - parameters supplied to the create or update Security Partner Provider operation. -func (client SecurityPartnerProvidersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, parameters SecurityPartnerProvider) (result SecurityPartnerProvidersCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityPartnerProvidersClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, securityPartnerProviderName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client SecurityPartnerProvidersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, parameters SecurityPartnerProvider) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "securityPartnerProviderName": autorest.Encode("path", securityPartnerProviderName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/securityPartnerProviders/{securityPartnerProviderName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityPartnerProvidersClient) CreateOrUpdateSender(req *http.Request) (future SecurityPartnerProvidersCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client SecurityPartnerProvidersClient) CreateOrUpdateResponder(resp *http.Response) (result SecurityPartnerProvider, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified Security Partner Provider. -// Parameters: -// resourceGroupName - the name of the resource group. -// securityPartnerProviderName - the name of the Security Partner Provider. -func (client SecurityPartnerProvidersClient) Delete(ctx context.Context, resourceGroupName string, securityPartnerProviderName string) (result SecurityPartnerProvidersDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityPartnerProvidersClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, securityPartnerProviderName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client SecurityPartnerProvidersClient) DeletePreparer(ctx context.Context, resourceGroupName string, securityPartnerProviderName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "securityPartnerProviderName": autorest.Encode("path", securityPartnerProviderName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/securityPartnerProviders/{securityPartnerProviderName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityPartnerProvidersClient) DeleteSender(req *http.Request) (future SecurityPartnerProvidersDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client SecurityPartnerProvidersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified Security Partner Provider. -// Parameters: -// resourceGroupName - the name of the resource group. -// securityPartnerProviderName - the name of the Security Partner Provider. -func (client SecurityPartnerProvidersClient) Get(ctx context.Context, resourceGroupName string, securityPartnerProviderName string) (result SecurityPartnerProvider, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityPartnerProvidersClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, securityPartnerProviderName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "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.SecurityPartnerProvidersClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client SecurityPartnerProvidersClient) GetPreparer(ctx context.Context, resourceGroupName string, securityPartnerProviderName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "securityPartnerProviderName": autorest.Encode("path", securityPartnerProviderName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/securityPartnerProviders/{securityPartnerProviderName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityPartnerProvidersClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client SecurityPartnerProvidersClient) GetResponder(resp *http.Response) (result SecurityPartnerProvider, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the Security Partner Providers in a subscription. -func (client SecurityPartnerProvidersClient) List(ctx context.Context) (result SecurityPartnerProviderListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityPartnerProvidersClient.List") - defer func() { - sc := -1 - if result.spplr.Response.Response != nil { - sc = result.spplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.spplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "List", resp, "Failure sending request") - return - } - - result.spplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "List", resp, "Failure responding to request") - return - } - if result.spplr.hasNextLink() && result.spplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client SecurityPartnerProvidersClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/securityPartnerProviders", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityPartnerProvidersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client SecurityPartnerProvidersClient) ListResponder(resp *http.Response) (result SecurityPartnerProviderListResult, err error) { - err = autorest.Respond( - resp, - 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 SecurityPartnerProvidersClient) listNextResults(ctx context.Context, lastResults SecurityPartnerProviderListResult) (result SecurityPartnerProviderListResult, err error) { - req, err := lastResults.securityPartnerProviderListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client SecurityPartnerProvidersClient) ListComplete(ctx context.Context) (result SecurityPartnerProviderListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityPartnerProvidersClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all Security Partner Providers in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client SecurityPartnerProvidersClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result SecurityPartnerProviderListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityPartnerProvidersClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.spplr.Response.Response != nil { - sc = result.spplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.spplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.spplr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.spplr.hasNextLink() && result.spplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client SecurityPartnerProvidersClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/securityPartnerProviders", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityPartnerProvidersClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client SecurityPartnerProvidersClient) ListByResourceGroupResponder(resp *http.Response) (result SecurityPartnerProviderListResult, err error) { - err = autorest.Respond( - resp, - 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 SecurityPartnerProvidersClient) listByResourceGroupNextResults(ctx context.Context, lastResults SecurityPartnerProviderListResult) (result SecurityPartnerProviderListResult, err error) { - req, err := lastResults.securityPartnerProviderListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client SecurityPartnerProvidersClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result SecurityPartnerProviderListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityPartnerProvidersClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates tags of a Security Partner Provider resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// securityPartnerProviderName - the name of the Security Partner Provider. -// parameters - parameters supplied to update Security Partner Provider tags. -func (client SecurityPartnerProvidersClient) UpdateTags(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, parameters TagsObject) (result SecurityPartnerProvider, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityPartnerProvidersClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, securityPartnerProviderName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityPartnerProvidersClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client SecurityPartnerProvidersClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, securityPartnerProviderName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "securityPartnerProviderName": autorest.Encode("path", securityPartnerProviderName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/securityPartnerProviders/{securityPartnerProviderName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityPartnerProvidersClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client SecurityPartnerProvidersClient) UpdateTagsResponder(resp *http.Response) (result SecurityPartnerProvider, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/securityrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/securityrules.go deleted file mode 100644 index 744c7cea70..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/securityrules.go +++ /dev/null @@ -1,392 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SecurityRulesClient is the network Client -type SecurityRulesClient struct { - BaseClient -} - -// NewSecurityRulesClient creates an instance of the SecurityRulesClient client. -func NewSecurityRulesClient(subscriptionID string) SecurityRulesClient { - return NewSecurityRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSecurityRulesClientWithBaseURI creates an instance of the SecurityRulesClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewSecurityRulesClientWithBaseURI(baseURI string, subscriptionID string) SecurityRulesClient { - return SecurityRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a security rule in the specified network security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// securityRuleName - the name of the security rule. -// securityRuleParameters - parameters supplied to the create or update network security rule operation. -func (client SecurityRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule) (result SecurityRulesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRulesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client SecurityRulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "securityRuleName": autorest.Encode("path", securityRuleName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - securityRuleParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}", pathParameters), - autorest.WithJSON(securityRuleParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityRulesClient) CreateOrUpdateSender(req *http.Request) (future SecurityRulesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client SecurityRulesClient) CreateOrUpdateResponder(resp *http.Response) (result SecurityRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified network security rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// securityRuleName - the name of the security rule. -func (client SecurityRulesClient) Delete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (result SecurityRulesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRulesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkSecurityGroupName, securityRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client SecurityRulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "securityRuleName": autorest.Encode("path", securityRuleName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityRulesClient) DeleteSender(req *http.Request) (future SecurityRulesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client SecurityRulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the specified network security rule. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -// securityRuleName - the name of the security rule. -func (client SecurityRulesClient) Get(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (result SecurityRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkSecurityGroupName, securityRuleName) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client SecurityRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "securityRuleName": autorest.Encode("path", securityRuleName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client SecurityRulesClient) GetResponder(resp *http.Response) (result SecurityRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all security rules in a network security group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkSecurityGroupName - the name of the network security group. -func (client SecurityRulesClient) List(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRulesClient.List") - defer func() { - sc := -1 - if result.srlr.Response.Response != nil { - sc = result.srlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkSecurityGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.srlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure sending request") - return - } - - result.srlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure responding to request") - return - } - if result.srlr.hasNextLink() && result.srlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client SecurityRulesClient) ListPreparer(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkSecurityGroups/{networkSecurityGroupName}/securityRules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client SecurityRulesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client SecurityRulesClient) ListResponder(resp *http.Response) (result SecurityRuleListResult, err error) { - err = autorest.Respond( - resp, - 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 SecurityRulesClient) listNextResults(ctx context.Context, lastResults SecurityRuleListResult) (result SecurityRuleListResult, err error) { - req, err := lastResults.securityRuleListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client SecurityRulesClient) ListComplete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecurityRulesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkSecurityGroupName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/serviceassociationlinks.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/serviceassociationlinks.go deleted file mode 100644 index c36939d2c7..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/serviceassociationlinks.go +++ /dev/null @@ -1,110 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ServiceAssociationLinksClient is the network Client -type ServiceAssociationLinksClient struct { - BaseClient -} - -// NewServiceAssociationLinksClient creates an instance of the ServiceAssociationLinksClient client. -func NewServiceAssociationLinksClient(subscriptionID string) ServiceAssociationLinksClient { - return NewServiceAssociationLinksClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewServiceAssociationLinksClientWithBaseURI creates an instance of the ServiceAssociationLinksClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewServiceAssociationLinksClientWithBaseURI(baseURI string, subscriptionID string) ServiceAssociationLinksClient { - return ServiceAssociationLinksClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets a list of service association links for a subnet. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// subnetName - the name of the subnet. -func (client ServiceAssociationLinksClient) List(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) (result ServiceAssociationLinksListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceAssociationLinksClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, virtualNetworkName, subnetName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceAssociationLinksClient", "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.ServiceAssociationLinksClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceAssociationLinksClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ServiceAssociationLinksClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subnetName": autorest.Encode("path", subnetName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2022-07-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/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/ServiceAssociationLinks", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceAssociationLinksClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ServiceAssociationLinksClient) ListResponder(resp *http.Response) (result ServiceAssociationLinksListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/serviceendpointpolicies.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/serviceendpointpolicies.go deleted file mode 100644 index 4b74b9fff1..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/serviceendpointpolicies.go +++ /dev/null @@ -1,582 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ServiceEndpointPoliciesClient is the network Client -type ServiceEndpointPoliciesClient struct { - BaseClient -} - -// NewServiceEndpointPoliciesClient creates an instance of the ServiceEndpointPoliciesClient client. -func NewServiceEndpointPoliciesClient(subscriptionID string) ServiceEndpointPoliciesClient { - return NewServiceEndpointPoliciesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewServiceEndpointPoliciesClientWithBaseURI creates an instance of the ServiceEndpointPoliciesClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewServiceEndpointPoliciesClientWithBaseURI(baseURI string, subscriptionID string) ServiceEndpointPoliciesClient { - return ServiceEndpointPoliciesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a service Endpoint Policies. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy. -// parameters - parameters supplied to the create or update service endpoint policy operation. -func (client ServiceEndpointPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, parameters ServiceEndpointPolicy) (result ServiceEndpointPoliciesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceEndpointPolicyName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ServiceEndpointPoliciesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, parameters ServiceEndpointPolicy) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - parameters.Kind = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPoliciesClient) CreateOrUpdateSender(req *http.Request) (future ServiceEndpointPoliciesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPoliciesClient) CreateOrUpdateResponder(resp *http.Response) (result ServiceEndpointPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified service endpoint policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy. -func (client ServiceEndpointPoliciesClient) Delete(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string) (result ServiceEndpointPoliciesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceEndpointPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ServiceEndpointPoliciesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/serviceEndpointPolicies/{serviceEndpointPolicyName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPoliciesClient) DeleteSender(req *http.Request) (future ServiceEndpointPoliciesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPoliciesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified service Endpoint Policies in a specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy. -// expand - expands referenced resources. -func (client ServiceEndpointPoliciesClient) Get(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, expand string) (result ServiceEndpointPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceEndpointPolicyName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "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.ServiceEndpointPoliciesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ServiceEndpointPoliciesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/serviceEndpointPolicies/{serviceEndpointPolicyName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPoliciesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPoliciesClient) GetResponder(resp *http.Response) (result ServiceEndpointPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the service endpoint policies in a subscription. -func (client ServiceEndpointPoliciesClient) List(ctx context.Context) (result ServiceEndpointPolicyListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.List") - defer func() { - sc := -1 - if result.seplr.Response.Response != nil { - sc = result.seplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.seplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "List", resp, "Failure sending request") - return - } - - result.seplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "List", resp, "Failure responding to request") - return - } - if result.seplr.hasNextLink() && result.seplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ServiceEndpointPoliciesClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ServiceEndpointPolicies", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPoliciesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPoliciesClient) ListResponder(resp *http.Response) (result ServiceEndpointPolicyListResult, err error) { - err = autorest.Respond( - resp, - 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 ServiceEndpointPoliciesClient) listNextResults(ctx context.Context, lastResults ServiceEndpointPolicyListResult) (result ServiceEndpointPolicyListResult, err error) { - req, err := lastResults.serviceEndpointPolicyListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ServiceEndpointPoliciesClient) ListComplete(ctx context.Context) (result ServiceEndpointPolicyListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup gets all service endpoint Policies in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client ServiceEndpointPoliciesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ServiceEndpointPolicyListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.seplr.Response.Response != nil { - sc = result.seplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.seplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.seplr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.seplr.hasNextLink() && result.seplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ServiceEndpointPoliciesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/serviceEndpointPolicies", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPoliciesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPoliciesClient) ListByResourceGroupResponder(resp *http.Response) (result ServiceEndpointPolicyListResult, err error) { - err = autorest.Respond( - resp, - 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 ServiceEndpointPoliciesClient) listByResourceGroupNextResults(ctx context.Context, lastResults ServiceEndpointPolicyListResult) (result ServiceEndpointPolicyListResult, err error) { - req, err := lastResults.serviceEndpointPolicyListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ServiceEndpointPoliciesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ServiceEndpointPolicyListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates tags of a service endpoint policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy. -// parameters - parameters supplied to update service endpoint policy tags. -func (client ServiceEndpointPoliciesClient) UpdateTags(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, parameters TagsObject) (result ServiceEndpointPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPoliciesClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, serviceEndpointPolicyName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPoliciesClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client ServiceEndpointPoliciesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPoliciesClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPoliciesClient) UpdateTagsResponder(resp *http.Response) (result ServiceEndpointPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/serviceendpointpolicydefinitions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/serviceendpointpolicydefinitions.go deleted file mode 100644 index 5206cad37a..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/serviceendpointpolicydefinitions.go +++ /dev/null @@ -1,394 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ServiceEndpointPolicyDefinitionsClient is the network Client -type ServiceEndpointPolicyDefinitionsClient struct { - BaseClient -} - -// NewServiceEndpointPolicyDefinitionsClient creates an instance of the ServiceEndpointPolicyDefinitionsClient client. -func NewServiceEndpointPolicyDefinitionsClient(subscriptionID string) ServiceEndpointPolicyDefinitionsClient { - return NewServiceEndpointPolicyDefinitionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewServiceEndpointPolicyDefinitionsClientWithBaseURI creates an instance of the -// ServiceEndpointPolicyDefinitionsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewServiceEndpointPolicyDefinitionsClientWithBaseURI(baseURI string, subscriptionID string) ServiceEndpointPolicyDefinitionsClient { - return ServiceEndpointPolicyDefinitionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a service endpoint policy definition in the specified service endpoint policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy. -// serviceEndpointPolicyDefinitionName - the name of the service endpoint policy definition name. -// serviceEndpointPolicyDefinitions - parameters supplied to the create or update service endpoint policy -// operation. -func (client ServiceEndpointPolicyDefinitionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string, serviceEndpointPolicyDefinitions ServiceEndpointPolicyDefinition) (result ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, serviceEndpointPolicyDefinitions) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ServiceEndpointPolicyDefinitionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string, serviceEndpointPolicyDefinitions ServiceEndpointPolicyDefinition) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyDefinitionName": autorest.Encode("path", serviceEndpointPolicyDefinitionName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - serviceEndpointPolicyDefinitions.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}", pathParameters), - autorest.WithJSON(serviceEndpointPolicyDefinitions), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPolicyDefinitionsClient) CreateOrUpdateSender(req *http.Request) (future ServiceEndpointPolicyDefinitionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPolicyDefinitionsClient) CreateOrUpdateResponder(resp *http.Response) (result ServiceEndpointPolicyDefinition, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified ServiceEndpoint policy definitions. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the Service Endpoint Policy. -// serviceEndpointPolicyDefinitionName - the name of the service endpoint policy definition. -func (client ServiceEndpointPolicyDefinitionsClient) Delete(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string) (result ServiceEndpointPolicyDefinitionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ServiceEndpointPolicyDefinitionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyDefinitionName": autorest.Encode("path", serviceEndpointPolicyDefinitionName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPolicyDefinitionsClient) DeleteSender(req *http.Request) (future ServiceEndpointPolicyDefinitionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPolicyDefinitionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get the specified service endpoint policy definitions from service endpoint policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy name. -// serviceEndpointPolicyDefinitionName - the name of the service endpoint policy definition name. -func (client ServiceEndpointPolicyDefinitionsClient) Get(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string) (result ServiceEndpointPolicyDefinition, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "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.ServiceEndpointPolicyDefinitionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client ServiceEndpointPolicyDefinitionsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string, serviceEndpointPolicyDefinitionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyDefinitionName": autorest.Encode("path", serviceEndpointPolicyDefinitionName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions/{serviceEndpointPolicyDefinitionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPolicyDefinitionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPolicyDefinitionsClient) GetResponder(resp *http.Response) (result ServiceEndpointPolicyDefinition, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByResourceGroup gets all service endpoint policy definitions in a service end point policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// serviceEndpointPolicyName - the name of the service endpoint policy name. -func (client ServiceEndpointPolicyDefinitionsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string) (result ServiceEndpointPolicyDefinitionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.sepdlr.Response.Response != nil { - sc = result.sepdlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, serviceEndpointPolicyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.sepdlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.sepdlr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.sepdlr.hasNextLink() && result.sepdlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ServiceEndpointPolicyDefinitionsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "serviceEndpointPolicyName": autorest.Encode("path", serviceEndpointPolicyName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/serviceEndpointPolicies/{serviceEndpointPolicyName}/serviceEndpointPolicyDefinitions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceEndpointPolicyDefinitionsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ServiceEndpointPolicyDefinitionsClient) ListByResourceGroupResponder(resp *http.Response) (result ServiceEndpointPolicyDefinitionListResult, err error) { - err = autorest.Respond( - resp, - 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 ServiceEndpointPolicyDefinitionsClient) listByResourceGroupNextResults(ctx context.Context, lastResults ServiceEndpointPolicyDefinitionListResult) (result ServiceEndpointPolicyDefinitionListResult, err error) { - req, err := lastResults.serviceEndpointPolicyDefinitionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceEndpointPolicyDefinitionsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ServiceEndpointPolicyDefinitionsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, serviceEndpointPolicyName string) (result ServiceEndpointPolicyDefinitionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceEndpointPolicyDefinitionsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName, serviceEndpointPolicyName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/servicetaginformation.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/servicetaginformation.go deleted file mode 100644 index b57f55295f..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/servicetaginformation.go +++ /dev/null @@ -1,158 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ServiceTagInformationClient is the network Client -type ServiceTagInformationClient struct { - BaseClient -} - -// NewServiceTagInformationClient creates an instance of the ServiceTagInformationClient client. -func NewServiceTagInformationClient(subscriptionID string) ServiceTagInformationClient { - return NewServiceTagInformationClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewServiceTagInformationClientWithBaseURI creates an instance of the ServiceTagInformationClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewServiceTagInformationClientWithBaseURI(baseURI string, subscriptionID string) ServiceTagInformationClient { - return ServiceTagInformationClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets a list of service tag information resources with pagination. -// Parameters: -// location - the location that will be used as a reference for cloud (not as a filter based on location, you -// will get the list of service tags with prefix details across all regions but limited to the cloud that your -// subscription belongs to). -// noAddressPrefixes - do not return address prefixes for the tag(s). -// tagName - return tag information for a particular tag. -func (client ServiceTagInformationClient) List(ctx context.Context, location string, noAddressPrefixes *bool, tagName string) (result ServiceTagInformationListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceTagInformationClient.List") - defer func() { - sc := -1 - if result.stilr.Response.Response != nil { - sc = result.stilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, location, noAddressPrefixes, tagName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceTagInformationClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.stilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.ServiceTagInformationClient", "List", resp, "Failure sending request") - return - } - - result.stilr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceTagInformationClient", "List", resp, "Failure responding to request") - return - } - if result.stilr.hasNextLink() && result.stilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ServiceTagInformationClient) ListPreparer(ctx context.Context, location string, noAddressPrefixes *bool, tagName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if noAddressPrefixes != nil { - queryParameters["noAddressPrefixes"] = autorest.Encode("query", *noAddressPrefixes) - } - if len(tagName) > 0 { - queryParameters["tagName"] = autorest.Encode("query", tagName) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/serviceTagDetails", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceTagInformationClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ServiceTagInformationClient) ListResponder(resp *http.Response) (result ServiceTagInformationListResult, err error) { - err = autorest.Respond( - resp, - 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 ServiceTagInformationClient) listNextResults(ctx context.Context, lastResults ServiceTagInformationListResult) (result ServiceTagInformationListResult, err error) { - req, err := lastResults.serviceTagInformationListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ServiceTagInformationClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ServiceTagInformationClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceTagInformationClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ServiceTagInformationClient) ListComplete(ctx context.Context, location string, noAddressPrefixes *bool, tagName string) (result ServiceTagInformationListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceTagInformationClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, location, noAddressPrefixes, tagName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/servicetags.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/servicetags.go deleted file mode 100644 index 3710ad3961..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/servicetags.go +++ /dev/null @@ -1,107 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// ServiceTagsClient is the network Client -type ServiceTagsClient struct { - BaseClient -} - -// NewServiceTagsClient creates an instance of the ServiceTagsClient client. -func NewServiceTagsClient(subscriptionID string) ServiceTagsClient { - return NewServiceTagsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewServiceTagsClientWithBaseURI creates an instance of the ServiceTagsClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewServiceTagsClientWithBaseURI(baseURI string, subscriptionID string) ServiceTagsClient { - return ServiceTagsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gets a list of service tag information resources. -// Parameters: -// location - the location that will be used as a reference for version (not as a filter based on location, you -// will get the list of service tags with prefix details across all regions but limited to the cloud that your -// subscription belongs to). -func (client ServiceTagsClient) List(ctx context.Context, location string) (result ServiceTagsListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/ServiceTagsClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceTagsClient", "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.ServiceTagsClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ServiceTagsClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client ServiceTagsClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/serviceTags", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ServiceTagsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ServiceTagsClient) ListResponder(resp *http.Response) (result ServiceTagsListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/staticmembers.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/staticmembers.go deleted file mode 100644 index 565741e30d..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/staticmembers.go +++ /dev/null @@ -1,415 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// StaticMembersClient is the network Client -type StaticMembersClient struct { - BaseClient -} - -// NewStaticMembersClient creates an instance of the StaticMembersClient client. -func NewStaticMembersClient(subscriptionID string) StaticMembersClient { - return NewStaticMembersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewStaticMembersClientWithBaseURI creates an instance of the StaticMembersClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewStaticMembersClientWithBaseURI(baseURI string, subscriptionID string) StaticMembersClient { - return StaticMembersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a static member. -// Parameters: -// parameters - parameters supplied to the specify the static member to create -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// networkGroupName - the name of the network group. -// staticMemberName - the name of the static member. -func (client StaticMembersClient) CreateOrUpdate(ctx context.Context, parameters StaticMember, resourceGroupName string, networkManagerName string, networkGroupName string, staticMemberName string) (result StaticMember, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StaticMembersClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, parameters, resourceGroupName, networkManagerName, networkGroupName, staticMemberName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.StaticMembersClient", "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.StaticMembersClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.StaticMembersClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client StaticMembersClient) CreateOrUpdatePreparer(ctx context.Context, parameters StaticMember, resourceGroupName string, networkManagerName string, networkGroupName string, staticMemberName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkGroupName": autorest.Encode("path", networkGroupName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "staticMemberName": autorest.Encode("path", staticMemberName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}/staticMembers/{staticMemberName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client StaticMembersClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client StaticMembersClient) CreateOrUpdateResponder(resp *http.Response) (result StaticMember, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a static member. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// networkGroupName - the name of the network group. -// staticMemberName - the name of the static member. -func (client StaticMembersClient) Delete(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, staticMemberName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StaticMembersClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkManagerName, networkGroupName, staticMemberName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.StaticMembersClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "network.StaticMembersClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.StaticMembersClient", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client StaticMembersClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, staticMemberName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkGroupName": autorest.Encode("path", networkGroupName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "staticMemberName": autorest.Encode("path", staticMemberName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}/staticMembers/{staticMemberName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client StaticMembersClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client StaticMembersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified static member. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// networkGroupName - the name of the network group. -// staticMemberName - the name of the static member. -func (client StaticMembersClient) Get(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, staticMemberName string) (result StaticMember, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StaticMembersClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkManagerName, networkGroupName, staticMemberName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.StaticMembersClient", "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.StaticMembersClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.StaticMembersClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client StaticMembersClient) GetPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, staticMemberName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkGroupName": autorest.Encode("path", networkGroupName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "staticMemberName": autorest.Encode("path", staticMemberName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}/staticMembers/{staticMemberName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client StaticMembersClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client StaticMembersClient) GetResponder(resp *http.Response) (result StaticMember, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists the specified static member. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkManagerName - the name of the network manager. -// networkGroupName - the name of the network group. -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -// skipToken - skipToken is only used if a previous operation returned a partial result. If a previous response -// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that -// specifies a starting point to use for subsequent calls. -func (client StaticMembersClient) List(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, top *int32, skipToken string) (result StaticMemberListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StaticMembersClient.List") - defer func() { - sc := -1 - if result.smlr.Response.Response != nil { - sc = result.smlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.StaticMembersClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkManagerName, networkGroupName, top, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "network.StaticMembersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.smlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.StaticMembersClient", "List", resp, "Failure sending request") - return - } - - result.smlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.StaticMembersClient", "List", resp, "Failure responding to request") - return - } - if result.smlr.hasNextLink() && result.smlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client StaticMembersClient) ListPreparer(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, top *int32, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkGroupName": autorest.Encode("path", networkGroupName), - "networkManagerName": autorest.Encode("path", networkManagerName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(skipToken) > 0 { - queryParameters["$skipToken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkManagers/{networkManagerName}/networkGroups/{networkGroupName}/staticMembers", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client StaticMembersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client StaticMembersClient) ListResponder(resp *http.Response) (result StaticMemberListResult, err error) { - err = autorest.Respond( - resp, - 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 StaticMembersClient) listNextResults(ctx context.Context, lastResults StaticMemberListResult) (result StaticMemberListResult, err error) { - req, err := lastResults.staticMemberListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.StaticMembersClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.StaticMembersClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.StaticMembersClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client StaticMembersClient) ListComplete(ctx context.Context, resourceGroupName string, networkManagerName string, networkGroupName string, top *int32, skipToken string) (result StaticMemberListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StaticMembersClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkManagerName, networkGroupName, top, skipToken) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/subnets.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/subnets.go deleted file mode 100644 index 3ef48cbbd0..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/subnets.go +++ /dev/null @@ -1,564 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SubnetsClient is the network Client -type SubnetsClient struct { - BaseClient -} - -// NewSubnetsClient creates an instance of the SubnetsClient client. -func NewSubnetsClient(subscriptionID string) SubnetsClient { - return NewSubnetsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSubnetsClientWithBaseURI creates an instance of the SubnetsClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewSubnetsClientWithBaseURI(baseURI string, subscriptionID string) SubnetsClient { - return SubnetsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a subnet in the specified virtual network. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// subnetName - the name of the subnet. -// subnetParameters - parameters supplied to the create or update subnet operation. -func (client SubnetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet) (result SubnetsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualNetworkName, subnetName, subnetParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client SubnetsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subnetName": autorest.Encode("path", subnetName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - subnetParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}", pathParameters), - autorest.WithJSON(subnetParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client SubnetsClient) CreateOrUpdateSender(req *http.Request) (future SubnetsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client SubnetsClient) CreateOrUpdateResponder(resp *http.Response) (result Subnet, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified subnet. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// subnetName - the name of the subnet. -func (client SubnetsClient) Delete(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) (result SubnetsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualNetworkName, subnetName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client SubnetsClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subnetName": autorest.Encode("path", subnetName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2022-07-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/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client SubnetsClient) DeleteSender(req *http.Request) (future SubnetsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client SubnetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified subnet by virtual network and resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// subnetName - the name of the subnet. -// expand - expands referenced resources. -func (client SubnetsClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (result Subnet, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualNetworkName, subnetName, expand) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client SubnetsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subnetName": autorest.Encode("path", subnetName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2022-07-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/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client SubnetsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client SubnetsClient) GetResponder(resp *http.Response) (result Subnet, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all subnets in a virtual network. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -func (client SubnetsClient) List(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result SubnetListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetsClient.List") - defer func() { - sc := -1 - if result.slr.Response.Response != nil { - sc = result.slr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualNetworkName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.slr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure sending request") - return - } - - result.slr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure responding to request") - return - } - if result.slr.hasNextLink() && result.slr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client SubnetsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName 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 = "2022-07-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/virtualNetworks/{virtualNetworkName}/subnets", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client SubnetsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client SubnetsClient) ListResponder(resp *http.Response) (result SubnetListResult, err error) { - err = autorest.Respond( - resp, - 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 SubnetsClient) listNextResults(ctx context.Context, lastResults SubnetListResult) (result SubnetListResult, err error) { - req, err := lastResults.subnetListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client SubnetsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result SubnetListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualNetworkName) - return -} - -// PrepareNetworkPolicies prepares a subnet by applying network intent policies. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// subnetName - the name of the subnet. -// prepareNetworkPoliciesRequestParameters - parameters supplied to prepare subnet by applying network intent -// policies. -func (client SubnetsClient) PrepareNetworkPolicies(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, prepareNetworkPoliciesRequestParameters PrepareNetworkPoliciesRequest) (result SubnetsPrepareNetworkPoliciesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetsClient.PrepareNetworkPolicies") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PrepareNetworkPoliciesPreparer(ctx, resourceGroupName, virtualNetworkName, subnetName, prepareNetworkPoliciesRequestParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "PrepareNetworkPolicies", nil, "Failure preparing request") - return - } - - result, err = client.PrepareNetworkPoliciesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "PrepareNetworkPolicies", result.Response(), "Failure sending request") - return - } - - return -} - -// PrepareNetworkPoliciesPreparer prepares the PrepareNetworkPolicies request. -func (client SubnetsClient) PrepareNetworkPoliciesPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, prepareNetworkPoliciesRequestParameters PrepareNetworkPoliciesRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subnetName": autorest.Encode("path", subnetName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/PrepareNetworkPolicies", pathParameters), - autorest.WithJSON(prepareNetworkPoliciesRequestParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PrepareNetworkPoliciesSender sends the PrepareNetworkPolicies request. The method will close the -// http.Response Body if it receives an error. -func (client SubnetsClient) PrepareNetworkPoliciesSender(req *http.Request) (future SubnetsPrepareNetworkPoliciesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// PrepareNetworkPoliciesResponder handles the response to the PrepareNetworkPolicies request. The method always -// closes the http.Response Body. -func (client SubnetsClient) PrepareNetworkPoliciesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// UnprepareNetworkPolicies unprepares a subnet by removing network intent policies. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// subnetName - the name of the subnet. -// unprepareNetworkPoliciesRequestParameters - parameters supplied to unprepare subnet to remove network intent -// policies. -func (client SubnetsClient) UnprepareNetworkPolicies(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, unprepareNetworkPoliciesRequestParameters UnprepareNetworkPoliciesRequest) (result SubnetsUnprepareNetworkPoliciesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubnetsClient.UnprepareNetworkPolicies") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UnprepareNetworkPoliciesPreparer(ctx, resourceGroupName, virtualNetworkName, subnetName, unprepareNetworkPoliciesRequestParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "UnprepareNetworkPolicies", nil, "Failure preparing request") - return - } - - result, err = client.UnprepareNetworkPoliciesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "UnprepareNetworkPolicies", result.Response(), "Failure sending request") - return - } - - return -} - -// UnprepareNetworkPoliciesPreparer prepares the UnprepareNetworkPolicies request. -func (client SubnetsClient) UnprepareNetworkPoliciesPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, unprepareNetworkPoliciesRequestParameters UnprepareNetworkPoliciesRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subnetName": autorest.Encode("path", subnetName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/UnprepareNetworkPolicies", pathParameters), - autorest.WithJSON(unprepareNetworkPoliciesRequestParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UnprepareNetworkPoliciesSender sends the UnprepareNetworkPolicies request. The method will close the -// http.Response Body if it receives an error. -func (client SubnetsClient) UnprepareNetworkPoliciesSender(req *http.Request) (future SubnetsUnprepareNetworkPoliciesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UnprepareNetworkPoliciesResponder handles the response to the UnprepareNetworkPolicies request. The method always -// closes the http.Response Body. -func (client SubnetsClient) UnprepareNetworkPoliciesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/subscriptionnetworkmanagerconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/subscriptionnetworkmanagerconnections.go deleted file mode 100644 index 41256f35bd..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/subscriptionnetworkmanagerconnections.go +++ /dev/null @@ -1,393 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// SubscriptionNetworkManagerConnectionsClient is the network Client -type SubscriptionNetworkManagerConnectionsClient struct { - BaseClient -} - -// NewSubscriptionNetworkManagerConnectionsClient creates an instance of the -// SubscriptionNetworkManagerConnectionsClient client. -func NewSubscriptionNetworkManagerConnectionsClient(subscriptionID string) SubscriptionNetworkManagerConnectionsClient { - return NewSubscriptionNetworkManagerConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewSubscriptionNetworkManagerConnectionsClientWithBaseURI creates an instance of the -// SubscriptionNetworkManagerConnectionsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewSubscriptionNetworkManagerConnectionsClientWithBaseURI(baseURI string, subscriptionID string) SubscriptionNetworkManagerConnectionsClient { - return SubscriptionNetworkManagerConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate create a network manager connection on this subscription. -// Parameters: -// parameters - network manager connection to be created/updated. -// networkManagerConnectionName - name for the network manager connection. -func (client SubscriptionNetworkManagerConnectionsClient) CreateOrUpdate(ctx context.Context, parameters ManagerConnection, networkManagerConnectionName string) (result ManagerConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubscriptionNetworkManagerConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, parameters, networkManagerConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubscriptionNetworkManagerConnectionsClient", "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.SubscriptionNetworkManagerConnectionsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubscriptionNetworkManagerConnectionsClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client SubscriptionNetworkManagerConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, parameters ManagerConnection, networkManagerConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerConnectionName": autorest.Encode("path", networkManagerConnectionName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.SystemData = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkManagerConnections/{networkManagerConnectionName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client SubscriptionNetworkManagerConnectionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client SubscriptionNetworkManagerConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result ManagerConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete delete specified connection created by this subscription. -// Parameters: -// networkManagerConnectionName - name for the network manager connection. -func (client SubscriptionNetworkManagerConnectionsClient) Delete(ctx context.Context, networkManagerConnectionName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubscriptionNetworkManagerConnectionsClient.Delete") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, networkManagerConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubscriptionNetworkManagerConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "network.SubscriptionNetworkManagerConnectionsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubscriptionNetworkManagerConnectionsClient", "Delete", resp, "Failure responding to request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client SubscriptionNetworkManagerConnectionsClient) DeletePreparer(ctx context.Context, networkManagerConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerConnectionName": autorest.Encode("path", networkManagerConnectionName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkManagerConnections/{networkManagerConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client SubscriptionNetworkManagerConnectionsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client SubscriptionNetworkManagerConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get get a specified connection created by this subscription. -// Parameters: -// networkManagerConnectionName - name for the network manager connection. -func (client SubscriptionNetworkManagerConnectionsClient) Get(ctx context.Context, networkManagerConnectionName string) (result ManagerConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubscriptionNetworkManagerConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, networkManagerConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubscriptionNetworkManagerConnectionsClient", "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.SubscriptionNetworkManagerConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubscriptionNetworkManagerConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client SubscriptionNetworkManagerConnectionsClient) GetPreparer(ctx context.Context, networkManagerConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkManagerConnectionName": autorest.Encode("path", networkManagerConnectionName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkManagerConnections/{networkManagerConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client SubscriptionNetworkManagerConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client SubscriptionNetworkManagerConnectionsClient) GetResponder(resp *http.Response) (result ManagerConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all network manager connections created by this subscription. -// Parameters: -// top - an optional query parameter which specifies the maximum number of records to be returned by the -// server. -// skipToken - skipToken is only used if a previous operation returned a partial result. If a previous response -// contains a nextLink element, the value of the nextLink element will include a skipToken parameter that -// specifies a starting point to use for subsequent calls. -func (client SubscriptionNetworkManagerConnectionsClient) List(ctx context.Context, top *int32, skipToken string) (result ManagerConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubscriptionNetworkManagerConnectionsClient.List") - defer func() { - sc := -1 - if result.mclr.Response.Response != nil { - sc = result.mclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: top, - Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(20), Chain: nil}, - {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.SubscriptionNetworkManagerConnectionsClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, top, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubscriptionNetworkManagerConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.mclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.SubscriptionNetworkManagerConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.mclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubscriptionNetworkManagerConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.mclr.hasNextLink() && result.mclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client SubscriptionNetworkManagerConnectionsClient) ListPreparer(ctx context.Context, top *int32, skipToken string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(skipToken) > 0 { - queryParameters["$skipToken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkManagerConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client SubscriptionNetworkManagerConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client SubscriptionNetworkManagerConnectionsClient) ListResponder(resp *http.Response) (result ManagerConnectionListResult, err error) { - err = autorest.Respond( - resp, - 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 SubscriptionNetworkManagerConnectionsClient) listNextResults(ctx context.Context, lastResults ManagerConnectionListResult) (result ManagerConnectionListResult, err error) { - req, err := lastResults.managerConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SubscriptionNetworkManagerConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SubscriptionNetworkManagerConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubscriptionNetworkManagerConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client SubscriptionNetworkManagerConnectionsClient) ListComplete(ctx context.Context, top *int32, skipToken string) (result ManagerConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SubscriptionNetworkManagerConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, top, skipToken) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/usages.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/usages.go deleted file mode 100644 index 724cb11578..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/usages.go +++ /dev/null @@ -1,154 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// UsagesClient is the network Client -type UsagesClient struct { - BaseClient -} - -// NewUsagesClient creates an instance of the UsagesClient client. -func NewUsagesClient(subscriptionID string) UsagesClient { - return NewUsagesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewUsagesClientWithBaseURI creates an instance of the UsagesClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewUsagesClientWithBaseURI(baseURI string, subscriptionID string) UsagesClient { - return UsagesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List list network usages for a subscription. -// Parameters: -// location - the location where resource usage is queried. -func (client UsagesClient) List(ctx context.Context, location string) (result UsagesListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/UsagesClient.List") - defer func() { - sc := -1 - if result.ulr.Response.Response != nil { - sc = result.ulr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.NewError("network.UsagesClient", "List", err.Error()) - } - - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, location) - if err != nil { - err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.ulr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure sending request") - return - } - - result.ulr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure responding to request") - return - } - if result.ulr.hasNextLink() && result.ulr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client UsagesClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "location": autorest.Encode("path", location), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/usages", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client UsagesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client UsagesClient) ListResponder(resp *http.Response) (result UsagesListResult, err error) { - err = autorest.Respond( - resp, - 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 UsagesClient) listNextResults(ctx context.Context, lastResults UsagesListResult) (result UsagesListResult, err error) { - req, err := lastResults.usagesListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.UsagesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.UsagesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.UsagesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client UsagesClient) ListComplete(ctx context.Context, location string) (result UsagesListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/UsagesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, location) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/version.go deleted file mode 100644 index 0bc5ef0889..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/version.go +++ /dev/null @@ -1,19 +0,0 @@ -package network - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// UserAgent returns the UserAgent string to use when sending http.Requests. -func UserAgent() string { - return "Azure-SDK-For-Go/" + Version() + " network/2022-07-01" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vipswap.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vipswap.go deleted file mode 100644 index cc1f1ea744..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vipswap.go +++ /dev/null @@ -1,272 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VipSwapClient is the network Client -type VipSwapClient struct { - BaseClient -} - -// NewVipSwapClient creates an instance of the VipSwapClient client. -func NewVipSwapClient(subscriptionID string) VipSwapClient { - return NewVipSwapClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVipSwapClientWithBaseURI creates an instance of the VipSwapClient client using a custom endpoint. Use this when -// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVipSwapClientWithBaseURI(baseURI string, subscriptionID string) VipSwapClient { - return VipSwapClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Create performs vip swap operation on swappable cloud services. -// Parameters: -// groupName - the name of the resource group. -// resourceName - the name of the cloud service. -// parameters - swapResource object where slot type should be the target slot after vip swap for the specified -// cloud service. -func (client VipSwapClient) Create(ctx context.Context, groupName string, resourceName string, parameters SwapResource) (result VipSwapCreateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VipSwapClient.Create") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreatePreparer(ctx, groupName, resourceName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VipSwapClient", "Create", nil, "Failure preparing request") - return - } - - result, err = client.CreateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VipSwapClient", "Create", result.Response(), "Failure sending request") - return - } - - return -} - -// CreatePreparer prepares the Create request. -func (client VipSwapClient) CreatePreparer(ctx context.Context, groupName string, resourceName string, parameters SwapResource) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "groupName": autorest.Encode("path", groupName), - "resourceName": autorest.Encode("path", resourceName), - "singletonResource": autorest.Encode("path", "swap"), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.ID = nil - parameters.Name = nil - parameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Compute/cloudServices/{resourceName}/providers/Microsoft.Network/cloudServiceSlots/{singletonResource}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client VipSwapClient) CreateSender(req *http.Request) (future VipSwapCreateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client VipSwapClient) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the SwapResource which identifies the slot type for the specified cloud service. The slot type on a cloud -// service can either be Staging or Production -// Parameters: -// groupName - the name of the resource group. -// resourceName - the name of the cloud service. -func (client VipSwapClient) Get(ctx context.Context, groupName string, resourceName string) (result SwapResource, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VipSwapClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, groupName, resourceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VipSwapClient", "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.VipSwapClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VipSwapClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VipSwapClient) GetPreparer(ctx context.Context, groupName string, resourceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "groupName": autorest.Encode("path", groupName), - "resourceName": autorest.Encode("path", resourceName), - "singletonResource": autorest.Encode("path", "swap"), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Compute/cloudServices/{resourceName}/providers/Microsoft.Network/cloudServiceSlots/{singletonResource}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VipSwapClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VipSwapClient) GetResponder(resp *http.Response) (result SwapResource, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets the list of SwapResource which identifies the slot type for the specified cloud service. The slot type on -// a cloud service can either be Staging or Production -// Parameters: -// groupName - the name of the resource group. -// resourceName - the name of the cloud service. -func (client VipSwapClient) List(ctx context.Context, groupName string, resourceName string) (result SwapResourceListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VipSwapClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, groupName, resourceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VipSwapClient", "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.VipSwapClient", "List", resp, "Failure sending request") - return - } - - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VipSwapClient", "List", resp, "Failure responding to request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VipSwapClient) ListPreparer(ctx context.Context, groupName string, resourceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "groupName": autorest.Encode("path", groupName), - "resourceName": autorest.Encode("path", resourceName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Compute/cloudServices/{resourceName}/providers/Microsoft.Network/cloudServiceSlots", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VipSwapClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VipSwapClient) ListResponder(resp *http.Response) (result SwapResourceListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualappliances.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualappliances.go deleted file mode 100644 index 97d9fb25a9..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualappliances.go +++ /dev/null @@ -1,593 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualAppliancesClient is the network Client -type VirtualAppliancesClient struct { - BaseClient -} - -// NewVirtualAppliancesClient creates an instance of the VirtualAppliancesClient client. -func NewVirtualAppliancesClient(subscriptionID string) VirtualAppliancesClient { - return NewVirtualAppliancesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualAppliancesClientWithBaseURI creates an instance of the VirtualAppliancesClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewVirtualAppliancesClientWithBaseURI(baseURI string, subscriptionID string) VirtualAppliancesClient { - return VirtualAppliancesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates the specified Network Virtual Appliance. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkVirtualApplianceName - the name of Network Virtual Appliance. -// parameters - parameters supplied to the create or update Network Virtual Appliance. -func (client VirtualAppliancesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, parameters VirtualAppliance) (result VirtualAppliancesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualAppliancesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VirtualAppliancePropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualAppliancePropertiesFormat.VirtualApplianceAsn", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualAppliancePropertiesFormat.VirtualApplianceAsn", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "parameters.VirtualAppliancePropertiesFormat.VirtualApplianceAsn", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualAppliancesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkVirtualApplianceName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualAppliancesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, parameters VirtualAppliance) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkVirtualApplianceName": autorest.Encode("path", networkVirtualApplianceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualAppliancesClient) CreateOrUpdateSender(req *http.Request) (future VirtualAppliancesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualAppliancesClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualAppliance, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified Network Virtual Appliance. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkVirtualApplianceName - the name of Network Virtual Appliance. -func (client VirtualAppliancesClient) Delete(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string) (result VirtualAppliancesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualAppliancesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkVirtualApplianceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualAppliancesClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkVirtualApplianceName": autorest.Encode("path", networkVirtualApplianceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkVirtualAppliances/{networkVirtualApplianceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualAppliancesClient) DeleteSender(req *http.Request) (future VirtualAppliancesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualAppliancesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified Network Virtual Appliance. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkVirtualApplianceName - the name of Network Virtual Appliance. -// expand - expands referenced resources. -func (client VirtualAppliancesClient) Get(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, expand string) (result VirtualAppliance, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualAppliancesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkVirtualApplianceName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "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.VirtualAppliancesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualAppliancesClient) GetPreparer(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkVirtualApplianceName": autorest.Encode("path", networkVirtualApplianceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkVirtualAppliances/{networkVirtualApplianceName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualAppliancesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualAppliancesClient) GetResponder(resp *http.Response) (result VirtualAppliance, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all Network Virtual Appliances in a subscription. -func (client VirtualAppliancesClient) List(ctx context.Context) (result VirtualApplianceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualAppliancesClient.List") - defer func() { - sc := -1 - if result.valr.Response.Response != nil { - sc = result.valr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.valr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "List", resp, "Failure sending request") - return - } - - result.valr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "List", resp, "Failure responding to request") - return - } - if result.valr.hasNextLink() && result.valr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualAppliancesClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkVirtualAppliances", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualAppliancesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualAppliancesClient) ListResponder(resp *http.Response) (result VirtualApplianceListResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualAppliancesClient) listNextResults(ctx context.Context, lastResults VirtualApplianceListResult) (result VirtualApplianceListResult, err error) { - req, err := lastResults.virtualApplianceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualAppliancesClient) ListComplete(ctx context.Context) (result VirtualApplianceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualAppliancesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all Network Virtual Appliances in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client VirtualAppliancesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result VirtualApplianceListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualAppliancesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.valr.Response.Response != nil { - sc = result.valr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.valr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.valr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.valr.hasNextLink() && result.valr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client VirtualAppliancesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkVirtualAppliances", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualAppliancesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client VirtualAppliancesClient) ListByResourceGroupResponder(resp *http.Response) (result VirtualApplianceListResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualAppliancesClient) listByResourceGroupNextResults(ctx context.Context, lastResults VirtualApplianceListResult) (result VirtualApplianceListResult, err error) { - req, err := lastResults.virtualApplianceListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualAppliancesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result VirtualApplianceListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualAppliancesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates a Network Virtual Appliance. -// Parameters: -// resourceGroupName - the resource group name of Network Virtual Appliance. -// networkVirtualApplianceName - the name of Network Virtual Appliance being updated. -// parameters - parameters supplied to Update Network Virtual Appliance Tags. -func (client VirtualAppliancesClient) UpdateTags(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, parameters TagsObject) (result VirtualAppliance, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualAppliancesClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, networkVirtualApplianceName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualAppliancesClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VirtualAppliancesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkVirtualApplianceName": autorest.Encode("path", networkVirtualApplianceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualAppliancesClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VirtualAppliancesClient) UpdateTagsResponder(resp *http.Response) (result VirtualAppliance, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualappliancesites.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualappliancesites.go deleted file mode 100644 index 1a9d266858..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualappliancesites.go +++ /dev/null @@ -1,394 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualApplianceSitesClient is the network Client -type VirtualApplianceSitesClient struct { - BaseClient -} - -// NewVirtualApplianceSitesClient creates an instance of the VirtualApplianceSitesClient client. -func NewVirtualApplianceSitesClient(subscriptionID string) VirtualApplianceSitesClient { - return NewVirtualApplianceSitesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualApplianceSitesClientWithBaseURI creates an instance of the VirtualApplianceSitesClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewVirtualApplianceSitesClientWithBaseURI(baseURI string, subscriptionID string) VirtualApplianceSitesClient { - return VirtualApplianceSitesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates the specified Network Virtual Appliance Site. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkVirtualApplianceName - the name of the Network Virtual Appliance. -// siteName - the name of the site. -// parameters - parameters supplied to the create or update Network Virtual Appliance Site operation. -func (client VirtualApplianceSitesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string, parameters VirtualApplianceSite) (result VirtualApplianceSitesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceSitesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, networkVirtualApplianceName, siteName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSitesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSitesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualApplianceSitesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string, parameters VirtualApplianceSite) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkVirtualApplianceName": autorest.Encode("path", networkVirtualApplianceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "siteName": autorest.Encode("path", siteName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - parameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}/virtualApplianceSites/{siteName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualApplianceSitesClient) CreateOrUpdateSender(req *http.Request) (future VirtualApplianceSitesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualApplianceSitesClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualApplianceSite, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified site from a Virtual Appliance. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkVirtualApplianceName - the name of the Network Virtual Appliance. -// siteName - the name of the site. -func (client VirtualApplianceSitesClient) Delete(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string) (result VirtualApplianceSitesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceSitesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkVirtualApplianceName, siteName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSitesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSitesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualApplianceSitesClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkVirtualApplianceName": autorest.Encode("path", networkVirtualApplianceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "siteName": autorest.Encode("path", siteName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkVirtualAppliances/{networkVirtualApplianceName}/virtualApplianceSites/{siteName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualApplianceSitesClient) DeleteSender(req *http.Request) (future VirtualApplianceSitesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualApplianceSitesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified Virtual Appliance Site. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkVirtualApplianceName - the name of the Network Virtual Appliance. -// siteName - the name of the site. -func (client VirtualApplianceSitesClient) Get(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string) (result VirtualApplianceSite, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceSitesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, networkVirtualApplianceName, siteName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSitesClient", "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.VirtualApplianceSitesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSitesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualApplianceSitesClient) GetPreparer(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkVirtualApplianceName": autorest.Encode("path", networkVirtualApplianceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "siteName": autorest.Encode("path", siteName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkVirtualAppliances/{networkVirtualApplianceName}/virtualApplianceSites/{siteName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualApplianceSitesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualApplianceSitesClient) GetResponder(resp *http.Response) (result VirtualApplianceSite, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all Network Virtual Appliance Sites in a Network Virtual Appliance resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkVirtualApplianceName - the name of the Network Virtual Appliance. -func (client VirtualApplianceSitesClient) List(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string) (result VirtualApplianceSiteListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceSitesClient.List") - defer func() { - sc := -1 - if result.vaslr.Response.Response != nil { - sc = result.vaslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, networkVirtualApplianceName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSitesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vaslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSitesClient", "List", resp, "Failure sending request") - return - } - - result.vaslr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSitesClient", "List", resp, "Failure responding to request") - return - } - if result.vaslr.hasNextLink() && result.vaslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualApplianceSitesClient) ListPreparer(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "networkVirtualApplianceName": autorest.Encode("path", networkVirtualApplianceName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/networkVirtualAppliances/{networkVirtualApplianceName}/virtualApplianceSites", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualApplianceSitesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualApplianceSitesClient) ListResponder(resp *http.Response) (result VirtualApplianceSiteListResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualApplianceSitesClient) listNextResults(ctx context.Context, lastResults VirtualApplianceSiteListResult) (result VirtualApplianceSiteListResult, err error) { - req, err := lastResults.virtualApplianceSiteListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualApplianceSitesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualApplianceSitesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSitesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualApplianceSitesClient) ListComplete(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string) (result VirtualApplianceSiteListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceSitesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, networkVirtualApplianceName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualapplianceskus.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualapplianceskus.go deleted file mode 100644 index 3da40524df..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualapplianceskus.go +++ /dev/null @@ -1,219 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualApplianceSkusClient is the network Client -type VirtualApplianceSkusClient struct { - BaseClient -} - -// NewVirtualApplianceSkusClient creates an instance of the VirtualApplianceSkusClient client. -func NewVirtualApplianceSkusClient(subscriptionID string) VirtualApplianceSkusClient { - return NewVirtualApplianceSkusClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualApplianceSkusClientWithBaseURI creates an instance of the VirtualApplianceSkusClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewVirtualApplianceSkusClientWithBaseURI(baseURI string, subscriptionID string) VirtualApplianceSkusClient { - return VirtualApplianceSkusClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get retrieves a single available sku for network virtual appliance. -// Parameters: -// skuName - name of the Sku. -func (client VirtualApplianceSkusClient) Get(ctx context.Context, skuName string) (result VirtualApplianceSku, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceSkusClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, skuName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSkusClient", "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.VirtualApplianceSkusClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSkusClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualApplianceSkusClient) GetPreparer(ctx context.Context, skuName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "skuName": autorest.Encode("path", skuName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkVirtualApplianceSkus/{skuName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualApplianceSkusClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualApplianceSkusClient) GetResponder(resp *http.Response) (result VirtualApplianceSku, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List list all SKUs available for a virtual appliance. -func (client VirtualApplianceSkusClient) List(ctx context.Context) (result VirtualApplianceSkuListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceSkusClient.List") - defer func() { - sc := -1 - if result.vaslr.Response.Response != nil { - sc = result.vaslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSkusClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vaslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSkusClient", "List", resp, "Failure sending request") - return - } - - result.vaslr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSkusClient", "List", resp, "Failure responding to request") - return - } - if result.vaslr.hasNextLink() && result.vaslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualApplianceSkusClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkVirtualApplianceSkus", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualApplianceSkusClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualApplianceSkusClient) ListResponder(resp *http.Response) (result VirtualApplianceSkuListResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualApplianceSkusClient) listNextResults(ctx context.Context, lastResults VirtualApplianceSkuListResult) (result VirtualApplianceSkuListResult, err error) { - req, err := lastResults.virtualApplianceSkuListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualApplianceSkusClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualApplianceSkusClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualApplianceSkusClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualApplianceSkusClient) ListComplete(ctx context.Context) (result VirtualApplianceSkuListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualApplianceSkusClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubbgpconnection.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubbgpconnection.go deleted file mode 100644 index 766d331597..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubbgpconnection.go +++ /dev/null @@ -1,289 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualHubBgpConnectionClient is the network Client -type VirtualHubBgpConnectionClient struct { - BaseClient -} - -// NewVirtualHubBgpConnectionClient creates an instance of the VirtualHubBgpConnectionClient client. -func NewVirtualHubBgpConnectionClient(subscriptionID string) VirtualHubBgpConnectionClient { - return NewVirtualHubBgpConnectionClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualHubBgpConnectionClientWithBaseURI creates an instance of the VirtualHubBgpConnectionClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewVirtualHubBgpConnectionClientWithBaseURI(baseURI string, subscriptionID string) VirtualHubBgpConnectionClient { - return VirtualHubBgpConnectionClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a VirtualHubBgpConnection resource if it doesn't exist else updates the existing -// VirtualHubBgpConnection. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// connectionName - the name of the connection. -// parameters - parameters of Bgp connection. -func (client VirtualHubBgpConnectionClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, parameters BgpConnection) (result VirtualHubBgpConnectionCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubBgpConnectionClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.BgpConnectionProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.BgpConnectionProperties.PeerAsn", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.BgpConnectionProperties.PeerAsn", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "parameters.BgpConnectionProperties.PeerAsn", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualHubBgpConnectionClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualHubName, connectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualHubBgpConnectionClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string, parameters BgpConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - parameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/bgpConnections/{connectionName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubBgpConnectionClient) CreateOrUpdateSender(req *http.Request) (future VirtualHubBgpConnectionCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualHubBgpConnectionClient) CreateOrUpdateResponder(resp *http.Response) (result BgpConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a VirtualHubBgpConnection. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHubBgpConnection. -// virtualHubName - the name of the VirtualHub. -// connectionName - the name of the connection. -func (client VirtualHubBgpConnectionClient) Delete(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (result VirtualHubBgpConnectionDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubBgpConnectionClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualHubName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualHubBgpConnectionClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/bgpConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubBgpConnectionClient) DeleteSender(req *http.Request) (future VirtualHubBgpConnectionDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualHubBgpConnectionClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a Virtual Hub Bgp Connection. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// connectionName - the name of the connection. -func (client VirtualHubBgpConnectionClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (result BgpConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubBgpConnectionClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualHubName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionClient", "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.VirtualHubBgpConnectionClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualHubBgpConnectionClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/bgpConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubBgpConnectionClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualHubBgpConnectionClient) GetResponder(resp *http.Response) (result BgpConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubbgpconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubbgpconnections.go deleted file mode 100644 index 430cb12af9..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubbgpconnections.go +++ /dev/null @@ -1,312 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualHubBgpConnectionsClient is the network Client -type VirtualHubBgpConnectionsClient struct { - BaseClient -} - -// NewVirtualHubBgpConnectionsClient creates an instance of the VirtualHubBgpConnectionsClient client. -func NewVirtualHubBgpConnectionsClient(subscriptionID string) VirtualHubBgpConnectionsClient { - return NewVirtualHubBgpConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualHubBgpConnectionsClientWithBaseURI creates an instance of the VirtualHubBgpConnectionsClient client using -// a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewVirtualHubBgpConnectionsClientWithBaseURI(baseURI string, subscriptionID string) VirtualHubBgpConnectionsClient { - return VirtualHubBgpConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List retrieves the details of all VirtualHubBgpConnections. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -func (client VirtualHubBgpConnectionsClient) List(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListVirtualHubBgpConnectionResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubBgpConnectionsClient.List") - defer func() { - sc := -1 - if result.lvhbcr.Response.Response != nil { - sc = result.lvhbcr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualHubName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lvhbcr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.lvhbcr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.lvhbcr.hasNextLink() && result.lvhbcr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualHubBgpConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/bgpConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubBgpConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualHubBgpConnectionsClient) ListResponder(resp *http.Response) (result ListVirtualHubBgpConnectionResults, err error) { - err = autorest.Respond( - resp, - 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 VirtualHubBgpConnectionsClient) listNextResults(ctx context.Context, lastResults ListVirtualHubBgpConnectionResults) (result ListVirtualHubBgpConnectionResults, err error) { - req, err := lastResults.listVirtualHubBgpConnectionResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualHubBgpConnectionsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListVirtualHubBgpConnectionResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubBgpConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualHubName) - return -} - -// ListAdvertisedRoutes retrieves a list of routes the virtual hub bgp connection is advertising to the specified peer. -// Parameters: -// resourceGroupName - the name of the resource group. -// hubName - the name of the virtual hub. -// connectionName - the name of the virtual hub bgp connection. -func (client VirtualHubBgpConnectionsClient) ListAdvertisedRoutes(ctx context.Context, resourceGroupName string, hubName string, connectionName string) (result VirtualHubBgpConnectionsListAdvertisedRoutesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubBgpConnectionsClient.ListAdvertisedRoutes") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAdvertisedRoutesPreparer(ctx, resourceGroupName, hubName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsClient", "ListAdvertisedRoutes", nil, "Failure preparing request") - return - } - - result, err = client.ListAdvertisedRoutesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsClient", "ListAdvertisedRoutes", result.Response(), "Failure sending request") - return - } - - return -} - -// ListAdvertisedRoutesPreparer prepares the ListAdvertisedRoutes request. -func (client VirtualHubBgpConnectionsClient) ListAdvertisedRoutesPreparer(ctx context.Context, resourceGroupName string, hubName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "hubName": autorest.Encode("path", hubName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/virtualHubs/{hubName}/bgpConnections/{connectionName}/advertisedRoutes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAdvertisedRoutesSender sends the ListAdvertisedRoutes request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubBgpConnectionsClient) ListAdvertisedRoutesSender(req *http.Request) (future VirtualHubBgpConnectionsListAdvertisedRoutesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListAdvertisedRoutesResponder handles the response to the ListAdvertisedRoutes request. The method always -// closes the http.Response Body. -func (client VirtualHubBgpConnectionsClient) ListAdvertisedRoutesResponder(resp *http.Response) (result PeerRouteList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListLearnedRoutes retrieves a list of routes the virtual hub bgp connection has learned. -// Parameters: -// resourceGroupName - the name of the resource group. -// hubName - the name of the virtual hub. -// connectionName - the name of the virtual hub bgp connection. -func (client VirtualHubBgpConnectionsClient) ListLearnedRoutes(ctx context.Context, resourceGroupName string, hubName string, connectionName string) (result VirtualHubBgpConnectionsListLearnedRoutesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubBgpConnectionsClient.ListLearnedRoutes") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListLearnedRoutesPreparer(ctx, resourceGroupName, hubName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsClient", "ListLearnedRoutes", nil, "Failure preparing request") - return - } - - result, err = client.ListLearnedRoutesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubBgpConnectionsClient", "ListLearnedRoutes", result.Response(), "Failure sending request") - return - } - - return -} - -// ListLearnedRoutesPreparer prepares the ListLearnedRoutes request. -func (client VirtualHubBgpConnectionsClient) ListLearnedRoutesPreparer(ctx context.Context, resourceGroupName string, hubName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "hubName": autorest.Encode("path", hubName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/virtualHubs/{hubName}/bgpConnections/{connectionName}/learnedRoutes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListLearnedRoutesSender sends the ListLearnedRoutes request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubBgpConnectionsClient) ListLearnedRoutesSender(req *http.Request) (future VirtualHubBgpConnectionsListLearnedRoutesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListLearnedRoutesResponder handles the response to the ListLearnedRoutes request. The method always -// closes the http.Response Body. -func (client VirtualHubBgpConnectionsClient) ListLearnedRoutesResponder(resp *http.Response) (result PeerRouteList, err error) { - err = autorest.Respond( - resp, - 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/services/network/mgmt/2022-07-01/network/virtualhubipconfiguration.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubipconfiguration.go deleted file mode 100644 index c6c84931f2..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubipconfiguration.go +++ /dev/null @@ -1,413 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualHubIPConfigurationClient is the network Client -type VirtualHubIPConfigurationClient struct { - BaseClient -} - -// NewVirtualHubIPConfigurationClient creates an instance of the VirtualHubIPConfigurationClient client. -func NewVirtualHubIPConfigurationClient(subscriptionID string) VirtualHubIPConfigurationClient { - return NewVirtualHubIPConfigurationClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualHubIPConfigurationClientWithBaseURI creates an instance of the VirtualHubIPConfigurationClient client -// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign -// clouds, Azure stack). -func NewVirtualHubIPConfigurationClientWithBaseURI(baseURI string, subscriptionID string) VirtualHubIPConfigurationClient { - return VirtualHubIPConfigurationClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a VirtualHubIpConfiguration resource if it doesn't exist else updates the existing -// VirtualHubIpConfiguration. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// IPConfigName - the name of the ipconfig. -// parameters - hub Ip Configuration parameters. -func (client VirtualHubIPConfigurationClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, IPConfigName string, parameters HubIPConfiguration) (result VirtualHubIPConfigurationCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubIPConfigurationClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.HubIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.HubIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.HubIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.HubIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.HubIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.HubIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, - }}, - {Target: "parameters.HubIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.ServicePublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - {Target: "parameters.HubIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.LinkedPublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualHubIPConfigurationClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualHubName, IPConfigName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualHubIPConfigurationClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, IPConfigName string, parameters HubIPConfiguration) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipConfigName": autorest.Encode("path", IPConfigName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - parameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/ipConfigurations/{ipConfigName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubIPConfigurationClient) CreateOrUpdateSender(req *http.Request) (future VirtualHubIPConfigurationCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualHubIPConfigurationClient) CreateOrUpdateResponder(resp *http.Response) (result HubIPConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a VirtualHubIpConfiguration. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHubBgpConnection. -// virtualHubName - the name of the VirtualHub. -// IPConfigName - the name of the ipconfig. -func (client VirtualHubIPConfigurationClient) Delete(ctx context.Context, resourceGroupName string, virtualHubName string, IPConfigName string) (result VirtualHubIPConfigurationDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubIPConfigurationClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualHubName, IPConfigName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualHubIPConfigurationClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, IPConfigName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipConfigName": autorest.Encode("path", IPConfigName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/ipConfigurations/{ipConfigName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubIPConfigurationClient) DeleteSender(req *http.Request) (future VirtualHubIPConfigurationDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualHubIPConfigurationClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a Virtual Hub Ip configuration. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// IPConfigName - the name of the ipconfig. -func (client VirtualHubIPConfigurationClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, IPConfigName string) (result HubIPConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubIPConfigurationClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualHubName, IPConfigName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationClient", "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.VirtualHubIPConfigurationClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualHubIPConfigurationClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, IPConfigName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "ipConfigName": autorest.Encode("path", IPConfigName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/ipConfigurations/{ipConfigName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubIPConfigurationClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualHubIPConfigurationClient) GetResponder(resp *http.Response) (result HubIPConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List retrieves the details of all VirtualHubIpConfigurations. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -func (client VirtualHubIPConfigurationClient) List(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListVirtualHubIPConfigurationResultsPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubIPConfigurationClient.List") - defer func() { - sc := -1 - if result.lvhicr.Response.Response != nil { - sc = result.lvhicr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualHubName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lvhicr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationClient", "List", resp, "Failure sending request") - return - } - - result.lvhicr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationClient", "List", resp, "Failure responding to request") - return - } - if result.lvhicr.hasNextLink() && result.lvhicr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualHubIPConfigurationClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/ipConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubIPConfigurationClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualHubIPConfigurationClient) ListResponder(resp *http.Response) (result ListVirtualHubIPConfigurationResults, err error) { - err = autorest.Respond( - resp, - 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 VirtualHubIPConfigurationClient) listNextResults(ctx context.Context, lastResults ListVirtualHubIPConfigurationResults) (result ListVirtualHubIPConfigurationResults, err error) { - req, err := lastResults.listVirtualHubIPConfigurationResultsPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubIPConfigurationClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualHubIPConfigurationClient) ListComplete(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListVirtualHubIPConfigurationResultsIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubIPConfigurationClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualHubName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubroutetablev2s.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubroutetablev2s.go deleted file mode 100644 index 210a170e34..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubroutetablev2s.go +++ /dev/null @@ -1,394 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualHubRouteTableV2sClient is the network Client -type VirtualHubRouteTableV2sClient struct { - BaseClient -} - -// NewVirtualHubRouteTableV2sClient creates an instance of the VirtualHubRouteTableV2sClient client. -func NewVirtualHubRouteTableV2sClient(subscriptionID string) VirtualHubRouteTableV2sClient { - return NewVirtualHubRouteTableV2sClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualHubRouteTableV2sClientWithBaseURI creates an instance of the VirtualHubRouteTableV2sClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewVirtualHubRouteTableV2sClientWithBaseURI(baseURI string, subscriptionID string) VirtualHubRouteTableV2sClient { - return VirtualHubRouteTableV2sClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a VirtualHubRouteTableV2 resource if it doesn't exist else updates the existing -// VirtualHubRouteTableV2. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// routeTableName - the name of the VirtualHubRouteTableV2. -// virtualHubRouteTableV2Parameters - parameters supplied to create or update VirtualHubRouteTableV2. -func (client VirtualHubRouteTableV2sClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, virtualHubRouteTableV2Parameters VirtualHubRouteTableV2) (result VirtualHubRouteTableV2sCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubRouteTableV2sClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualHubName, routeTableName, virtualHubRouteTableV2Parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualHubRouteTableV2sClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string, virtualHubRouteTableV2Parameters VirtualHubRouteTableV2) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - virtualHubRouteTableV2Parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/routeTables/{routeTableName}", pathParameters), - autorest.WithJSON(virtualHubRouteTableV2Parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubRouteTableV2sClient) CreateOrUpdateSender(req *http.Request) (future VirtualHubRouteTableV2sCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualHubRouteTableV2sClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualHubRouteTableV2, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a VirtualHubRouteTableV2. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHubRouteTableV2. -// virtualHubName - the name of the VirtualHub. -// routeTableName - the name of the VirtualHubRouteTableV2. -func (client VirtualHubRouteTableV2sClient) Delete(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string) (result VirtualHubRouteTableV2sDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubRouteTableV2sClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualHubName, routeTableName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualHubRouteTableV2sClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/routeTables/{routeTableName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubRouteTableV2sClient) DeleteSender(req *http.Request) (future VirtualHubRouteTableV2sDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualHubRouteTableV2sClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a VirtualHubRouteTableV2. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHubRouteTableV2. -// virtualHubName - the name of the VirtualHub. -// routeTableName - the name of the VirtualHubRouteTableV2. -func (client VirtualHubRouteTableV2sClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string) (result VirtualHubRouteTableV2, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubRouteTableV2sClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualHubName, routeTableName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sClient", "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.VirtualHubRouteTableV2sClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualHubRouteTableV2sClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, routeTableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "routeTableName": autorest.Encode("path", routeTableName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/routeTables/{routeTableName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubRouteTableV2sClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualHubRouteTableV2sClient) GetResponder(resp *http.Response) (result VirtualHubRouteTableV2, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List retrieves the details of all VirtualHubRouteTableV2s. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -func (client VirtualHubRouteTableV2sClient) List(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListVirtualHubRouteTableV2sResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubRouteTableV2sClient.List") - defer func() { - sc := -1 - if result.lvhrtvr.Response.Response != nil { - sc = result.lvhrtvr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualHubName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lvhrtvr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sClient", "List", resp, "Failure sending request") - return - } - - result.lvhrtvr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sClient", "List", resp, "Failure responding to request") - return - } - if result.lvhrtvr.hasNextLink() && result.lvhrtvr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualHubRouteTableV2sClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}/routeTables", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubRouteTableV2sClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualHubRouteTableV2sClient) ListResponder(resp *http.Response) (result ListVirtualHubRouteTableV2sResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualHubRouteTableV2sClient) listNextResults(ctx context.Context, lastResults ListVirtualHubRouteTableV2sResult) (result ListVirtualHubRouteTableV2sResult, err error) { - req, err := lastResults.listVirtualHubRouteTableV2sResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubRouteTableV2sClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualHubRouteTableV2sClient) ListComplete(ctx context.Context, resourceGroupName string, virtualHubName string) (result ListVirtualHubRouteTableV2sResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubRouteTableV2sClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualHubName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubs.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubs.go deleted file mode 100644 index 5ca1619791..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualhubs.go +++ /dev/null @@ -1,840 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualHubsClient is the network Client -type VirtualHubsClient struct { - BaseClient -} - -// NewVirtualHubsClient creates an instance of the VirtualHubsClient client. -func NewVirtualHubsClient(subscriptionID string) VirtualHubsClient { - return NewVirtualHubsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualHubsClientWithBaseURI creates an instance of the VirtualHubsClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVirtualHubsClientWithBaseURI(baseURI string, subscriptionID string) VirtualHubsClient { - return VirtualHubsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a VirtualHub resource if it doesn't exist else updates the existing VirtualHub. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// virtualHubParameters - parameters supplied to create or update VirtualHub. -func (client VirtualHubsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualHubName string, virtualHubParameters VirtualHub) (result VirtualHubsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: virtualHubParameters, - Constraints: []validation.Constraint{{Target: "virtualHubParameters.VirtualHubProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "virtualHubParameters.VirtualHubProperties.VirtualRouterAsn", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "virtualHubParameters.VirtualHubProperties.VirtualRouterAsn", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "virtualHubParameters.VirtualHubProperties.VirtualRouterAsn", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - {Target: "virtualHubParameters.VirtualHubProperties.VirtualRouterAutoScaleConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "virtualHubParameters.VirtualHubProperties.VirtualRouterAutoScaleConfiguration.MinCapacity", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "virtualHubParameters.VirtualHubProperties.VirtualRouterAutoScaleConfiguration.MinCapacity", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualHubsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualHubName, virtualHubParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualHubsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualHubName string, virtualHubParameters VirtualHub) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - virtualHubParameters.Etag = nil - virtualHubParameters.Kind = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}", pathParameters), - autorest.WithJSON(virtualHubParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) CreateOrUpdateSender(req *http.Request) (future VirtualHubsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualHub, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a VirtualHub. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -func (client VirtualHubsClient) Delete(ctx context.Context, resourceGroupName string, virtualHubName string) (result VirtualHubsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualHubName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualHubsClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) DeleteSender(req *http.Request) (future VirtualHubsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a VirtualHub. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -func (client VirtualHubsClient) Get(ctx context.Context, resourceGroupName string, virtualHubName string) (result VirtualHub, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualHubName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "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.VirtualHubsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualHubsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualHubName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-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/virtualHubs/{virtualHubName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) GetResponder(resp *http.Response) (result VirtualHub, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetEffectiveVirtualHubRoutes gets the effective routes configured for the Virtual Hub resource or the specified -// resource . -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// effectiveRoutesParameters - parameters supplied to get the effective routes for a specific resource. -func (client VirtualHubsClient) GetEffectiveVirtualHubRoutes(ctx context.Context, resourceGroupName string, virtualHubName string, effectiveRoutesParameters *EffectiveRoutesParameters) (result VirtualHubsGetEffectiveVirtualHubRoutesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.GetEffectiveVirtualHubRoutes") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetEffectiveVirtualHubRoutesPreparer(ctx, resourceGroupName, virtualHubName, effectiveRoutesParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "GetEffectiveVirtualHubRoutes", nil, "Failure preparing request") - return - } - - result, err = client.GetEffectiveVirtualHubRoutesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "GetEffectiveVirtualHubRoutes", result.Response(), "Failure sending request") - return - } - - return -} - -// GetEffectiveVirtualHubRoutesPreparer prepares the GetEffectiveVirtualHubRoutes request. -func (client VirtualHubsClient) GetEffectiveVirtualHubRoutesPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, effectiveRoutesParameters *EffectiveRoutesParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/effectiveRoutes", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if effectiveRoutesParameters != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(effectiveRoutesParameters)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetEffectiveVirtualHubRoutesSender sends the GetEffectiveVirtualHubRoutes request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) GetEffectiveVirtualHubRoutesSender(req *http.Request) (future VirtualHubsGetEffectiveVirtualHubRoutesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetEffectiveVirtualHubRoutesResponder handles the response to the GetEffectiveVirtualHubRoutes request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) GetEffectiveVirtualHubRoutesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// GetInboundRoutes gets the inbound routes configured for the Virtual Hub on a particular connection. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// getInboundRoutesParameters - parameters supplied to get the inbound routes for a connection resource. -func (client VirtualHubsClient) GetInboundRoutes(ctx context.Context, resourceGroupName string, virtualHubName string, getInboundRoutesParameters GetInboundRoutesParameters) (result VirtualHubsGetInboundRoutesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.GetInboundRoutes") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetInboundRoutesPreparer(ctx, resourceGroupName, virtualHubName, getInboundRoutesParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "GetInboundRoutes", nil, "Failure preparing request") - return - } - - result, err = client.GetInboundRoutesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "GetInboundRoutes", result.Response(), "Failure sending request") - return - } - - return -} - -// GetInboundRoutesPreparer prepares the GetInboundRoutes request. -func (client VirtualHubsClient) GetInboundRoutesPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, getInboundRoutesParameters GetInboundRoutesParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/inboundRoutes", pathParameters), - autorest.WithJSON(getInboundRoutesParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetInboundRoutesSender sends the GetInboundRoutes request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) GetInboundRoutesSender(req *http.Request) (future VirtualHubsGetInboundRoutesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetInboundRoutesResponder handles the response to the GetInboundRoutes request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) GetInboundRoutesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// GetOutboundRoutes gets the outbound routes configured for the Virtual Hub on a particular connection. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// getOutboundRoutesParameters - parameters supplied to get the outbound routes for a connection resource. -func (client VirtualHubsClient) GetOutboundRoutes(ctx context.Context, resourceGroupName string, virtualHubName string, getOutboundRoutesParameters GetOutboundRoutesParameters) (result VirtualHubsGetOutboundRoutesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.GetOutboundRoutes") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetOutboundRoutesPreparer(ctx, resourceGroupName, virtualHubName, getOutboundRoutesParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "GetOutboundRoutes", nil, "Failure preparing request") - return - } - - result, err = client.GetOutboundRoutesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "GetOutboundRoutes", result.Response(), "Failure sending request") - return - } - - return -} - -// GetOutboundRoutesPreparer prepares the GetOutboundRoutes request. -func (client VirtualHubsClient) GetOutboundRoutesPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, getOutboundRoutesParameters GetOutboundRoutesParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/outboundRoutes", pathParameters), - autorest.WithJSON(getOutboundRoutesParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetOutboundRoutesSender sends the GetOutboundRoutes request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) GetOutboundRoutesSender(req *http.Request) (future VirtualHubsGetOutboundRoutesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetOutboundRoutesResponder handles the response to the GetOutboundRoutes request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) GetOutboundRoutesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// List lists all the VirtualHubs in a subscription. -func (client VirtualHubsClient) List(ctx context.Context) (result ListVirtualHubsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.List") - defer func() { - sc := -1 - if result.lvhr.Response.Response != nil { - sc = result.lvhr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lvhr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "List", resp, "Failure sending request") - return - } - - result.lvhr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "List", resp, "Failure responding to request") - return - } - if result.lvhr.hasNextLink() && result.lvhr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualHubsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualHubs", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) ListResponder(resp *http.Response) (result ListVirtualHubsResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualHubsClient) listNextResults(ctx context.Context, lastResults ListVirtualHubsResult) (result ListVirtualHubsResult, err error) { - req, err := lastResults.listVirtualHubsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualHubsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualHubsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualHubsClient) ListComplete(ctx context.Context) (result ListVirtualHubsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all the VirtualHubs in a resource group. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -func (client VirtualHubsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListVirtualHubsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.lvhr.Response.Response != nil { - sc = result.lvhr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.lvhr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.lvhr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.lvhr.hasNextLink() && result.lvhr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client VirtualHubsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/virtualHubs", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) ListByResourceGroupResponder(resp *http.Response) (result ListVirtualHubsResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualHubsClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListVirtualHubsResult) (result ListVirtualHubsResult, err error) { - req, err := lastResults.listVirtualHubsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualHubsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualHubsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualHubsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListVirtualHubsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates VirtualHub tags. -// Parameters: -// resourceGroupName - the resource group name of the VirtualHub. -// virtualHubName - the name of the VirtualHub. -// virtualHubParameters - parameters supplied to update VirtualHub tags. -func (client VirtualHubsClient) UpdateTags(ctx context.Context, resourceGroupName string, virtualHubName string, virtualHubParameters TagsObject) (result VirtualHub, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualHubsClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, virtualHubName, virtualHubParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualHubsClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VirtualHubsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, virtualHubName string, virtualHubParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualHubName": autorest.Encode("path", virtualHubName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}", pathParameters), - autorest.WithJSON(virtualHubParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualHubsClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VirtualHubsClient) UpdateTagsResponder(resp *http.Response) (result VirtualHub, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworkgatewayconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworkgatewayconnections.go deleted file mode 100644 index 44549b8b8f..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworkgatewayconnections.go +++ /dev/null @@ -1,1095 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualNetworkGatewayConnectionsClient is the network Client -type VirtualNetworkGatewayConnectionsClient struct { - BaseClient -} - -// NewVirtualNetworkGatewayConnectionsClient creates an instance of the VirtualNetworkGatewayConnectionsClient client. -func NewVirtualNetworkGatewayConnectionsClient(subscriptionID string) VirtualNetworkGatewayConnectionsClient { - return NewVirtualNetworkGatewayConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualNetworkGatewayConnectionsClientWithBaseURI creates an instance of the -// VirtualNetworkGatewayConnectionsClient client using a custom endpoint. Use this when interacting with an Azure -// cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVirtualNetworkGatewayConnectionsClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworkGatewayConnectionsClient { - return VirtualNetworkGatewayConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a virtual network gateway connection in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway connection. -// parameters - parameters supplied to the create or update virtual network gateway connection operation. -func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection) (result VirtualNetworkGatewayConnectionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.BgpSettings", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway1.VirtualNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway1.VirtualNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway1.VirtualNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.InclusiveMinimum, Rule: int64(0), 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.BgpSettings", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway2.VirtualNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway2.VirtualNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway2.VirtualNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.InclusiveMinimum, Rule: int64(0), 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.BgpSettings", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.LocalNetworkGateway2.LocalNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.LocalNetworkGateway2.LocalNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.LocalNetworkGateway2.LocalNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworkGatewayConnectionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkGatewayConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified virtual network Gateway connection. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway connection. -func (client VirtualNetworkGatewayConnectionsClient) Delete(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (result VirtualNetworkGatewayConnectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualNetworkGatewayConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2022-07-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/connections/{virtualNetworkGatewayConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) DeleteSender(req *http.Request) (future VirtualNetworkGatewayConnectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified virtual network gateway connection by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway connection. -func (client VirtualNetworkGatewayConnectionsClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (result VirtualNetworkGatewayConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualNetworkGatewayConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2022-07-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/connections/{virtualNetworkGatewayConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) GetResponder(resp *http.Response) (result VirtualNetworkGatewayConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetIkeSas lists IKE Security Associations for the virtual network gateway connection in the specified resource -// group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway Connection. -func (client VirtualNetworkGatewayConnectionsClient) GetIkeSas(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (result VirtualNetworkGatewayConnectionsGetIkeSasFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.GetIkeSas") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetIkeSasPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetIkeSas", nil, "Failure preparing request") - return - } - - result, err = client.GetIkeSasSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetIkeSas", result.Response(), "Failure sending request") - return - } - - return -} - -// GetIkeSasPreparer prepares the GetIkeSas request. -func (client VirtualNetworkGatewayConnectionsClient) GetIkeSasPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2022-07-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/connections/{virtualNetworkGatewayConnectionName}/getikesas", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetIkeSasSender sends the GetIkeSas request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) GetIkeSasSender(req *http.Request) (future VirtualNetworkGatewayConnectionsGetIkeSasFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetIkeSasResponder handles the response to the GetIkeSas request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) GetIkeSasResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetSharedKey the Get VirtualNetworkGatewayConnectionSharedKey operation retrieves information about the specified -// virtual network gateway connection shared key through Network resource provider. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the virtual network gateway connection shared key name. -func (client VirtualNetworkGatewayConnectionsClient) GetSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (result ConnectionSharedKey, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.GetSharedKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetSharedKeyPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", resp, "Failure sending request") - return - } - - result, err = client.GetSharedKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", resp, "Failure responding to request") - return - } - - return -} - -// GetSharedKeyPreparer prepares the GetSharedKey request. -func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeyPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2022-07-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/connections/{virtualNetworkGatewayConnectionName}/sharedkey", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSharedKeySender sends the GetSharedKey request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetSharedKeyResponder handles the response to the GetSharedKey request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeyResponder(resp *http.Response) (result ConnectionSharedKey, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List the List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections -// created. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client VirtualNetworkGatewayConnectionsClient) List(ctx context.Context, resourceGroupName string) (result VirtualNetworkGatewayConnectionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.List") - defer func() { - sc := -1 - if result.vngclr.Response.Response != nil { - sc = result.vngclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vngclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure sending request") - return - } - - result.vngclr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure responding to request") - return - } - if result.vngclr.hasNextLink() && result.vngclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualNetworkGatewayConnectionsClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/connections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) ListResponder(resp *http.Response) (result VirtualNetworkGatewayConnectionListResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualNetworkGatewayConnectionsClient) listNextResults(ctx context.Context, lastResults VirtualNetworkGatewayConnectionListResult) (result VirtualNetworkGatewayConnectionListResult, err error) { - req, err := lastResults.virtualNetworkGatewayConnectionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworkGatewayConnectionsClient) ListComplete(ctx context.Context, resourceGroupName string) (result VirtualNetworkGatewayConnectionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ResetConnection resets the virtual network gateway connection specified. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway Connection. -func (client VirtualNetworkGatewayConnectionsClient) ResetConnection(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (result VirtualNetworkGatewayConnectionsResetConnectionFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.ResetConnection") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ResetConnectionPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetConnection", nil, "Failure preparing request") - return - } - - result, err = client.ResetConnectionSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetConnection", result.Response(), "Failure sending request") - return - } - - return -} - -// ResetConnectionPreparer prepares the ResetConnection request. -func (client VirtualNetworkGatewayConnectionsClient) ResetConnectionPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2022-07-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/connections/{virtualNetworkGatewayConnectionName}/resetconnection", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ResetConnectionSender sends the ResetConnection request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) ResetConnectionSender(req *http.Request) (future VirtualNetworkGatewayConnectionsResetConnectionFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ResetConnectionResponder handles the response to the ResetConnection request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) ResetConnectionResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the virtual network gateway connection reset shared key Name. -// parameters - parameters supplied to the begin reset virtual network gateway connection shared key operation -// through network resource provider. -func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey) (result VirtualNetworkGatewayConnectionsResetSharedKeyFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.ResetSharedKey") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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: int64(128), Chain: nil}, - {Target: "parameters.KeyLength", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", err.Error()) - } - - req, err := client.ResetSharedKeyPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", nil, "Failure preparing request") - return - } - - result, err = client.ResetSharedKeySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", result.Response(), "Failure sending request") - return - } - - return -} - -// ResetSharedKeyPreparer prepares the ResetSharedKey request. -func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey/reset", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ResetSharedKeySender sends the ResetSharedKey request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeySender(req *http.Request) (future VirtualNetworkGatewayConnectionsResetSharedKeyFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ResetSharedKeyResponder handles the response to the ResetSharedKey request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyResponder(resp *http.Response) (result ConnectionResetSharedKey, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the virtual network gateway connection name. -// parameters - parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation -// throughNetwork resource provider. -func (client VirtualNetworkGatewayConnectionsClient) SetSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey) (result VirtualNetworkGatewayConnectionsSetSharedKeyFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.SetSharedKey") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.NewError("network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", err.Error()) - } - - req, err := client.SetSharedKeyPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", nil, "Failure preparing request") - return - } - - result, err = client.SetSharedKeySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", result.Response(), "Failure sending request") - return - } - - return -} - -// SetSharedKeyPreparer prepares the SetSharedKey request. -func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetSharedKeySender sends the SetSharedKey request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeySender(req *http.Request) (future VirtualNetworkGatewayConnectionsSetSharedKeyFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// SetSharedKeyResponder handles the response to the SetSharedKey request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyResponder(resp *http.Response) (result ConnectionSharedKey, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// StartPacketCapture starts packet capture on virtual network gateway connection in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway connection. -// parameters - virtual network gateway packet capture parameters supplied to start packet capture on gateway -// connection. -func (client VirtualNetworkGatewayConnectionsClient) StartPacketCapture(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters *VpnPacketCaptureStartParameters) (result VirtualNetworkGatewayConnectionsStartPacketCaptureFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.StartPacketCapture") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPacketCapturePreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "StartPacketCapture", nil, "Failure preparing request") - return - } - - result, err = client.StartPacketCaptureSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "StartPacketCapture", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPacketCapturePreparer prepares the StartPacketCapture request. -func (client VirtualNetworkGatewayConnectionsClient) StartPacketCapturePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters *VpnPacketCaptureStartParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/startPacketCapture", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if parameters != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(parameters)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartPacketCaptureSender sends the StartPacketCapture request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) StartPacketCaptureSender(req *http.Request) (future VirtualNetworkGatewayConnectionsStartPacketCaptureFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartPacketCaptureResponder handles the response to the StartPacketCapture request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) StartPacketCaptureResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// StopPacketCapture stops packet capture on virtual network gateway connection in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway Connection. -// parameters - virtual network gateway packet capture parameters supplied to stop packet capture on gateway -// connection. -func (client VirtualNetworkGatewayConnectionsClient) StopPacketCapture(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VpnPacketCaptureStopParameters) (result VirtualNetworkGatewayConnectionsStopPacketCaptureFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.StopPacketCapture") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPacketCapturePreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "StopPacketCapture", nil, "Failure preparing request") - return - } - - result, err = client.StopPacketCaptureSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "StopPacketCapture", result.Response(), "Failure sending request") - return - } - - return -} - -// StopPacketCapturePreparer prepares the StopPacketCapture request. -func (client VirtualNetworkGatewayConnectionsClient) StopPacketCapturePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VpnPacketCaptureStopParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/stopPacketCapture", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StopPacketCaptureSender sends the StopPacketCapture request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) StopPacketCaptureSender(req *http.Request) (future VirtualNetworkGatewayConnectionsStopPacketCaptureFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StopPacketCaptureResponder handles the response to the StopPacketCapture request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) StopPacketCaptureResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates a virtual network gateway connection tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway connection. -// parameters - parameters supplied to update virtual network gateway connection tags. -func (client VirtualNetworkGatewayConnectionsClient) UpdateTags(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters TagsObject) (result VirtualNetworkGatewayConnectionsUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayConnectionsClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VirtualNetworkGatewayConnectionsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayConnectionsClient) UpdateTagsSender(req *http.Request) (future VirtualNetworkGatewayConnectionsUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) UpdateTagsResponder(resp *http.Response) (result VirtualNetworkGatewayConnection, err error) { - err = autorest.Respond( - resp, - 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/services/network/mgmt/2022-07-01/network/virtualnetworkgatewaynatrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworkgatewaynatrules.go deleted file mode 100644 index 119619416b..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworkgatewaynatrules.go +++ /dev/null @@ -1,395 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualNetworkGatewayNatRulesClient is the network Client -type VirtualNetworkGatewayNatRulesClient struct { - BaseClient -} - -// NewVirtualNetworkGatewayNatRulesClient creates an instance of the VirtualNetworkGatewayNatRulesClient client. -func NewVirtualNetworkGatewayNatRulesClient(subscriptionID string) VirtualNetworkGatewayNatRulesClient { - return NewVirtualNetworkGatewayNatRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualNetworkGatewayNatRulesClientWithBaseURI creates an instance of the VirtualNetworkGatewayNatRulesClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewVirtualNetworkGatewayNatRulesClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworkGatewayNatRulesClient { - return VirtualNetworkGatewayNatRulesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a nat rule to a scalable virtual network gateway if it doesn't exist else updates the -// existing nat rules. -// Parameters: -// resourceGroupName - the resource group name of the Virtual Network Gateway. -// virtualNetworkGatewayName - the name of the gateway. -// natRuleName - the name of the nat rule. -// natRuleParameters - parameters supplied to create or Update a Nat Rule. -func (client VirtualNetworkGatewayNatRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string, natRuleParameters VirtualNetworkGatewayNatRule) (result VirtualNetworkGatewayNatRulesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayNatRulesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualNetworkGatewayName, natRuleName, natRuleParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworkGatewayNatRulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string, natRuleParameters VirtualNetworkGatewayNatRule) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "natRuleName": autorest.Encode("path", natRuleName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - natRuleParameters.Etag = nil - natRuleParameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/natRules/{natRuleName}", pathParameters), - autorest.WithJSON(natRuleParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayNatRulesClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworkGatewayNatRulesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayNatRulesClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkGatewayNatRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a nat rule. -// Parameters: -// resourceGroupName - the resource group name of the Virtual Network Gateway. -// virtualNetworkGatewayName - the name of the gateway. -// natRuleName - the name of the nat rule. -func (client VirtualNetworkGatewayNatRulesClient) Delete(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string) (result VirtualNetworkGatewayNatRulesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayNatRulesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualNetworkGatewayName, natRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualNetworkGatewayNatRulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "natRuleName": autorest.Encode("path", natRuleName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2022-07-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/virtualNetworkGateways/{virtualNetworkGatewayName}/natRules/{natRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayNatRulesClient) DeleteSender(req *http.Request) (future VirtualNetworkGatewayNatRulesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayNatRulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a nat rule. -// Parameters: -// resourceGroupName - the resource group name of the Virtual Network Gateway. -// virtualNetworkGatewayName - the name of the gateway. -// natRuleName - the name of the nat rule. -func (client VirtualNetworkGatewayNatRulesClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string) (result VirtualNetworkGatewayNatRule, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayNatRulesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualNetworkGatewayName, natRuleName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesClient", "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.VirtualNetworkGatewayNatRulesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualNetworkGatewayNatRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, natRuleName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "natRuleName": autorest.Encode("path", natRuleName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), - } - - const APIVersion = "2022-07-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/virtualNetworkGateways/{virtualNetworkGatewayName}/natRules/{natRuleName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayNatRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayNatRulesClient) GetResponder(resp *http.Response) (result VirtualNetworkGatewayNatRule, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByVirtualNetworkGateway retrieves all nat rules for a particular virtual network gateway. -// Parameters: -// resourceGroupName - the resource group name of the virtual network gateway. -// virtualNetworkGatewayName - the name of the gateway. -func (client VirtualNetworkGatewayNatRulesClient) ListByVirtualNetworkGateway(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result ListVirtualNetworkGatewayNatRulesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayNatRulesClient.ListByVirtualNetworkGateway") - defer func() { - sc := -1 - if result.lvngnrr.Response.Response != nil { - sc = result.lvngnrr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByVirtualNetworkGatewayNextResults - req, err := client.ListByVirtualNetworkGatewayPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesClient", "ListByVirtualNetworkGateway", nil, "Failure preparing request") - return - } - - resp, err := client.ListByVirtualNetworkGatewaySender(req) - if err != nil { - result.lvngnrr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesClient", "ListByVirtualNetworkGateway", resp, "Failure sending request") - return - } - - result.lvngnrr, err = client.ListByVirtualNetworkGatewayResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesClient", "ListByVirtualNetworkGateway", resp, "Failure responding to request") - return - } - if result.lvngnrr.hasNextLink() && result.lvngnrr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByVirtualNetworkGatewayPreparer prepares the ListByVirtualNetworkGateway request. -func (client VirtualNetworkGatewayNatRulesClient) ListByVirtualNetworkGatewayPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*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 = "2022-07-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/virtualNetworkGateways/{virtualNetworkGatewayName}/natRules", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByVirtualNetworkGatewaySender sends the ListByVirtualNetworkGateway request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewayNatRulesClient) ListByVirtualNetworkGatewaySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByVirtualNetworkGatewayResponder handles the response to the ListByVirtualNetworkGateway request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewayNatRulesClient) ListByVirtualNetworkGatewayResponder(resp *http.Response) (result ListVirtualNetworkGatewayNatRulesResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByVirtualNetworkGatewayNextResults retrieves the next set of results, if any. -func (client VirtualNetworkGatewayNatRulesClient) listByVirtualNetworkGatewayNextResults(ctx context.Context, lastResults ListVirtualNetworkGatewayNatRulesResult) (result ListVirtualNetworkGatewayNatRulesResult, err error) { - req, err := lastResults.listVirtualNetworkGatewayNatRulesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesClient", "listByVirtualNetworkGatewayNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByVirtualNetworkGatewaySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesClient", "listByVirtualNetworkGatewayNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByVirtualNetworkGatewayResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayNatRulesClient", "listByVirtualNetworkGatewayNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByVirtualNetworkGatewayComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworkGatewayNatRulesClient) ListByVirtualNetworkGatewayComplete(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result ListVirtualNetworkGatewayNatRulesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewayNatRulesClient.ListByVirtualNetworkGateway") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByVirtualNetworkGateway(ctx, resourceGroupName, virtualNetworkGatewayName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworkgateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworkgateways.go deleted file mode 100644 index 1948dfbbd5..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworkgateways.go +++ /dev/null @@ -1,1910 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualNetworkGatewaysClient is the network Client -type VirtualNetworkGatewaysClient struct { - BaseClient -} - -// NewVirtualNetworkGatewaysClient creates an instance of the VirtualNetworkGatewaysClient client. -func NewVirtualNetworkGatewaysClient(subscriptionID string) VirtualNetworkGatewaysClient { - return NewVirtualNetworkGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualNetworkGatewaysClientWithBaseURI creates an instance of the VirtualNetworkGatewaysClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewVirtualNetworkGatewaysClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworkGatewaysClient { - return VirtualNetworkGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a virtual network gateway in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// parameters - parameters supplied to create or update virtual network gateway operation. -func (client VirtualNetworkGatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway) (result VirtualNetworkGatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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.BgpSettings", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "parameters.VirtualNetworkGatewayPropertiesFormat.BgpSettings.Asn", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualNetworkGatewaysClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworkGatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworkGatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified virtual network gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) Delete(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualNetworkGatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*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 = "2022-07-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/virtualNetworkGateways/{virtualNetworkGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) DeleteSender(req *http.Request) (future VirtualNetworkGatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// DisconnectVirtualNetworkGatewayVpnConnections disconnect vpn connections of virtual network gateway in the specified -// resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// request - the parameters are supplied to disconnect vpn connections. -func (client VirtualNetworkGatewaysClient) DisconnectVirtualNetworkGatewayVpnConnections(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, request P2SVpnConnectionRequest) (result VirtualNetworkGatewaysDisconnectVirtualNetworkGatewayVpnConnectionsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.DisconnectVirtualNetworkGatewayVpnConnections") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DisconnectVirtualNetworkGatewayVpnConnectionsPreparer(ctx, resourceGroupName, virtualNetworkGatewayName, request) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "DisconnectVirtualNetworkGatewayVpnConnections", nil, "Failure preparing request") - return - } - - result, err = client.DisconnectVirtualNetworkGatewayVpnConnectionsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "DisconnectVirtualNetworkGatewayVpnConnections", result.Response(), "Failure sending request") - return - } - - return -} - -// DisconnectVirtualNetworkGatewayVpnConnectionsPreparer prepares the DisconnectVirtualNetworkGatewayVpnConnections request. -func (client VirtualNetworkGatewaysClient) DisconnectVirtualNetworkGatewayVpnConnectionsPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, request P2SVpnConnectionRequest) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/disconnectVirtualNetworkGatewayVpnConnections", pathParameters), - autorest.WithJSON(request), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DisconnectVirtualNetworkGatewayVpnConnectionsSender sends the DisconnectVirtualNetworkGatewayVpnConnections request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) DisconnectVirtualNetworkGatewayVpnConnectionsSender(req *http.Request) (future VirtualNetworkGatewaysDisconnectVirtualNetworkGatewayVpnConnectionsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DisconnectVirtualNetworkGatewayVpnConnectionsResponder handles the response to the DisconnectVirtualNetworkGatewayVpnConnections request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) DisconnectVirtualNetworkGatewayVpnConnectionsResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// Generatevpnclientpackage generates VPN client package for P2S client of the virtual network gateway in the specified -// resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// parameters - parameters supplied to the generate virtual network gateway VPN client package operation. -func (client VirtualNetworkGatewaysClient) Generatevpnclientpackage(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VpnClientParameters) (result VirtualNetworkGatewaysGeneratevpnclientpackageFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.Generatevpnclientpackage") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GeneratevpnclientpackagePreparer(ctx, resourceGroupName, virtualNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Generatevpnclientpackage", nil, "Failure preparing request") - return - } - - result, err = client.GeneratevpnclientpackageSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Generatevpnclientpackage", result.Response(), "Failure sending request") - return - } - - return -} - -// GeneratevpnclientpackagePreparer prepares the Generatevpnclientpackage request. -func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackagePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VpnClientParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/generatevpnclientpackage", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GeneratevpnclientpackageSender sends the Generatevpnclientpackage request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackageSender(req *http.Request) (future VirtualNetworkGatewaysGeneratevpnclientpackageFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GeneratevpnclientpackageResponder handles the response to the Generatevpnclientpackage request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackageResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GenerateVpnProfile generates VPN profile for P2S client of the virtual network gateway in the specified resource -// group. Used for IKEV2 and radius based authentication. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// parameters - parameters supplied to the generate virtual network gateway VPN client package operation. -func (client VirtualNetworkGatewaysClient) GenerateVpnProfile(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VpnClientParameters) (result VirtualNetworkGatewaysGenerateVpnProfileFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.GenerateVpnProfile") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GenerateVpnProfilePreparer(ctx, resourceGroupName, virtualNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GenerateVpnProfile", nil, "Failure preparing request") - return - } - - result, err = client.GenerateVpnProfileSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GenerateVpnProfile", result.Response(), "Failure sending request") - return - } - - return -} - -// GenerateVpnProfilePreparer prepares the GenerateVpnProfile request. -func (client VirtualNetworkGatewaysClient) GenerateVpnProfilePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VpnClientParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/generatevpnprofile", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GenerateVpnProfileSender sends the GenerateVpnProfile request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GenerateVpnProfileSender(req *http.Request) (future VirtualNetworkGatewaysGenerateVpnProfileFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GenerateVpnProfileResponder handles the response to the GenerateVpnProfile request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GenerateVpnProfileResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get gets the specified virtual network gateway by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualNetworkGatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*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 = "2022-07-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/virtualNetworkGateways/{virtualNetworkGatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GetResponder(resp *http.Response) (result VirtualNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetAdvertisedRoutes this operation retrieves a list of routes the virtual network gateway is advertising to the -// specified peer. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// peer - the IP address of the peer. -func (client VirtualNetworkGatewaysClient) GetAdvertisedRoutes(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, peer string) (result VirtualNetworkGatewaysGetAdvertisedRoutesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.GetAdvertisedRoutes") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetAdvertisedRoutesPreparer(ctx, resourceGroupName, virtualNetworkGatewayName, peer) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetAdvertisedRoutes", nil, "Failure preparing request") - return - } - - result, err = client.GetAdvertisedRoutesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetAdvertisedRoutes", result.Response(), "Failure sending request") - return - } - - return -} - -// GetAdvertisedRoutesPreparer prepares the GetAdvertisedRoutes request. -func (client VirtualNetworkGatewaysClient) GetAdvertisedRoutesPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, peer string) (*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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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) (future VirtualNetworkGatewaysGetAdvertisedRoutesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// peer - the IP address of the peer to retrieve the status of. -func (client VirtualNetworkGatewaysClient) GetBgpPeerStatus(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, peer string) (result VirtualNetworkGatewaysGetBgpPeerStatusFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.GetBgpPeerStatus") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetBgpPeerStatusPreparer(ctx, resourceGroupName, virtualNetworkGatewayName, peer) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetBgpPeerStatus", nil, "Failure preparing request") - return - } - - result, err = client.GetBgpPeerStatusSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetBgpPeerStatus", result.Response(), "Failure sending request") - return - } - - return -} - -// GetBgpPeerStatusPreparer prepares the GetBgpPeerStatus request. -func (client VirtualNetworkGatewaysClient) GetBgpPeerStatusPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, peer string) (*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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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) (future VirtualNetworkGatewaysGetBgpPeerStatusFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) GetLearnedRoutes(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewaysGetLearnedRoutesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.GetLearnedRoutes") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetLearnedRoutesPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetLearnedRoutes", nil, "Failure preparing request") - return - } - - result, err = client.GetLearnedRoutesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetLearnedRoutes", result.Response(), "Failure sending request") - return - } - - return -} - -// GetLearnedRoutesPreparer prepares the GetLearnedRoutes request. -func (client VirtualNetworkGatewaysClient) GetLearnedRoutesPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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) (future VirtualNetworkGatewaysGetLearnedRoutesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetVpnclientConnectionHealth get VPN client connection health detail per P2S client connection of the virtual -// network gateway in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) GetVpnclientConnectionHealth(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewaysGetVpnclientConnectionHealthFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.GetVpnclientConnectionHealth") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetVpnclientConnectionHealthPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetVpnclientConnectionHealth", nil, "Failure preparing request") - return - } - - result, err = client.GetVpnclientConnectionHealthSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetVpnclientConnectionHealth", result.Response(), "Failure sending request") - return - } - - return -} - -// GetVpnclientConnectionHealthPreparer prepares the GetVpnclientConnectionHealth request. -func (client VirtualNetworkGatewaysClient) GetVpnclientConnectionHealthPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*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 = "2022-07-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}/getVpnClientConnectionHealth", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetVpnclientConnectionHealthSender sends the GetVpnclientConnectionHealth request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GetVpnclientConnectionHealthSender(req *http.Request) (future VirtualNetworkGatewaysGetVpnclientConnectionHealthFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetVpnclientConnectionHealthResponder handles the response to the GetVpnclientConnectionHealth request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GetVpnclientConnectionHealthResponder(resp *http.Response) (result VpnClientConnectionHealthDetailListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetVpnclientIpsecParameters the Get VpnclientIpsecParameters operation retrieves information about the vpnclient -// ipsec policy for P2S client of virtual network gateway in the specified resource group through Network resource -// provider. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the virtual network gateway name. -func (client VirtualNetworkGatewaysClient) GetVpnclientIpsecParameters(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.GetVpnclientIpsecParameters") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetVpnclientIpsecParametersPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetVpnclientIpsecParameters", nil, "Failure preparing request") - return - } - - result, err = client.GetVpnclientIpsecParametersSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetVpnclientIpsecParameters", result.Response(), "Failure sending request") - return - } - - return -} - -// GetVpnclientIpsecParametersPreparer prepares the GetVpnclientIpsecParameters request. -func (client VirtualNetworkGatewaysClient) GetVpnclientIpsecParametersPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*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 = "2022-07-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}/getvpnclientipsecparameters", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetVpnclientIpsecParametersSender sends the GetVpnclientIpsecParameters request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GetVpnclientIpsecParametersSender(req *http.Request) (future VirtualNetworkGatewaysGetVpnclientIpsecParametersFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetVpnclientIpsecParametersResponder handles the response to the GetVpnclientIpsecParameters request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GetVpnclientIpsecParametersResponder(resp *http.Response) (result VpnClientIPsecParameters, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetVpnProfilePackageURL gets pre-generated VPN profile for P2S client of the virtual network gateway in the -// specified resource group. The profile needs to be generated first using generateVpnProfile. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) GetVpnProfilePackageURL(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewaysGetVpnProfilePackageURLFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.GetVpnProfilePackageURL") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetVpnProfilePackageURLPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetVpnProfilePackageURL", nil, "Failure preparing request") - return - } - - result, err = client.GetVpnProfilePackageURLSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetVpnProfilePackageURL", result.Response(), "Failure sending request") - return - } - - return -} - -// GetVpnProfilePackageURLPreparer prepares the GetVpnProfilePackageURL request. -func (client VirtualNetworkGatewaysClient) GetVpnProfilePackageURLPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*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 = "2022-07-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}/getvpnprofilepackageurl", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetVpnProfilePackageURLSender sends the GetVpnProfilePackageURL request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) GetVpnProfilePackageURLSender(req *http.Request) (future VirtualNetworkGatewaysGetVpnProfilePackageURLFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetVpnProfilePackageURLResponder handles the response to the GetVpnProfilePackageURL request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) GetVpnProfilePackageURLResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all virtual network gateways by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client VirtualNetworkGatewaysClient) List(ctx context.Context, resourceGroupName string) (result VirtualNetworkGatewayListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.List") - defer func() { - sc := -1 - if result.vnglr.Response.Response != nil { - sc = result.vnglr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vnglr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure sending request") - return - } - - result.vnglr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure responding to request") - return - } - if result.vnglr.hasNextLink() && result.vnglr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualNetworkGatewaysClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/virtualNetworkGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) ListResponder(resp *http.Response) (result VirtualNetworkGatewayListResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualNetworkGatewaysClient) listNextResults(ctx context.Context, lastResults VirtualNetworkGatewayListResult) (result VirtualNetworkGatewayListResult, err error) { - req, err := lastResults.virtualNetworkGatewayListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworkGatewaysClient) ListComplete(ctx context.Context, resourceGroupName string) (result VirtualNetworkGatewayListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListConnections gets all the connections in a virtual network gateway. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) ListConnections(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewayListConnectionsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.ListConnections") - defer func() { - sc := -1 - if result.vnglcr.Response.Response != nil { - sc = result.vnglcr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listConnectionsNextResults - req, err := client.ListConnectionsPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "ListConnections", nil, "Failure preparing request") - return - } - - resp, err := client.ListConnectionsSender(req) - if err != nil { - result.vnglcr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "ListConnections", resp, "Failure sending request") - return - } - - result.vnglcr, err = client.ListConnectionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "ListConnections", resp, "Failure responding to request") - return - } - if result.vnglcr.hasNextLink() && result.vnglcr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListConnectionsPreparer prepares the ListConnections request. -func (client VirtualNetworkGatewaysClient) ListConnectionsPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*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 = "2022-07-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/virtualNetworkGateways/{virtualNetworkGatewayName}/connections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListConnectionsSender sends the ListConnections request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) ListConnectionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListConnectionsResponder handles the response to the ListConnections request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) ListConnectionsResponder(resp *http.Response) (result VirtualNetworkGatewayListConnectionsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listConnectionsNextResults retrieves the next set of results, if any. -func (client VirtualNetworkGatewaysClient) listConnectionsNextResults(ctx context.Context, lastResults VirtualNetworkGatewayListConnectionsResult) (result VirtualNetworkGatewayListConnectionsResult, err error) { - req, err := lastResults.virtualNetworkGatewayListConnectionsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "listConnectionsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListConnectionsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "listConnectionsNextResults", resp, "Failure sending next results request") - } - result, err = client.ListConnectionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "listConnectionsNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListConnectionsComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworkGatewaysClient) ListConnectionsComplete(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewayListConnectionsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.ListConnections") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListConnections(ctx, resourceGroupName, virtualNetworkGatewayName) - return -} - -// Reset resets the primary of the virtual network gateway in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// gatewayVip - virtual network gateway vip address supplied to the begin reset of the active-active feature -// enabled gateway. -func (client VirtualNetworkGatewaysClient) Reset(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, gatewayVip string) (result VirtualNetworkGatewaysResetFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.Reset") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ResetPreparer(ctx, resourceGroupName, virtualNetworkGatewayName, gatewayVip) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", nil, "Failure preparing request") - return - } - - result, err = client.ResetSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", result.Response(), "Failure sending request") - return - } - - return -} - -// ResetPreparer prepares the Reset request. -func (client VirtualNetworkGatewaysClient) ResetPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, gatewayVip string) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(gatewayVip) > 0 { - queryParameters["gatewayVip"] = autorest.Encode("query", gatewayVip) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/reset", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ResetSender sends the Reset request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) ResetSender(req *http.Request) (future VirtualNetworkGatewaysResetFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ResetResponder handles the response to the Reset request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) ResetResponder(resp *http.Response) (result VirtualNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ResetVpnClientSharedKey resets the VPN client shared key of the virtual network gateway in the specified resource -// group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) ResetVpnClientSharedKey(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGatewaysResetVpnClientSharedKeyFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.ResetVpnClientSharedKey") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ResetVpnClientSharedKeyPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "ResetVpnClientSharedKey", nil, "Failure preparing request") - return - } - - result, err = client.ResetVpnClientSharedKeySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "ResetVpnClientSharedKey", result.Response(), "Failure sending request") - return - } - - return -} - -// ResetVpnClientSharedKeyPreparer prepares the ResetVpnClientSharedKey request. -func (client VirtualNetworkGatewaysClient) ResetVpnClientSharedKeyPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*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 = "2022-07-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}/resetvpnclientsharedkey", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ResetVpnClientSharedKeySender sends the ResetVpnClientSharedKey request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) ResetVpnClientSharedKeySender(req *http.Request) (future VirtualNetworkGatewaysResetVpnClientSharedKeyFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ResetVpnClientSharedKeyResponder handles the response to the ResetVpnClientSharedKey request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) ResetVpnClientSharedKeyResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} - -// SetVpnclientIpsecParameters the Set VpnclientIpsecParameters operation sets the vpnclient ipsec policy for P2S -// client of virtual network gateway in the specified resource group through Network resource provider. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// vpnclientIpsecParams - parameters supplied to the Begin Set vpnclient ipsec parameters of Virtual Network -// Gateway P2S client operation through Network resource provider. -func (client VirtualNetworkGatewaysClient) SetVpnclientIpsecParameters(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, vpnclientIpsecParams VpnClientIPsecParameters) (result VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.SetVpnclientIpsecParameters") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: vpnclientIpsecParams, - Constraints: []validation.Constraint{{Target: "vpnclientIpsecParams.SaLifeTimeSeconds", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "vpnclientIpsecParams.SaDataSizeKilobytes", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.VirtualNetworkGatewaysClient", "SetVpnclientIpsecParameters", err.Error()) - } - - req, err := client.SetVpnclientIpsecParametersPreparer(ctx, resourceGroupName, virtualNetworkGatewayName, vpnclientIpsecParams) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "SetVpnclientIpsecParameters", nil, "Failure preparing request") - return - } - - result, err = client.SetVpnclientIpsecParametersSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "SetVpnclientIpsecParameters", result.Response(), "Failure sending request") - return - } - - return -} - -// SetVpnclientIpsecParametersPreparer prepares the SetVpnclientIpsecParameters request. -func (client VirtualNetworkGatewaysClient) SetVpnclientIpsecParametersPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, vpnclientIpsecParams VpnClientIPsecParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/setvpnclientipsecparameters", pathParameters), - autorest.WithJSON(vpnclientIpsecParams), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetVpnclientIpsecParametersSender sends the SetVpnclientIpsecParameters request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) SetVpnclientIpsecParametersSender(req *http.Request) (future VirtualNetworkGatewaysSetVpnclientIpsecParametersFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// SetVpnclientIpsecParametersResponder handles the response to the SetVpnclientIpsecParameters request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) SetVpnclientIpsecParametersResponder(resp *http.Response) (result VpnClientIPsecParameters, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// StartPacketCapture starts packet capture on virtual network gateway in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// parameters - virtual network gateway packet capture parameters supplied to start packet capture on gateway. -func (client VirtualNetworkGatewaysClient) StartPacketCapture(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters *VpnPacketCaptureStartParameters) (result VirtualNetworkGatewaysStartPacketCaptureFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.StartPacketCapture") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPacketCapturePreparer(ctx, resourceGroupName, virtualNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "StartPacketCapture", nil, "Failure preparing request") - return - } - - result, err = client.StartPacketCaptureSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "StartPacketCapture", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPacketCapturePreparer prepares the StartPacketCapture request. -func (client VirtualNetworkGatewaysClient) StartPacketCapturePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters *VpnPacketCaptureStartParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/startPacketCapture", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if parameters != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(parameters)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartPacketCaptureSender sends the StartPacketCapture request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) StartPacketCaptureSender(req *http.Request) (future VirtualNetworkGatewaysStartPacketCaptureFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartPacketCaptureResponder handles the response to the StartPacketCapture request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) StartPacketCaptureResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// StopPacketCapture stops packet capture on virtual network gateway in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// parameters - virtual network gateway packet capture parameters supplied to stop packet capture on gateway. -func (client VirtualNetworkGatewaysClient) StopPacketCapture(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VpnPacketCaptureStopParameters) (result VirtualNetworkGatewaysStopPacketCaptureFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.StopPacketCapture") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPacketCapturePreparer(ctx, resourceGroupName, virtualNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "StopPacketCapture", nil, "Failure preparing request") - return - } - - result, err = client.StopPacketCaptureSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "StopPacketCapture", result.Response(), "Failure sending request") - return - } - - return -} - -// StopPacketCapturePreparer prepares the StopPacketCapture request. -func (client VirtualNetworkGatewaysClient) StopPacketCapturePreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters VpnPacketCaptureStopParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/stopPacketCapture", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StopPacketCaptureSender sends the StopPacketCapture request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) StopPacketCaptureSender(req *http.Request) (future VirtualNetworkGatewaysStopPacketCaptureFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StopPacketCaptureResponder handles the response to the StopPacketCapture request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) StopPacketCaptureResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SupportedVpnDevices gets a xml format representation for supported vpn devices. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) SupportedVpnDevices(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (result String, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.SupportedVpnDevices") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.SupportedVpnDevicesPreparer(ctx, resourceGroupName, virtualNetworkGatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "SupportedVpnDevices", nil, "Failure preparing request") - return - } - - resp, err := client.SupportedVpnDevicesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "SupportedVpnDevices", resp, "Failure sending request") - return - } - - result, err = client.SupportedVpnDevicesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "SupportedVpnDevices", resp, "Failure responding to request") - return - } - - return -} - -// SupportedVpnDevicesPreparer prepares the SupportedVpnDevices request. -func (client VirtualNetworkGatewaysClient) SupportedVpnDevicesPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string) (*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 = "2022-07-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}/supportedvpndevices", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SupportedVpnDevicesSender sends the SupportedVpnDevices request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) SupportedVpnDevicesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// SupportedVpnDevicesResponder handles the response to the SupportedVpnDevices request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) SupportedVpnDevicesResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates a virtual network gateway tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayName - the name of the virtual network gateway. -// parameters - parameters supplied to update virtual network gateway tags. -func (client VirtualNetworkGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters TagsObject) (result VirtualNetworkGatewaysUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, virtualNetworkGatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VirtualNetworkGatewaysClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayName string, parameters TagsObject) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) UpdateTagsSender(req *http.Request) (future VirtualNetworkGatewaysUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) UpdateTagsResponder(resp *http.Response) (result VirtualNetworkGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// VpnDeviceConfigurationScript gets a xml format representation for vpn device configuration script. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkGatewayConnectionName - the name of the virtual network gateway connection for which the -// configuration script is generated. -// parameters - parameters supplied to the generate vpn device script operation. -func (client VirtualNetworkGatewaysClient) VpnDeviceConfigurationScript(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VpnDeviceScriptParameters) (result String, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkGatewaysClient.VpnDeviceConfigurationScript") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.VpnDeviceConfigurationScriptPreparer(ctx, resourceGroupName, virtualNetworkGatewayConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "VpnDeviceConfigurationScript", nil, "Failure preparing request") - return - } - - resp, err := client.VpnDeviceConfigurationScriptSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "VpnDeviceConfigurationScript", resp, "Failure sending request") - return - } - - result, err = client.VpnDeviceConfigurationScriptResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "VpnDeviceConfigurationScript", resp, "Failure responding to request") - return - } - - return -} - -// VpnDeviceConfigurationScriptPreparer prepares the VpnDeviceConfigurationScript request. -func (client VirtualNetworkGatewaysClient) VpnDeviceConfigurationScriptPreparer(ctx context.Context, resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VpnDeviceScriptParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/vpndeviceconfigurationscript", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// VpnDeviceConfigurationScriptSender sends the VpnDeviceConfigurationScript request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkGatewaysClient) VpnDeviceConfigurationScriptSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// VpnDeviceConfigurationScriptResponder handles the response to the VpnDeviceConfigurationScript request. The method always -// closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) VpnDeviceConfigurationScriptResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworkpeerings.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworkpeerings.go deleted file mode 100644 index 03e63e845a..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworkpeerings.go +++ /dev/null @@ -1,411 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualNetworkPeeringsClient is the network Client -type VirtualNetworkPeeringsClient struct { - BaseClient -} - -// NewVirtualNetworkPeeringsClient creates an instance of the VirtualNetworkPeeringsClient client. -func NewVirtualNetworkPeeringsClient(subscriptionID string) VirtualNetworkPeeringsClient { - return NewVirtualNetworkPeeringsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualNetworkPeeringsClientWithBaseURI creates an instance of the VirtualNetworkPeeringsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewVirtualNetworkPeeringsClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworkPeeringsClient { - return VirtualNetworkPeeringsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a peering in the specified virtual network. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// virtualNetworkPeeringName - the name of the peering. -// virtualNetworkPeeringParameters - parameters supplied to the create or update virtual network peering -// operation. -// syncRemoteAddressSpace - parameter indicates the intention to sync the peering with the current address -// space on the remote vNet after it's updated. -func (client VirtualNetworkPeeringsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, virtualNetworkPeeringParameters VirtualNetworkPeering, syncRemoteAddressSpace SyncRemoteAddressSpace) (result VirtualNetworkPeeringsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: virtualNetworkPeeringParameters, - Constraints: []validation.Constraint{{Target: "virtualNetworkPeeringParameters.VirtualNetworkPeeringPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "virtualNetworkPeeringParameters.VirtualNetworkPeeringPropertiesFormat.RemoteBgpCommunities", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "virtualNetworkPeeringParameters.VirtualNetworkPeeringPropertiesFormat.RemoteBgpCommunities.VirtualNetworkCommunity", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "virtualNetworkPeeringParameters.VirtualNetworkPeeringPropertiesFormat.RemoteVirtualNetworkEncryption", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "virtualNetworkPeeringParameters.VirtualNetworkPeeringPropertiesFormat.RemoteVirtualNetworkEncryption.Enabled", Name: validation.Null, Rule: true, Chain: nil}}}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualNetworkPeeringsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, syncRemoteAddressSpace) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworkPeeringsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, virtualNetworkPeeringParameters VirtualNetworkPeering, syncRemoteAddressSpace SyncRemoteAddressSpace) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - "virtualNetworkPeeringName": autorest.Encode("path", virtualNetworkPeeringName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if len(string(syncRemoteAddressSpace)) > 0 { - queryParameters["syncRemoteAddressSpace"] = autorest.Encode("query", syncRemoteAddressSpace) - } - - virtualNetworkPeeringParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}", pathParameters), - autorest.WithJSON(virtualNetworkPeeringParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkPeeringsClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworkPeeringsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualNetworkPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified virtual network peering. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// virtualNetworkPeeringName - the name of the virtual network peering. -func (client VirtualNetworkPeeringsClient) Delete(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string) (result VirtualNetworkPeeringsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualNetworkName, virtualNetworkPeeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualNetworkPeeringsClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - "virtualNetworkPeeringName": autorest.Encode("path", virtualNetworkPeeringName), - } - - const APIVersion = "2022-07-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/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkPeeringsClient) DeleteSender(req *http.Request) (future VirtualNetworkPeeringsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualNetworkPeeringsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified virtual network peering. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// virtualNetworkPeeringName - the name of the virtual network peering. -func (client VirtualNetworkPeeringsClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string) (result VirtualNetworkPeering, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualNetworkName, virtualNetworkPeeringName) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualNetworkPeeringsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualNetworkName": autorest.Encode("path", virtualNetworkName), - "virtualNetworkPeeringName": autorest.Encode("path", virtualNetworkPeeringName), - } - - const APIVersion = "2022-07-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/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkPeeringsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualNetworkPeeringsClient) GetResponder(resp *http.Response) (result VirtualNetworkPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all virtual network peerings in a virtual network. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -func (client VirtualNetworkPeeringsClient) List(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result VirtualNetworkPeeringListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringsClient.List") - defer func() { - sc := -1 - if result.vnplr.Response.Response != nil { - sc = result.vnplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualNetworkName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vnplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "List", resp, "Failure sending request") - return - } - - result.vnplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "List", resp, "Failure responding to request") - return - } - if result.vnplr.hasNextLink() && result.vnplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualNetworkPeeringsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName 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 = "2022-07-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/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkPeeringsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualNetworkPeeringsClient) ListResponder(resp *http.Response) (result VirtualNetworkPeeringListResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualNetworkPeeringsClient) listNextResults(ctx context.Context, lastResults VirtualNetworkPeeringListResult) (result VirtualNetworkPeeringListResult, err error) { - req, err := lastResults.virtualNetworkPeeringListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworkPeeringsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result VirtualNetworkPeeringListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkPeeringsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualNetworkName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworks.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworks.go deleted file mode 100644 index 9f8ef4ba6b..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworks.go +++ /dev/null @@ -1,916 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualNetworksClient is the network Client -type VirtualNetworksClient struct { - BaseClient -} - -// NewVirtualNetworksClient creates an instance of the VirtualNetworksClient client. -func NewVirtualNetworksClient(subscriptionID string) VirtualNetworksClient { - return NewVirtualNetworksClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualNetworksClientWithBaseURI creates an instance of the VirtualNetworksClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVirtualNetworksClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworksClient { - return VirtualNetworksClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CheckIPAddressAvailability checks whether a private IP address is available for use. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// IPAddress - the private IP address to be verified. -func (client VirtualNetworksClient) CheckIPAddressAvailability(ctx context.Context, resourceGroupName string, virtualNetworkName string, IPAddress string) (result IPAddressAvailabilityResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.CheckIPAddressAvailability") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CheckIPAddressAvailabilityPreparer(ctx, resourceGroupName, virtualNetworkName, IPAddress) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CheckIPAddressAvailability", resp, "Failure sending request") - return - } - - result, err = client.CheckIPAddressAvailabilityResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CheckIPAddressAvailability", resp, "Failure responding to request") - return - } - - return -} - -// CheckIPAddressAvailabilityPreparer prepares the CheckIPAddressAvailability request. -func (client VirtualNetworksClient) CheckIPAddressAvailabilityPreparer(ctx context.Context, 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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - "ipAddress": autorest.Encode("query", IPAddress), - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/CheckIPAddressAvailability", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckIPAddressAvailabilitySender sends the CheckIPAddressAvailability request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) CheckIPAddressAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CheckIPAddressAvailabilityResponder handles the response to the CheckIPAddressAvailability request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) CheckIPAddressAvailabilityResponder(resp *http.Response) (result IPAddressAvailabilityResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate creates or updates a virtual network in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// parameters - parameters supplied to the create or update virtual network operation. -func (client VirtualNetworksClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork) (result VirtualNetworksCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VirtualNetworkPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkPropertiesFormat.BgpCommunities", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkPropertiesFormat.BgpCommunities.VirtualNetworkCommunity", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "parameters.VirtualNetworkPropertiesFormat.Encryption", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkPropertiesFormat.Encryption.Enabled", Name: validation.Null, Rule: true, Chain: nil}}}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualNetworksClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualNetworkName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworksClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworksCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetwork, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified virtual network. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -func (client VirtualNetworksClient) Delete(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result VirtualNetworksDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualNetworkName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualNetworksClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName 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 = "2022-07-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/virtualNetworks/{virtualNetworkName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) DeleteSender(req *http.Request) (future VirtualNetworksDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified virtual network by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// expand - expands referenced resources. -func (client VirtualNetworksClient) Get(ctx context.Context, resourceGroupName string, virtualNetworkName string, expand string) (result VirtualNetwork, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualNetworkName, expand) - if err != nil { - 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} - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualNetworksClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, expand 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 = "2022-07-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/virtualNetworks/{virtualNetworkName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) GetResponder(resp *http.Response) (result VirtualNetwork, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all virtual networks in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client VirtualNetworksClient) List(ctx context.Context, resourceGroupName string) (result VirtualNetworkListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.List") - defer func() { - sc := -1 - if result.vnlr.Response.Response != nil { - sc = result.vnlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vnlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure sending request") - return - } - - result.vnlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure responding to request") - return - } - if result.vnlr.hasNextLink() && result.vnlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualNetworksClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/virtualNetworks", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) ListResponder(resp *http.Response) (result VirtualNetworkListResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualNetworksClient) listNextResults(ctx context.Context, lastResults VirtualNetworkListResult) (result VirtualNetworkListResult, err error) { - req, err := lastResults.virtualNetworkListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworksClient) ListComplete(ctx context.Context, resourceGroupName string) (result VirtualNetworkListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all virtual networks in a subscription. -func (client VirtualNetworksClient) ListAll(ctx context.Context) (result VirtualNetworkListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.ListAll") - defer func() { - sc := -1 - if result.vnlr.Response.Response != nil { - sc = result.vnlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.vnlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure sending request") - return - } - - result.vnlr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure responding to request") - return - } - if result.vnlr.hasNextLink() && result.vnlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client VirtualNetworksClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualNetworks", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) ListAllResponder(resp *http.Response) (result VirtualNetworkListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client VirtualNetworksClient) listAllNextResults(ctx context.Context, lastResults VirtualNetworkListResult) (result VirtualNetworkListResult, err error) { - req, err := lastResults.virtualNetworkListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworksClient) ListAllComplete(ctx context.Context) (result VirtualNetworkListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListDdosProtectionStatus gets the Ddos Protection Status of all IP Addresses under the Virtual Network -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// top - the max number of ip addresses to return. -// skipToken - the skipToken that is given with nextLink. -func (client VirtualNetworksClient) ListDdosProtectionStatus(ctx context.Context, resourceGroupName string, virtualNetworkName string, top *int32, skipToken string) (result VirtualNetworksListDdosProtectionStatusFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.ListDdosProtectionStatus") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListDdosProtectionStatusPreparer(ctx, resourceGroupName, virtualNetworkName, top, skipToken) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListDdosProtectionStatus", nil, "Failure preparing request") - return - } - - result, err = client.ListDdosProtectionStatusSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListDdosProtectionStatus", result.Response(), "Failure sending request") - return - } - - return -} - -// ListDdosProtectionStatusPreparer prepares the ListDdosProtectionStatus request. -func (client VirtualNetworksClient) ListDdosProtectionStatusPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, top *int32, skipToken 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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["top"] = autorest.Encode("query", *top) - } - if len(skipToken) > 0 { - queryParameters["skipToken"] = autorest.Encode("query", skipToken) - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/ddosProtectionStatus", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListDdosProtectionStatusSender sends the ListDdosProtectionStatus request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) ListDdosProtectionStatusSender(req *http.Request) (future VirtualNetworksListDdosProtectionStatusFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListDdosProtectionStatusResponder handles the response to the ListDdosProtectionStatus request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) ListDdosProtectionStatusResponder(resp *http.Response) (result VirtualNetworkDdosProtectionStatusResultPage, err error) { - result.vndpsr, err = client.listDdosProtectionStatusResponder(resp) - result.fn = client.listDdosProtectionStatusNextResults - return -} - -func (client VirtualNetworksClient) listDdosProtectionStatusResponder(resp *http.Response) (result VirtualNetworkDdosProtectionStatusResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listDdosProtectionStatusNextResults retrieves the next set of results, if any. -func (client VirtualNetworksClient) listDdosProtectionStatusNextResults(ctx context.Context, lastResults VirtualNetworkDdosProtectionStatusResult) (result VirtualNetworkDdosProtectionStatusResult, err error) { - req, err := lastResults.virtualNetworkDdosProtectionStatusResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listDdosProtectionStatusNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - var resp *http.Response - resp, err = client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listDdosProtectionStatusNextResults", resp, "Failure sending next results request") - } - return client.listDdosProtectionStatusResponder(resp) -} - -// ListDdosProtectionStatusComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworksClient) ListDdosProtectionStatusComplete(ctx context.Context, resourceGroupName string, virtualNetworkName string, top *int32, skipToken string) (result VirtualNetworksListDdosProtectionStatusAllFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.ListDdosProtectionStatus") - defer func() { - sc := -1 - if result.Response() != nil { - sc = result.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - var future VirtualNetworksListDdosProtectionStatusFuture - future, err = client.ListDdosProtectionStatus(ctx, resourceGroupName, virtualNetworkName, top, skipToken) - result.FutureAPI = future.FutureAPI - return -} - -// ListUsage lists usage stats. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -func (client VirtualNetworksClient) ListUsage(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result VirtualNetworkListUsageResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.ListUsage") - defer func() { - sc := -1 - if result.vnlur.Response.Response != nil { - sc = result.vnlur.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listUsageNextResults - req, err := client.ListUsagePreparer(ctx, resourceGroupName, virtualNetworkName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListUsage", nil, "Failure preparing request") - return - } - - resp, err := client.ListUsageSender(req) - if err != nil { - result.vnlur.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListUsage", resp, "Failure sending request") - return - } - - result.vnlur, err = client.ListUsageResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListUsage", resp, "Failure responding to request") - return - } - if result.vnlur.hasNextLink() && result.vnlur.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListUsagePreparer prepares the ListUsage request. -func (client VirtualNetworksClient) ListUsagePreparer(ctx context.Context, resourceGroupName string, virtualNetworkName 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 = "2022-07-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/virtualNetworks/{virtualNetworkName}/usages", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListUsageSender sends the ListUsage request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) ListUsageSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListUsageResponder handles the response to the ListUsage request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) ListUsageResponder(resp *http.Response) (result VirtualNetworkListUsageResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listUsageNextResults retrieves the next set of results, if any. -func (client VirtualNetworksClient) listUsageNextResults(ctx context.Context, lastResults VirtualNetworkListUsageResult) (result VirtualNetworkListUsageResult, err error) { - req, err := lastResults.virtualNetworkListUsageResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listUsageNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListUsageSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listUsageNextResults", resp, "Failure sending next results request") - } - result, err = client.ListUsageResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "listUsageNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListUsageComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworksClient) ListUsageComplete(ctx context.Context, resourceGroupName string, virtualNetworkName string) (result VirtualNetworkListUsageResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.ListUsage") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListUsage(ctx, resourceGroupName, virtualNetworkName) - return -} - -// UpdateTags updates a virtual network tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualNetworkName - the name of the virtual network. -// parameters - parameters supplied to update virtual network tags. -func (client VirtualNetworksClient) UpdateTags(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters TagsObject) (result VirtualNetwork, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, virtualNetworkName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VirtualNetworksClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, virtualNetworkName string, parameters TagsObject) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworksClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VirtualNetworksClient) UpdateTagsResponder(resp *http.Response) (result VirtualNetwork, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworktaps.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworktaps.go deleted file mode 100644 index ed7df95593..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualnetworktaps.go +++ /dev/null @@ -1,613 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualNetworkTapsClient is the network Client -type VirtualNetworkTapsClient struct { - BaseClient -} - -// NewVirtualNetworkTapsClient creates an instance of the VirtualNetworkTapsClient client. -func NewVirtualNetworkTapsClient(subscriptionID string) VirtualNetworkTapsClient { - return NewVirtualNetworkTapsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualNetworkTapsClientWithBaseURI creates an instance of the VirtualNetworkTapsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewVirtualNetworkTapsClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworkTapsClient { - return VirtualNetworkTapsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a Virtual Network Tap. -// Parameters: -// resourceGroupName - the name of the resource group. -// tapName - the name of the virtual network tap. -// parameters - parameters supplied to the create or update virtual network tap operation. -func (client VirtualNetworkTapsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, tapName string, parameters VirtualNetworkTap) (result VirtualNetworkTapsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, - }}, - {Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.ServicePublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - {Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationNetworkInterfaceIPConfiguration.InterfaceIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.LinkedPublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - }}, - }}, - }}, - }}, - {Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, - }}, - {Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.ServicePublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - {Target: "parameters.VirtualNetworkTapPropertiesFormat.DestinationLoadBalancerFrontEndIPConfiguration.FrontendIPConfigurationPropertiesFormat.PublicIPAddress.PublicIPAddressPropertiesFormat.LinkedPublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - }}, - }}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualNetworkTapsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, tapName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworkTapsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, tapName string, parameters VirtualNetworkTap) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapName": autorest.Encode("path", tapName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkTapsClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworkTapsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualNetworkTapsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkTap, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified virtual network tap. -// Parameters: -// resourceGroupName - the name of the resource group. -// tapName - the name of the virtual network tap. -func (client VirtualNetworkTapsClient) Delete(ctx context.Context, resourceGroupName string, tapName string) (result VirtualNetworkTapsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, tapName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualNetworkTapsClient) DeletePreparer(ctx context.Context, resourceGroupName string, tapName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapName": autorest.Encode("path", tapName), - } - - const APIVersion = "2022-07-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/virtualNetworkTaps/{tapName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkTapsClient) DeleteSender(req *http.Request) (future VirtualNetworkTapsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualNetworkTapsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets information about the specified virtual network tap. -// Parameters: -// resourceGroupName - the name of the resource group. -// tapName - the name of virtual network tap. -func (client VirtualNetworkTapsClient) Get(ctx context.Context, resourceGroupName string, tapName string) (result VirtualNetworkTap, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, tapName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "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.VirtualNetworkTapsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualNetworkTapsClient) GetPreparer(ctx context.Context, resourceGroupName string, tapName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapName": autorest.Encode("path", tapName), - } - - const APIVersion = "2022-07-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/virtualNetworkTaps/{tapName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkTapsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualNetworkTapsClient) GetResponder(resp *http.Response) (result VirtualNetworkTap, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListAll gets all the VirtualNetworkTaps in a subscription. -func (client VirtualNetworkTapsClient) ListAll(ctx context.Context) (result VirtualNetworkTapListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.ListAll") - defer func() { - sc := -1 - if result.vntlr.Response.Response != nil { - sc = result.vntlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.vntlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListAll", resp, "Failure sending request") - return - } - - result.vntlr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListAll", resp, "Failure responding to request") - return - } - if result.vntlr.hasNextLink() && result.vntlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client VirtualNetworkTapsClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualNetworkTaps", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkTapsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client VirtualNetworkTapsClient) ListAllResponder(resp *http.Response) (result VirtualNetworkTapListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client VirtualNetworkTapsClient) listAllNextResults(ctx context.Context, lastResults VirtualNetworkTapListResult) (result VirtualNetworkTapListResult, err error) { - req, err := lastResults.virtualNetworkTapListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworkTapsClient) ListAllComplete(ctx context.Context) (result VirtualNetworkTapListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} - -// ListByResourceGroup gets all the VirtualNetworkTaps in a subscription. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client VirtualNetworkTapsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result VirtualNetworkTapListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.vntlr.Response.Response != nil { - sc = result.vntlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.vntlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.vntlr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.vntlr.hasNextLink() && result.vntlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client VirtualNetworkTapsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/virtualNetworkTaps", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkTapsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client VirtualNetworkTapsClient) ListByResourceGroupResponder(resp *http.Response) (result VirtualNetworkTapListResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualNetworkTapsClient) listByResourceGroupNextResults(ctx context.Context, lastResults VirtualNetworkTapListResult) (result VirtualNetworkTapListResult, err error) { - req, err := lastResults.virtualNetworkTapListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualNetworkTapsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result VirtualNetworkTapListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates an VirtualNetworkTap tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// tapName - the name of the tap. -// tapParameters - parameters supplied to update VirtualNetworkTap tags. -func (client VirtualNetworkTapsClient) UpdateTags(ctx context.Context, resourceGroupName string, tapName string, tapParameters TagsObject) (result VirtualNetworkTap, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkTapsClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, tapName, tapParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkTapsClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VirtualNetworkTapsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, tapName string, tapParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "tapName": autorest.Encode("path", tapName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkTaps/{tapName}", pathParameters), - autorest.WithJSON(tapParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualNetworkTapsClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VirtualNetworkTapsClient) UpdateTagsResponder(resp *http.Response) (result VirtualNetworkTap, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualrouterpeerings.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualrouterpeerings.go deleted file mode 100644 index 1b085b2078..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualrouterpeerings.go +++ /dev/null @@ -1,406 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualRouterPeeringsClient is the network Client -type VirtualRouterPeeringsClient struct { - BaseClient -} - -// NewVirtualRouterPeeringsClient creates an instance of the VirtualRouterPeeringsClient client. -func NewVirtualRouterPeeringsClient(subscriptionID string) VirtualRouterPeeringsClient { - return NewVirtualRouterPeeringsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualRouterPeeringsClientWithBaseURI creates an instance of the VirtualRouterPeeringsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewVirtualRouterPeeringsClientWithBaseURI(baseURI string, subscriptionID string) VirtualRouterPeeringsClient { - return VirtualRouterPeeringsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates the specified Virtual Router Peering. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualRouterName - the name of the Virtual Router. -// peeringName - the name of the Virtual Router Peering. -// parameters - parameters supplied to the create or update Virtual Router Peering operation. -func (client VirtualRouterPeeringsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string, parameters VirtualRouterPeering) (result VirtualRouterPeeringsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRouterPeeringsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VirtualRouterPeeringProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualRouterPeeringProperties.PeerAsn", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualRouterPeeringProperties.PeerAsn", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "parameters.VirtualRouterPeeringProperties.PeerAsn", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualRouterPeeringsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualRouterName, peeringName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualRouterPeeringsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string, parameters VirtualRouterPeering) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualRouterName": autorest.Encode("path", virtualRouterName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - parameters.Type = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}/peerings/{peeringName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualRouterPeeringsClient) CreateOrUpdateSender(req *http.Request) (future VirtualRouterPeeringsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualRouterPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualRouterPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified peering from a Virtual Router. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualRouterName - the name of the Virtual Router. -// peeringName - the name of the peering. -func (client VirtualRouterPeeringsClient) Delete(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string) (result VirtualRouterPeeringsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRouterPeeringsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualRouterName, peeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualRouterPeeringsClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualRouterName": autorest.Encode("path", virtualRouterName), - } - - const APIVersion = "2022-07-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/virtualRouters/{virtualRouterName}/peerings/{peeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualRouterPeeringsClient) DeleteSender(req *http.Request) (future VirtualRouterPeeringsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualRouterPeeringsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified Virtual Router Peering. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualRouterName - the name of the Virtual Router. -// peeringName - the name of the Virtual Router Peering. -func (client VirtualRouterPeeringsClient) Get(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string) (result VirtualRouterPeering, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRouterPeeringsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualRouterName, peeringName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsClient", "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.VirtualRouterPeeringsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualRouterPeeringsClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualRouterName string, peeringName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "peeringName": autorest.Encode("path", peeringName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualRouterName": autorest.Encode("path", virtualRouterName), - } - - const APIVersion = "2022-07-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/virtualRouters/{virtualRouterName}/peerings/{peeringName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualRouterPeeringsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualRouterPeeringsClient) GetResponder(resp *http.Response) (result VirtualRouterPeering, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all Virtual Router Peerings in a Virtual Router resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualRouterName - the name of the Virtual Router. -func (client VirtualRouterPeeringsClient) List(ctx context.Context, resourceGroupName string, virtualRouterName string) (result VirtualRouterPeeringListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRouterPeeringsClient.List") - defer func() { - sc := -1 - if result.vrplr.Response.Response != nil { - sc = result.vrplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName, virtualRouterName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vrplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsClient", "List", resp, "Failure sending request") - return - } - - result.vrplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsClient", "List", resp, "Failure responding to request") - return - } - if result.vrplr.hasNextLink() && result.vrplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualRouterPeeringsClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualRouterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualRouterName": autorest.Encode("path", virtualRouterName), - } - - const APIVersion = "2022-07-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/virtualRouters/{virtualRouterName}/peerings", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualRouterPeeringsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualRouterPeeringsClient) ListResponder(resp *http.Response) (result VirtualRouterPeeringListResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualRouterPeeringsClient) listNextResults(ctx context.Context, lastResults VirtualRouterPeeringListResult) (result VirtualRouterPeeringListResult, err error) { - req, err := lastResults.virtualRouterPeeringListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRouterPeeringsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualRouterPeeringsClient) ListComplete(ctx context.Context, resourceGroupName string, virtualRouterName string) (result VirtualRouterPeeringListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRouterPeeringsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName, virtualRouterName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualrouters.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualrouters.go deleted file mode 100644 index 83c98525aa..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualrouters.go +++ /dev/null @@ -1,513 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualRoutersClient is the network Client -type VirtualRoutersClient struct { - BaseClient -} - -// NewVirtualRoutersClient creates an instance of the VirtualRoutersClient client. -func NewVirtualRoutersClient(subscriptionID string) VirtualRoutersClient { - return NewVirtualRoutersClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualRoutersClientWithBaseURI creates an instance of the VirtualRoutersClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVirtualRoutersClientWithBaseURI(baseURI string, subscriptionID string) VirtualRoutersClient { - return VirtualRoutersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates the specified Virtual Router. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualRouterName - the name of the Virtual Router. -// parameters - parameters supplied to the create or update Virtual Router. -func (client VirtualRoutersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualRouterName string, parameters VirtualRouter) (result VirtualRoutersCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRoutersClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VirtualRouterPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualRouterPropertiesFormat.VirtualRouterAsn", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualRouterPropertiesFormat.VirtualRouterAsn", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "parameters.VirtualRouterPropertiesFormat.VirtualRouterAsn", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.VirtualRoutersClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualRouterName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualRoutersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualRouterName string, parameters VirtualRouter) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualRouterName": autorest.Encode("path", virtualRouterName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualRoutersClient) CreateOrUpdateSender(req *http.Request) (future VirtualRoutersCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualRoutersClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualRouter, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes the specified Virtual Router. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualRouterName - the name of the Virtual Router. -func (client VirtualRoutersClient) Delete(ctx context.Context, resourceGroupName string, virtualRouterName string) (result VirtualRoutersDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRoutersClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualRouterName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualRoutersClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualRouterName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualRouterName": autorest.Encode("path", virtualRouterName), - } - - const APIVersion = "2022-07-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/virtualRouters/{virtualRouterName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualRoutersClient) DeleteSender(req *http.Request) (future VirtualRoutersDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualRoutersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified Virtual Router. -// Parameters: -// resourceGroupName - the name of the resource group. -// virtualRouterName - the name of the Virtual Router. -// expand - expands referenced resources. -func (client VirtualRoutersClient) Get(ctx context.Context, resourceGroupName string, virtualRouterName string, expand string) (result VirtualRouter, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRoutersClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualRouterName, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "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.VirtualRoutersClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualRoutersClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualRouterName string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualRouterName": autorest.Encode("path", virtualRouterName), - } - - const APIVersion = "2022-07-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/virtualRouters/{virtualRouterName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualRoutersClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualRoutersClient) GetResponder(resp *http.Response) (result VirtualRouter, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List gets all the Virtual Routers in a subscription. -func (client VirtualRoutersClient) List(ctx context.Context) (result VirtualRouterListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRoutersClient.List") - defer func() { - sc := -1 - if result.vrlr.Response.Response != nil { - sc = result.vrlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.vrlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "List", resp, "Failure sending request") - return - } - - result.vrlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "List", resp, "Failure responding to request") - return - } - if result.vrlr.hasNextLink() && result.vrlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualRoutersClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualRouters", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualRoutersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualRoutersClient) ListResponder(resp *http.Response) (result VirtualRouterListResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualRoutersClient) listNextResults(ctx context.Context, lastResults VirtualRouterListResult) (result VirtualRouterListResult, err error) { - req, err := lastResults.virtualRouterListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualRoutersClient) ListComplete(ctx context.Context) (result VirtualRouterListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRoutersClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all Virtual Routers in a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client VirtualRoutersClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result VirtualRouterListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRoutersClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.vrlr.Response.Response != nil { - sc = result.vrlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.vrlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.vrlr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.vrlr.hasNextLink() && result.vrlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client VirtualRoutersClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/virtualRouters", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualRoutersClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client VirtualRoutersClient) ListByResourceGroupResponder(resp *http.Response) (result VirtualRouterListResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualRoutersClient) listByResourceGroupNextResults(ctx context.Context, lastResults VirtualRouterListResult) (result VirtualRouterListResult, err error) { - req, err := lastResults.virtualRouterListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualRoutersClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualRoutersClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result VirtualRouterListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualRoutersClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualwans.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualwans.go deleted file mode 100644 index 840147910e..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/virtualwans.go +++ /dev/null @@ -1,576 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VirtualWansClient is the network Client -type VirtualWansClient struct { - BaseClient -} - -// NewVirtualWansClient creates an instance of the VirtualWansClient client. -func NewVirtualWansClient(subscriptionID string) VirtualWansClient { - return NewVirtualWansClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVirtualWansClientWithBaseURI creates an instance of the VirtualWansClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVirtualWansClientWithBaseURI(baseURI string, subscriptionID string) VirtualWansClient { - return VirtualWansClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a VirtualWAN resource if it doesn't exist else updates the existing VirtualWAN. -// Parameters: -// resourceGroupName - the resource group name of the VirtualWan. -// virtualWANName - the name of the VirtualWAN being created or updated. -// wANParameters - parameters supplied to create or update VirtualWAN. -func (client VirtualWansClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualWANName string, wANParameters VirtualWAN) (result VirtualWansCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, virtualWANName, wANParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualWansClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, virtualWANName string, wANParameters VirtualWAN) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "VirtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - wANParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{VirtualWANName}", pathParameters), - autorest.WithJSON(wANParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualWansClient) CreateOrUpdateSender(req *http.Request) (future VirtualWansCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VirtualWansClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualWAN, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a VirtualWAN. -// Parameters: -// resourceGroupName - the resource group name of the VirtualWan. -// virtualWANName - the name of the VirtualWAN being deleted. -func (client VirtualWansClient) Delete(ctx context.Context, resourceGroupName string, virtualWANName string) (result VirtualWansDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, virtualWANName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VirtualWansClient) DeletePreparer(ctx context.Context, resourceGroupName string, virtualWANName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "VirtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2022-07-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/virtualWans/{VirtualWANName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualWansClient) DeleteSender(req *http.Request) (future VirtualWansDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VirtualWansClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a VirtualWAN. -// Parameters: -// resourceGroupName - the resource group name of the VirtualWan. -// virtualWANName - the name of the VirtualWAN being retrieved. -func (client VirtualWansClient) Get(ctx context.Context, resourceGroupName string, virtualWANName string) (result VirtualWAN, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, virtualWANName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "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.VirtualWansClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VirtualWansClient) GetPreparer(ctx context.Context, resourceGroupName string, virtualWANName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "VirtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2022-07-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/virtualWans/{VirtualWANName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualWansClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VirtualWansClient) GetResponder(resp *http.Response) (result VirtualWAN, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the VirtualWANs in a subscription. -func (client VirtualWansClient) List(ctx context.Context) (result ListVirtualWANsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.List") - defer func() { - sc := -1 - if result.lvwnr.Response.Response != nil { - sc = result.lvwnr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lvwnr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "List", resp, "Failure sending request") - return - } - - result.lvwnr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "List", resp, "Failure responding to request") - return - } - if result.lvwnr.hasNextLink() && result.lvwnr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VirtualWansClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualWans", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualWansClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VirtualWansClient) ListResponder(resp *http.Response) (result ListVirtualWANsResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualWansClient) listNextResults(ctx context.Context, lastResults ListVirtualWANsResult) (result ListVirtualWANsResult, err error) { - req, err := lastResults.listVirtualWANsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualWansClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualWansClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualWansClient) ListComplete(ctx context.Context) (result ListVirtualWANsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all the VirtualWANs in a resource group. -// Parameters: -// resourceGroupName - the resource group name of the VirtualWan. -func (client VirtualWansClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListVirtualWANsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.lvwnr.Response.Response != nil { - sc = result.lvwnr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.lvwnr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.lvwnr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.lvwnr.hasNextLink() && result.lvwnr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client VirtualWansClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/virtualWans", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualWansClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client VirtualWansClient) ListByResourceGroupResponder(resp *http.Response) (result ListVirtualWANsResult, err error) { - err = autorest.Respond( - resp, - 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 VirtualWansClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListVirtualWANsResult) (result ListVirtualWANsResult, err error) { - req, err := lastResults.listVirtualWANsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualWansClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualWansClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client VirtualWansClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListVirtualWANsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates a VirtualWAN tags. -// Parameters: -// resourceGroupName - the resource group name of the VirtualWan. -// virtualWANName - the name of the VirtualWAN being updated. -// wANParameters - parameters supplied to Update VirtualWAN tags. -func (client VirtualWansClient) UpdateTags(ctx context.Context, resourceGroupName string, virtualWANName string, wANParameters TagsObject) (result VirtualWAN, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VirtualWansClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, virtualWANName, wANParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualWansClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VirtualWansClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, virtualWANName string, wANParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "VirtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{VirtualWANName}", pathParameters), - autorest.WithJSON(wANParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VirtualWansClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VirtualWansClient) UpdateTagsResponder(resp *http.Response) (result VirtualWAN, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnconnections.go deleted file mode 100644 index 48663fa5f9..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnconnections.go +++ /dev/null @@ -1,568 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VpnConnectionsClient is the network Client -type VpnConnectionsClient struct { - BaseClient -} - -// NewVpnConnectionsClient creates an instance of the VpnConnectionsClient client. -func NewVpnConnectionsClient(subscriptionID string) VpnConnectionsClient { - return NewVpnConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVpnConnectionsClientWithBaseURI creates an instance of the VpnConnectionsClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVpnConnectionsClientWithBaseURI(baseURI string, subscriptionID string) VpnConnectionsClient { - return VpnConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing -// connection. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// connectionName - the name of the connection. -// vpnConnectionParameters - parameters supplied to create or Update a VPN Connection. -func (client VpnConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, vpnConnectionParameters VpnConnection) (result VpnConnectionsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, gatewayName, connectionName, vpnConnectionParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VpnConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, vpnConnectionParameters VpnConnection) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - vpnConnectionParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}", pathParameters), - autorest.WithJSON(vpnConnectionParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VpnConnectionsClient) CreateOrUpdateSender(req *http.Request) (future VpnConnectionsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VpnConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result VpnConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a vpn connection. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// connectionName - the name of the connection. -func (client VpnConnectionsClient) Delete(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (result VpnConnectionsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, gatewayName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VpnConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways/{gatewayName}/vpnConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VpnConnectionsClient) DeleteSender(req *http.Request) (future VpnConnectionsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VpnConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a vpn connection. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// connectionName - the name of the vpn connection. -func (client VpnConnectionsClient) Get(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (result VpnConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, gatewayName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "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.VpnConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VpnConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways/{gatewayName}/vpnConnections/{connectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VpnConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VpnConnectionsClient) GetResponder(resp *http.Response) (result VpnConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByVpnGateway retrieves all vpn connections for a particular virtual wan vpn gateway. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -func (client VpnConnectionsClient) ListByVpnGateway(ctx context.Context, resourceGroupName string, gatewayName string) (result ListVpnConnectionsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.ListByVpnGateway") - defer func() { - sc := -1 - if result.lvcr.Response.Response != nil { - sc = result.lvcr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByVpnGatewayNextResults - req, err := client.ListByVpnGatewayPreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "ListByVpnGateway", nil, "Failure preparing request") - return - } - - resp, err := client.ListByVpnGatewaySender(req) - if err != nil { - result.lvcr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "ListByVpnGateway", resp, "Failure sending request") - return - } - - result.lvcr, err = client.ListByVpnGatewayResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "ListByVpnGateway", resp, "Failure responding to request") - return - } - if result.lvcr.hasNextLink() && result.lvcr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByVpnGatewayPreparer prepares the ListByVpnGateway request. -func (client VpnConnectionsClient) ListByVpnGatewayPreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways/{gatewayName}/vpnConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByVpnGatewaySender sends the ListByVpnGateway request. The method will close the -// http.Response Body if it receives an error. -func (client VpnConnectionsClient) ListByVpnGatewaySender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByVpnGatewayResponder handles the response to the ListByVpnGateway request. The method always -// closes the http.Response Body. -func (client VpnConnectionsClient) ListByVpnGatewayResponder(resp *http.Response) (result ListVpnConnectionsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByVpnGatewayNextResults retrieves the next set of results, if any. -func (client VpnConnectionsClient) listByVpnGatewayNextResults(ctx context.Context, lastResults ListVpnConnectionsResult) (result ListVpnConnectionsResult, err error) { - req, err := lastResults.listVpnConnectionsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "listByVpnGatewayNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByVpnGatewaySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "listByVpnGatewayNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByVpnGatewayResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "listByVpnGatewayNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByVpnGatewayComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnConnectionsClient) ListByVpnGatewayComplete(ctx context.Context, resourceGroupName string, gatewayName string) (result ListVpnConnectionsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.ListByVpnGateway") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByVpnGateway(ctx, resourceGroupName, gatewayName) - return -} - -// StartPacketCapture starts packet capture on Vpn connection in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// gatewayName - the name of the gateway. -// vpnConnectionName - the name of the vpn connection. -// parameters - vpn Connection packet capture parameters supplied to start packet capture on gateway -// connection. -func (client VpnConnectionsClient) StartPacketCapture(ctx context.Context, resourceGroupName string, gatewayName string, vpnConnectionName string, parameters *VpnConnectionPacketCaptureStartParameters) (result VpnConnectionsStartPacketCaptureFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.StartPacketCapture") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPacketCapturePreparer(ctx, resourceGroupName, gatewayName, vpnConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "StartPacketCapture", nil, "Failure preparing request") - return - } - - result, err = client.StartPacketCaptureSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "StartPacketCapture", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPacketCapturePreparer prepares the StartPacketCapture request. -func (client VpnConnectionsClient) StartPacketCapturePreparer(ctx context.Context, resourceGroupName string, gatewayName string, vpnConnectionName string, parameters *VpnConnectionPacketCaptureStartParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnConnectionName": autorest.Encode("path", vpnConnectionName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{vpnConnectionName}/startpacketcapture", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if parameters != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(parameters)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartPacketCaptureSender sends the StartPacketCapture request. The method will close the -// http.Response Body if it receives an error. -func (client VpnConnectionsClient) StartPacketCaptureSender(req *http.Request) (future VpnConnectionsStartPacketCaptureFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartPacketCaptureResponder handles the response to the StartPacketCapture request. The method always -// closes the http.Response Body. -func (client VpnConnectionsClient) StartPacketCaptureResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// StopPacketCapture stops packet capture on Vpn connection in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// gatewayName - the name of the gateway. -// vpnConnectionName - the name of the vpn connection. -// parameters - vpn Connection packet capture parameters supplied to stop packet capture on gateway connection. -func (client VpnConnectionsClient) StopPacketCapture(ctx context.Context, resourceGroupName string, gatewayName string, vpnConnectionName string, parameters *VpnConnectionPacketCaptureStopParameters) (result VpnConnectionsStopPacketCaptureFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.StopPacketCapture") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPacketCapturePreparer(ctx, resourceGroupName, gatewayName, vpnConnectionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "StopPacketCapture", nil, "Failure preparing request") - return - } - - result, err = client.StopPacketCaptureSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "StopPacketCapture", result.Response(), "Failure sending request") - return - } - - return -} - -// StopPacketCapturePreparer prepares the StopPacketCapture request. -func (client VpnConnectionsClient) StopPacketCapturePreparer(ctx context.Context, resourceGroupName string, gatewayName string, vpnConnectionName string, parameters *VpnConnectionPacketCaptureStopParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnConnectionName": autorest.Encode("path", vpnConnectionName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{vpnConnectionName}/stoppacketcapture", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if parameters != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(parameters)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StopPacketCaptureSender sends the StopPacketCapture request. The method will close the -// http.Response Body if it receives an error. -func (client VpnConnectionsClient) StopPacketCaptureSender(req *http.Request) (future VpnConnectionsStopPacketCaptureFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StopPacketCaptureResponder handles the response to the StopPacketCapture request. The method always -// closes the http.Response Body. -func (client VpnConnectionsClient) StopPacketCaptureResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpngateways.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpngateways.go deleted file mode 100644 index 19e473877d..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpngateways.go +++ /dev/null @@ -1,842 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VpnGatewaysClient is the network Client -type VpnGatewaysClient struct { - BaseClient -} - -// NewVpnGatewaysClient creates an instance of the VpnGatewaysClient client. -func NewVpnGatewaysClient(subscriptionID string) VpnGatewaysClient { - return NewVpnGatewaysClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVpnGatewaysClientWithBaseURI creates an instance of the VpnGatewaysClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVpnGatewaysClientWithBaseURI(baseURI string, subscriptionID string) VpnGatewaysClient { - return VpnGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// vpnGatewayParameters - parameters supplied to create or Update a virtual wan vpn gateway. -func (client VpnGatewaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters VpnGateway) (result VpnGatewaysCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: vpnGatewayParameters, - Constraints: []validation.Constraint{{Target: "vpnGatewayParameters.VpnGatewayProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "vpnGatewayParameters.VpnGatewayProperties.BgpSettings", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "vpnGatewayParameters.VpnGatewayProperties.BgpSettings.Asn", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "vpnGatewayParameters.VpnGatewayProperties.BgpSettings.Asn", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "vpnGatewayParameters.VpnGatewayProperties.BgpSettings.Asn", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.VpnGatewaysClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, gatewayName, vpnGatewayParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VpnGatewaysClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters VpnGateway) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - vpnGatewayParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}", pathParameters), - autorest.WithJSON(vpnGatewayParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) CreateOrUpdateSender(req *http.Request) (future VpnGatewaysCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result VpnGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a virtual wan vpn gateway. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -func (client VpnGatewaysClient) Delete(ctx context.Context, resourceGroupName string, gatewayName string) (result VpnGatewaysDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VpnGatewaysClient) DeletePreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways/{gatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) DeleteSender(req *http.Request) (future VpnGatewaysDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a virtual wan vpn gateway. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -func (client VpnGatewaysClient) Get(ctx context.Context, resourceGroupName string, gatewayName string) (result VpnGateway, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "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.VpnGatewaysClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VpnGatewaysClient) GetPreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways/{gatewayName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) GetResponder(resp *http.Response) (result VpnGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the VpnGateways in a subscription. -func (client VpnGatewaysClient) List(ctx context.Context) (result ListVpnGatewaysResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.List") - defer func() { - sc := -1 - if result.lvgr.Response.Response != nil { - sc = result.lvgr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lvgr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "List", resp, "Failure sending request") - return - } - - result.lvgr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "List", resp, "Failure responding to request") - return - } - if result.lvgr.hasNextLink() && result.lvgr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VpnGatewaysClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) ListResponder(resp *http.Response) (result ListVpnGatewaysResult, err error) { - err = autorest.Respond( - resp, - 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 VpnGatewaysClient) listNextResults(ctx context.Context, lastResults ListVpnGatewaysResult) (result ListVpnGatewaysResult, err error) { - req, err := lastResults.listVpnGatewaysResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnGatewaysClient) ListComplete(ctx context.Context) (result ListVpnGatewaysResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all the VpnGateways in a resource group. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -func (client VpnGatewaysClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListVpnGatewaysResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.lvgr.Response.Response != nil { - sc = result.lvgr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.lvgr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.lvgr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.lvgr.hasNextLink() && result.lvgr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client VpnGatewaysClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) ListByResourceGroupResponder(resp *http.Response) (result ListVpnGatewaysResult, err error) { - err = autorest.Respond( - resp, - 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 VpnGatewaysClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListVpnGatewaysResult) (result ListVpnGatewaysResult, err error) { - req, err := lastResults.listVpnGatewaysResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnGatewaysClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListVpnGatewaysResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// Reset resets the primary of the vpn gateway in the specified resource group. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -func (client VpnGatewaysClient) Reset(ctx context.Context, resourceGroupName string, gatewayName string) (result VpnGatewaysResetFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.Reset") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ResetPreparer(ctx, resourceGroupName, gatewayName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "Reset", nil, "Failure preparing request") - return - } - - result, err = client.ResetSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "Reset", result.Response(), "Failure sending request") - return - } - - return -} - -// ResetPreparer prepares the Reset request. -func (client VpnGatewaysClient) ResetPreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways/{gatewayName}/reset", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ResetSender sends the Reset request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) ResetSender(req *http.Request) (future VpnGatewaysResetFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ResetResponder handles the response to the Reset request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) ResetResponder(resp *http.Response) (result VpnGateway, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// StartPacketCapture starts packet capture on vpn gateway in the specified resource group. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// parameters - vpn gateway packet capture parameters supplied to start packet capture on vpn gateway. -func (client VpnGatewaysClient) StartPacketCapture(ctx context.Context, resourceGroupName string, gatewayName string, parameters *VpnGatewayPacketCaptureStartParameters) (result VpnGatewaysStartPacketCaptureFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.StartPacketCapture") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StartPacketCapturePreparer(ctx, resourceGroupName, gatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "StartPacketCapture", nil, "Failure preparing request") - return - } - - result, err = client.StartPacketCaptureSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "StartPacketCapture", result.Response(), "Failure sending request") - return - } - - return -} - -// StartPacketCapturePreparer prepares the StartPacketCapture request. -func (client VpnGatewaysClient) StartPacketCapturePreparer(ctx context.Context, resourceGroupName string, gatewayName string, parameters *VpnGatewayPacketCaptureStartParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/startpacketcapture", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if parameters != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(parameters)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StartPacketCaptureSender sends the StartPacketCapture request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) StartPacketCaptureSender(req *http.Request) (future VpnGatewaysStartPacketCaptureFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StartPacketCaptureResponder handles the response to the StartPacketCapture request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) StartPacketCaptureResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// StopPacketCapture stops packet capture on vpn gateway in the specified resource group. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// parameters - vpn gateway packet capture parameters supplied to stop packet capture on vpn gateway. -func (client VpnGatewaysClient) StopPacketCapture(ctx context.Context, resourceGroupName string, gatewayName string, parameters *VpnGatewayPacketCaptureStopParameters) (result VpnGatewaysStopPacketCaptureFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.StopPacketCapture") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.StopPacketCapturePreparer(ctx, resourceGroupName, gatewayName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "StopPacketCapture", nil, "Failure preparing request") - return - } - - result, err = client.StopPacketCaptureSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "StopPacketCapture", result.Response(), "Failure sending request") - return - } - - return -} - -// StopPacketCapturePreparer prepares the StopPacketCapture request. -func (client VpnGatewaysClient) StopPacketCapturePreparer(ctx context.Context, resourceGroupName string, gatewayName string, parameters *VpnGatewayPacketCaptureStopParameters) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/stoppacketcapture", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if parameters != nil { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(parameters)) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// StopPacketCaptureSender sends the StopPacketCapture request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) StopPacketCaptureSender(req *http.Request) (future VpnGatewaysStopPacketCaptureFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// StopPacketCaptureResponder handles the response to the StopPacketCapture request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) StopPacketCaptureResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates virtual wan vpn gateway tags. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// vpnGatewayParameters - parameters supplied to update a virtual wan vpn gateway tags. -func (client VpnGatewaysClient) UpdateTags(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters TagsObject) (result VpnGatewaysUpdateTagsFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnGatewaysClient.UpdateTags") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, gatewayName, vpnGatewayParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "UpdateTags", nil, "Failure preparing request") - return - } - - result, err = client.UpdateTagsSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnGatewaysClient", "UpdateTags", result.Response(), "Failure sending request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VpnGatewaysClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, gatewayName string, vpnGatewayParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}", pathParameters), - autorest.WithJSON(vpnGatewayParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VpnGatewaysClient) UpdateTagsSender(req *http.Request) (future VpnGatewaysUpdateTagsFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VpnGatewaysClient) UpdateTagsResponder(resp *http.Response) (result VpnGateway, err error) { - err = autorest.Respond( - resp, - 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/services/network/mgmt/2022-07-01/network/vpnlinkconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnlinkconnections.go deleted file mode 100644 index 21927e1f1d..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnlinkconnections.go +++ /dev/null @@ -1,317 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VpnLinkConnectionsClient is the network Client -type VpnLinkConnectionsClient struct { - BaseClient -} - -// NewVpnLinkConnectionsClient creates an instance of the VpnLinkConnectionsClient client. -func NewVpnLinkConnectionsClient(subscriptionID string) VpnLinkConnectionsClient { - return NewVpnLinkConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVpnLinkConnectionsClientWithBaseURI creates an instance of the VpnLinkConnectionsClient client using a custom -// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure -// stack). -func NewVpnLinkConnectionsClientWithBaseURI(baseURI string, subscriptionID string) VpnLinkConnectionsClient { - return VpnLinkConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// GetIkeSas lists IKE Security Associations for Vpn Site Link Connection in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// gatewayName - the name of the gateway. -// connectionName - the name of the vpn connection. -// linkConnectionName - the name of the vpn link connection. -func (client VpnLinkConnectionsClient) GetIkeSas(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string) (result VpnLinkConnectionsGetIkeSasFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnLinkConnectionsClient.GetIkeSas") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetIkeSasPreparer(ctx, resourceGroupName, gatewayName, connectionName, linkConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnLinkConnectionsClient", "GetIkeSas", nil, "Failure preparing request") - return - } - - result, err = client.GetIkeSasSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnLinkConnectionsClient", "GetIkeSas", result.Response(), "Failure sending request") - return - } - - return -} - -// GetIkeSasPreparer prepares the GetIkeSas request. -func (client VpnLinkConnectionsClient) GetIkeSasPreparer(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "gatewayName": autorest.Encode("path", gatewayName), - "linkConnectionName": autorest.Encode("path", linkConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways/{gatewayName}/vpnConnections/{connectionName}/vpnLinkConnections/{linkConnectionName}/getikesas", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetIkeSasSender sends the GetIkeSas request. The method will close the -// http.Response Body if it receives an error. -func (client VpnLinkConnectionsClient) GetIkeSasSender(req *http.Request) (future VpnLinkConnectionsGetIkeSasFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetIkeSasResponder handles the response to the GetIkeSas request. The method always -// closes the http.Response Body. -func (client VpnLinkConnectionsClient) GetIkeSasResponder(resp *http.Response) (result String, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result.Value), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByVpnConnection retrieves all vpn site link connections for a particular virtual wan vpn gateway vpn connection. -// Parameters: -// resourceGroupName - the resource group name of the vpn gateway. -// gatewayName - the name of the gateway. -// connectionName - the name of the vpn connection. -func (client VpnLinkConnectionsClient) ListByVpnConnection(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (result ListVpnSiteLinkConnectionsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnLinkConnectionsClient.ListByVpnConnection") - defer func() { - sc := -1 - if result.lvslcr.Response.Response != nil { - sc = result.lvslcr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByVpnConnectionNextResults - req, err := client.ListByVpnConnectionPreparer(ctx, resourceGroupName, gatewayName, connectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnLinkConnectionsClient", "ListByVpnConnection", nil, "Failure preparing request") - return - } - - resp, err := client.ListByVpnConnectionSender(req) - if err != nil { - result.lvslcr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnLinkConnectionsClient", "ListByVpnConnection", resp, "Failure sending request") - return - } - - result.lvslcr, err = client.ListByVpnConnectionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnLinkConnectionsClient", "ListByVpnConnection", resp, "Failure responding to request") - return - } - if result.lvslcr.hasNextLink() && result.lvslcr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByVpnConnectionPreparer prepares the ListByVpnConnection request. -func (client VpnLinkConnectionsClient) ListByVpnConnectionPreparer(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "gatewayName": autorest.Encode("path", gatewayName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways/{gatewayName}/vpnConnections/{connectionName}/vpnLinkConnections", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByVpnConnectionSender sends the ListByVpnConnection request. The method will close the -// http.Response Body if it receives an error. -func (client VpnLinkConnectionsClient) ListByVpnConnectionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByVpnConnectionResponder handles the response to the ListByVpnConnection request. The method always -// closes the http.Response Body. -func (client VpnLinkConnectionsClient) ListByVpnConnectionResponder(resp *http.Response) (result ListVpnSiteLinkConnectionsResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByVpnConnectionNextResults retrieves the next set of results, if any. -func (client VpnLinkConnectionsClient) listByVpnConnectionNextResults(ctx context.Context, lastResults ListVpnSiteLinkConnectionsResult) (result ListVpnSiteLinkConnectionsResult, err error) { - req, err := lastResults.listVpnSiteLinkConnectionsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnLinkConnectionsClient", "listByVpnConnectionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByVpnConnectionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnLinkConnectionsClient", "listByVpnConnectionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByVpnConnectionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnLinkConnectionsClient", "listByVpnConnectionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByVpnConnectionComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnLinkConnectionsClient) ListByVpnConnectionComplete(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (result ListVpnSiteLinkConnectionsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnLinkConnectionsClient.ListByVpnConnection") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByVpnConnection(ctx, resourceGroupName, gatewayName, connectionName) - return -} - -// ResetConnection resets the VpnLink connection specified. -// Parameters: -// resourceGroupName - the name of the resource group. -// gatewayName - the name of the gateway. -// connectionName - the name of the vpn connection. -// linkConnectionName - the name of the vpn link connection. -func (client VpnLinkConnectionsClient) ResetConnection(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string) (result VpnLinkConnectionsResetConnectionFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnLinkConnectionsClient.ResetConnection") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ResetConnectionPreparer(ctx, resourceGroupName, gatewayName, connectionName, linkConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnLinkConnectionsClient", "ResetConnection", nil, "Failure preparing request") - return - } - - result, err = client.ResetConnectionSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnLinkConnectionsClient", "ResetConnection", result.Response(), "Failure sending request") - return - } - - return -} - -// ResetConnectionPreparer prepares the ResetConnection request. -func (client VpnLinkConnectionsClient) ResetConnectionPreparer(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "gatewayName": autorest.Encode("path", gatewayName), - "linkConnectionName": autorest.Encode("path", linkConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways/{gatewayName}/vpnConnections/{connectionName}/vpnLinkConnections/{linkConnectionName}/resetconnection", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ResetConnectionSender sends the ResetConnection request. The method will close the -// http.Response Body if it receives an error. -func (client VpnLinkConnectionsClient) ResetConnectionSender(req *http.Request) (future VpnLinkConnectionsResetConnectionFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ResetConnectionResponder handles the response to the ResetConnection request. The method always -// closes the http.Response Body. -func (client VpnLinkConnectionsClient) ResetConnectionResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnserverconfigurations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnserverconfigurations.go deleted file mode 100644 index 28d3c9535c..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnserverconfigurations.go +++ /dev/null @@ -1,578 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VpnServerConfigurationsClient is the network Client -type VpnServerConfigurationsClient struct { - BaseClient -} - -// NewVpnServerConfigurationsClient creates an instance of the VpnServerConfigurationsClient client. -func NewVpnServerConfigurationsClient(subscriptionID string) VpnServerConfigurationsClient { - return NewVpnServerConfigurationsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVpnServerConfigurationsClientWithBaseURI creates an instance of the VpnServerConfigurationsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewVpnServerConfigurationsClientWithBaseURI(baseURI string, subscriptionID string) VpnServerConfigurationsClient { - return VpnServerConfigurationsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a VpnServerConfiguration resource if it doesn't exist else updates the existing -// VpnServerConfiguration. -// Parameters: -// resourceGroupName - the resource group name of the VpnServerConfiguration. -// vpnServerConfigurationName - the name of the VpnServerConfiguration being created or updated. -// vpnServerConfigurationParameters - parameters supplied to create or update VpnServerConfiguration. -func (client VpnServerConfigurationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, vpnServerConfigurationParameters VpnServerConfiguration) (result VpnServerConfigurationsCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnServerConfigurationsClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, vpnServerConfigurationName, vpnServerConfigurationParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VpnServerConfigurationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, vpnServerConfigurationParameters VpnServerConfiguration) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnServerConfigurationName": autorest.Encode("path", vpnServerConfigurationName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - vpnServerConfigurationParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}", pathParameters), - autorest.WithJSON(vpnServerConfigurationParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VpnServerConfigurationsClient) CreateOrUpdateSender(req *http.Request) (future VpnServerConfigurationsCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VpnServerConfigurationsClient) CreateOrUpdateResponder(resp *http.Response) (result VpnServerConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a VpnServerConfiguration. -// Parameters: -// resourceGroupName - the resource group name of the VpnServerConfiguration. -// vpnServerConfigurationName - the name of the VpnServerConfiguration being deleted. -func (client VpnServerConfigurationsClient) Delete(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string) (result VpnServerConfigurationsDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnServerConfigurationsClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, vpnServerConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VpnServerConfigurationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnServerConfigurationName": autorest.Encode("path", vpnServerConfigurationName), - } - - const APIVersion = "2022-07-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/vpnServerConfigurations/{vpnServerConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VpnServerConfigurationsClient) DeleteSender(req *http.Request) (future VpnServerConfigurationsDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VpnServerConfigurationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a VpnServerConfiguration. -// Parameters: -// resourceGroupName - the resource group name of the VpnServerConfiguration. -// vpnServerConfigurationName - the name of the VpnServerConfiguration being retrieved. -func (client VpnServerConfigurationsClient) Get(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string) (result VpnServerConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnServerConfigurationsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, vpnServerConfigurationName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "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.VpnServerConfigurationsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VpnServerConfigurationsClient) GetPreparer(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnServerConfigurationName": autorest.Encode("path", vpnServerConfigurationName), - } - - const APIVersion = "2022-07-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/vpnServerConfigurations/{vpnServerConfigurationName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VpnServerConfigurationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VpnServerConfigurationsClient) GetResponder(resp *http.Response) (result VpnServerConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the VpnServerConfigurations in a subscription. -func (client VpnServerConfigurationsClient) List(ctx context.Context) (result ListVpnServerConfigurationsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnServerConfigurationsClient.List") - defer func() { - sc := -1 - if result.lvscr.Response.Response != nil { - sc = result.lvscr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lvscr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "List", resp, "Failure sending request") - return - } - - result.lvscr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "List", resp, "Failure responding to request") - return - } - if result.lvscr.hasNextLink() && result.lvscr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VpnServerConfigurationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnServerConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VpnServerConfigurationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VpnServerConfigurationsClient) ListResponder(resp *http.Response) (result ListVpnServerConfigurationsResult, err error) { - err = autorest.Respond( - resp, - 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 VpnServerConfigurationsClient) listNextResults(ctx context.Context, lastResults ListVpnServerConfigurationsResult) (result ListVpnServerConfigurationsResult, err error) { - req, err := lastResults.listVpnServerConfigurationsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnServerConfigurationsClient) ListComplete(ctx context.Context) (result ListVpnServerConfigurationsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnServerConfigurationsClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all the vpnServerConfigurations in a resource group. -// Parameters: -// resourceGroupName - the resource group name of the VpnServerConfiguration. -func (client VpnServerConfigurationsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListVpnServerConfigurationsResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnServerConfigurationsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.lvscr.Response.Response != nil { - sc = result.lvscr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.lvscr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.lvscr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.lvscr.hasNextLink() && result.lvscr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client VpnServerConfigurationsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnServerConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client VpnServerConfigurationsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client VpnServerConfigurationsClient) ListByResourceGroupResponder(resp *http.Response) (result ListVpnServerConfigurationsResult, err error) { - err = autorest.Respond( - resp, - 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 VpnServerConfigurationsClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListVpnServerConfigurationsResult) (result ListVpnServerConfigurationsResult, err error) { - req, err := lastResults.listVpnServerConfigurationsResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnServerConfigurationsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListVpnServerConfigurationsResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnServerConfigurationsClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates VpnServerConfiguration tags. -// Parameters: -// resourceGroupName - the resource group name of the VpnServerConfiguration. -// vpnServerConfigurationName - the name of the VpnServerConfiguration being updated. -// vpnServerConfigurationParameters - parameters supplied to update VpnServerConfiguration tags. -func (client VpnServerConfigurationsClient) UpdateTags(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, vpnServerConfigurationParameters TagsObject) (result VpnServerConfiguration, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnServerConfigurationsClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, vpnServerConfigurationName, vpnServerConfigurationParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VpnServerConfigurationsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, vpnServerConfigurationName string, vpnServerConfigurationParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnServerConfigurationName": autorest.Encode("path", vpnServerConfigurationName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}", pathParameters), - autorest.WithJSON(vpnServerConfigurationParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VpnServerConfigurationsClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VpnServerConfigurationsClient) UpdateTagsResponder(resp *http.Response) (result VpnServerConfiguration, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnserverconfigurationsassociatedwithvirtualwan.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnserverconfigurationsassociatedwithvirtualwan.go deleted file mode 100644 index fa7215ff90..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnserverconfigurationsassociatedwithvirtualwan.go +++ /dev/null @@ -1,112 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VpnServerConfigurationsAssociatedWithVirtualWanClient is the network Client -type VpnServerConfigurationsAssociatedWithVirtualWanClient struct { - BaseClient -} - -// NewVpnServerConfigurationsAssociatedWithVirtualWanClient creates an instance of the -// VpnServerConfigurationsAssociatedWithVirtualWanClient client. -func NewVpnServerConfigurationsAssociatedWithVirtualWanClient(subscriptionID string) VpnServerConfigurationsAssociatedWithVirtualWanClient { - return NewVpnServerConfigurationsAssociatedWithVirtualWanClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVpnServerConfigurationsAssociatedWithVirtualWanClientWithBaseURI creates an instance of the -// VpnServerConfigurationsAssociatedWithVirtualWanClient client using a custom endpoint. Use this when interacting -// with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVpnServerConfigurationsAssociatedWithVirtualWanClientWithBaseURI(baseURI string, subscriptionID string) VpnServerConfigurationsAssociatedWithVirtualWanClient { - return VpnServerConfigurationsAssociatedWithVirtualWanClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// List gives the list of VpnServerConfigurations associated with Virtual Wan in a resource group. -// Parameters: -// resourceGroupName - the resource group name. -// virtualWANName - the name of the VirtualWAN whose associated VpnServerConfigurations is needed. -func (client VpnServerConfigurationsAssociatedWithVirtualWanClient) List(ctx context.Context, resourceGroupName string, virtualWANName string) (result VpnServerConfigurationsAssociatedWithVirtualWanListFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnServerConfigurationsAssociatedWithVirtualWanClient.List") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, resourceGroupName, virtualWANName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsAssociatedWithVirtualWanClient", "List", nil, "Failure preparing request") - return - } - - result, err = client.ListSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnServerConfigurationsAssociatedWithVirtualWanClient", "List", result.Response(), "Failure sending request") - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VpnServerConfigurationsAssociatedWithVirtualWanClient) ListPreparer(ctx context.Context, resourceGroupName string, virtualWANName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2022-07-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/virtualWans/{virtualWANName}/vpnServerConfigurations", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VpnServerConfigurationsAssociatedWithVirtualWanClient) ListSender(req *http.Request) (future VpnServerConfigurationsAssociatedWithVirtualWanListFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VpnServerConfigurationsAssociatedWithVirtualWanClient) ListResponder(resp *http.Response) (result VpnServerConfigurationsResponse, err error) { - err = autorest.Respond( - resp, - 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/services/network/mgmt/2022-07-01/network/vpnsitelinkconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnsitelinkconnections.go deleted file mode 100644 index e39710eedb..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnsitelinkconnections.go +++ /dev/null @@ -1,112 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VpnSiteLinkConnectionsClient is the network Client -type VpnSiteLinkConnectionsClient struct { - BaseClient -} - -// NewVpnSiteLinkConnectionsClient creates an instance of the VpnSiteLinkConnectionsClient client. -func NewVpnSiteLinkConnectionsClient(subscriptionID string) VpnSiteLinkConnectionsClient { - return NewVpnSiteLinkConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVpnSiteLinkConnectionsClientWithBaseURI creates an instance of the VpnSiteLinkConnectionsClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewVpnSiteLinkConnectionsClientWithBaseURI(baseURI string, subscriptionID string) VpnSiteLinkConnectionsClient { - return VpnSiteLinkConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get retrieves the details of a vpn site link connection. -// Parameters: -// resourceGroupName - the resource group name of the VpnGateway. -// gatewayName - the name of the gateway. -// connectionName - the name of the vpn connection. -// linkConnectionName - the name of the vpn connection. -func (client VpnSiteLinkConnectionsClient) Get(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string) (result VpnSiteLinkConnection, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSiteLinkConnectionsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, gatewayName, connectionName, linkConnectionName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSiteLinkConnectionsClient", "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.VpnSiteLinkConnectionsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSiteLinkConnectionsClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VpnSiteLinkConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, linkConnectionName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "connectionName": autorest.Encode("path", connectionName), - "gatewayName": autorest.Encode("path", gatewayName), - "linkConnectionName": autorest.Encode("path", linkConnectionName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnGateways/{gatewayName}/vpnConnections/{connectionName}/vpnLinkConnections/{linkConnectionName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSiteLinkConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VpnSiteLinkConnectionsClient) GetResponder(resp *http.Response) (result VpnSiteLinkConnection, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnsitelinks.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnsitelinks.go deleted file mode 100644 index 966f7e7a4c..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnsitelinks.go +++ /dev/null @@ -1,227 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VpnSiteLinksClient is the network Client -type VpnSiteLinksClient struct { - BaseClient -} - -// NewVpnSiteLinksClient creates an instance of the VpnSiteLinksClient client. -func NewVpnSiteLinksClient(subscriptionID string) VpnSiteLinksClient { - return NewVpnSiteLinksClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVpnSiteLinksClientWithBaseURI creates an instance of the VpnSiteLinksClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVpnSiteLinksClientWithBaseURI(baseURI string, subscriptionID string) VpnSiteLinksClient { - return VpnSiteLinksClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get retrieves the details of a VPN site link. -// Parameters: -// resourceGroupName - the resource group name of the VpnSite. -// vpnSiteName - the name of the VpnSite. -// vpnSiteLinkName - the name of the VpnSiteLink being retrieved. -func (client VpnSiteLinksClient) Get(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteLinkName string) (result VpnSiteLink, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSiteLinksClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, vpnSiteName, vpnSiteLinkName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSiteLinksClient", "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.VpnSiteLinksClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSiteLinksClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VpnSiteLinksClient) GetPreparer(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteLinkName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnSiteLinkName": autorest.Encode("path", vpnSiteLinkName), - "vpnSiteName": autorest.Encode("path", vpnSiteName), - } - - const APIVersion = "2022-07-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/vpnSites/{vpnSiteName}/vpnSiteLinks/{vpnSiteLinkName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSiteLinksClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VpnSiteLinksClient) GetResponder(resp *http.Response) (result VpnSiteLink, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByVpnSite lists all the vpnSiteLinks in a resource group for a vpn site. -// Parameters: -// resourceGroupName - the resource group name of the VpnSite. -// vpnSiteName - the name of the VpnSite. -func (client VpnSiteLinksClient) ListByVpnSite(ctx context.Context, resourceGroupName string, vpnSiteName string) (result ListVpnSiteLinksResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSiteLinksClient.ListByVpnSite") - defer func() { - sc := -1 - if result.lvslr.Response.Response != nil { - sc = result.lvslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByVpnSiteNextResults - req, err := client.ListByVpnSitePreparer(ctx, resourceGroupName, vpnSiteName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSiteLinksClient", "ListByVpnSite", nil, "Failure preparing request") - return - } - - resp, err := client.ListByVpnSiteSender(req) - if err != nil { - result.lvslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnSiteLinksClient", "ListByVpnSite", resp, "Failure sending request") - return - } - - result.lvslr, err = client.ListByVpnSiteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSiteLinksClient", "ListByVpnSite", resp, "Failure responding to request") - return - } - if result.lvslr.hasNextLink() && result.lvslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByVpnSitePreparer prepares the ListByVpnSite request. -func (client VpnSiteLinksClient) ListByVpnSitePreparer(ctx context.Context, resourceGroupName string, vpnSiteName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnSiteName": autorest.Encode("path", vpnSiteName), - } - - const APIVersion = "2022-07-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/vpnSites/{vpnSiteName}/vpnSiteLinks", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByVpnSiteSender sends the ListByVpnSite request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSiteLinksClient) ListByVpnSiteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByVpnSiteResponder handles the response to the ListByVpnSite request. The method always -// closes the http.Response Body. -func (client VpnSiteLinksClient) ListByVpnSiteResponder(resp *http.Response) (result ListVpnSiteLinksResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByVpnSiteNextResults retrieves the next set of results, if any. -func (client VpnSiteLinksClient) listByVpnSiteNextResults(ctx context.Context, lastResults ListVpnSiteLinksResult) (result ListVpnSiteLinksResult, err error) { - req, err := lastResults.listVpnSiteLinksResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnSiteLinksClient", "listByVpnSiteNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByVpnSiteSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnSiteLinksClient", "listByVpnSiteNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByVpnSiteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSiteLinksClient", "listByVpnSiteNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByVpnSiteComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnSiteLinksClient) ListByVpnSiteComplete(ctx context.Context, resourceGroupName string, vpnSiteName string) (result ListVpnSiteLinksResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSiteLinksClient.ListByVpnSite") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByVpnSite(ctx, resourceGroupName, vpnSiteName) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnsites.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnsites.go deleted file mode 100644 index 6baf98b822..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnsites.go +++ /dev/null @@ -1,590 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VpnSitesClient is the network Client -type VpnSitesClient struct { - BaseClient -} - -// NewVpnSitesClient creates an instance of the VpnSitesClient client. -func NewVpnSitesClient(subscriptionID string) VpnSitesClient { - return NewVpnSitesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVpnSitesClientWithBaseURI creates an instance of the VpnSitesClient client using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewVpnSitesClientWithBaseURI(baseURI string, subscriptionID string) VpnSitesClient { - return VpnSitesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates a VpnSite resource if it doesn't exist else updates the existing VpnSite. -// Parameters: -// resourceGroupName - the resource group name of the VpnSite. -// vpnSiteName - the name of the VpnSite being created or updated. -// vpnSiteParameters - parameters supplied to create or update VpnSite. -func (client VpnSitesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters VpnSite) (result VpnSitesCreateOrUpdateFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: vpnSiteParameters, - Constraints: []validation.Constraint{{Target: "vpnSiteParameters.VpnSiteProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "vpnSiteParameters.VpnSiteProperties.BgpProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "vpnSiteParameters.VpnSiteProperties.BgpProperties.Asn", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "vpnSiteParameters.VpnSiteProperties.BgpProperties.Asn", Name: validation.InclusiveMaximum, Rule: int64(4294967295), Chain: nil}, - {Target: "vpnSiteParameters.VpnSiteProperties.BgpProperties.Asn", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.VpnSitesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, vpnSiteName, vpnSiteParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - result, err = client.CreateOrUpdateSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "CreateOrUpdate", result.Response(), "Failure sending request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VpnSitesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters VpnSite) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnSiteName": autorest.Encode("path", vpnSiteName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - vpnSiteParameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}", pathParameters), - autorest.WithJSON(vpnSiteParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesClient) CreateOrUpdateSender(req *http.Request) (future VpnSitesCreateOrUpdateFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client VpnSitesClient) CreateOrUpdateResponder(resp *http.Response) (result VpnSite, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a VpnSite. -// Parameters: -// resourceGroupName - the resource group name of the VpnSite. -// vpnSiteName - the name of the VpnSite being deleted. -func (client VpnSitesClient) Delete(ctx context.Context, resourceGroupName string, vpnSiteName string) (result VpnSitesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, vpnSiteName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client VpnSitesClient) DeletePreparer(ctx context.Context, resourceGroupName string, vpnSiteName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnSiteName": autorest.Encode("path", vpnSiteName), - } - - const APIVersion = "2022-07-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/vpnSites/{vpnSiteName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesClient) DeleteSender(req *http.Request) (future VpnSitesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client VpnSitesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieves the details of a VPN site. -// Parameters: -// resourceGroupName - the resource group name of the VpnSite. -// vpnSiteName - the name of the VpnSite being retrieved. -func (client VpnSitesClient) Get(ctx context.Context, resourceGroupName string, vpnSiteName string) (result VpnSite, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, vpnSiteName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "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.VpnSitesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client VpnSitesClient) GetPreparer(ctx context.Context, resourceGroupName string, vpnSiteName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnSiteName": autorest.Encode("path", vpnSiteName), - } - - const APIVersion = "2022-07-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/vpnSites/{vpnSiteName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client VpnSitesClient) GetResponder(resp *http.Response) (result VpnSite, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all the VpnSites in a subscription. -func (client VpnSitesClient) List(ctx context.Context) (result ListVpnSitesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.List") - defer func() { - sc := -1 - if result.lvsr.Response.Response != nil { - sc = result.lvsr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.lvsr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "List", resp, "Failure sending request") - return - } - - result.lvsr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "List", resp, "Failure responding to request") - return - } - if result.lvsr.hasNextLink() && result.lvsr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client VpnSitesClient) ListPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnSites", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client VpnSitesClient) ListResponder(resp *http.Response) (result ListVpnSitesResult, err error) { - err = autorest.Respond( - resp, - 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 VpnSitesClient) listNextResults(ctx context.Context, lastResults ListVpnSitesResult) (result ListVpnSitesResult, err error) { - req, err := lastResults.listVpnSitesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnSitesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnSitesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnSitesClient) ListComplete(ctx context.Context) (result ListVpnSitesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx) - return -} - -// ListByResourceGroup lists all the vpnSites in a resource group. -// Parameters: -// resourceGroupName - the resource group name of the VpnSite. -func (client VpnSitesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListVpnSitesResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.lvsr.Response.Response != nil { - sc = result.lvsr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.lvsr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.lvsr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "ListByResourceGroup", resp, "Failure responding to request") - return - } - if result.lvsr.hasNextLink() && result.lvsr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client VpnSitesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/vpnSites", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client VpnSitesClient) ListByResourceGroupResponder(resp *http.Response) (result ListVpnSitesResult, err error) { - err = autorest.Respond( - resp, - 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 VpnSitesClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListVpnSitesResult) (result ListVpnSitesResult, err error) { - req, err := lastResults.listVpnSitesResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VpnSitesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VpnSitesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client VpnSitesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListVpnSitesResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.ListByResourceGroup") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) - return -} - -// UpdateTags updates VpnSite tags. -// Parameters: -// resourceGroupName - the resource group name of the VpnSite. -// vpnSiteName - the name of the VpnSite being updated. -// vpnSiteParameters - parameters supplied to update VpnSite tags. -func (client VpnSitesClient) UpdateTags(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters TagsObject) (result VpnSite, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, vpnSiteName, vpnSiteParameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client VpnSitesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters TagsObject) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vpnSiteName": autorest.Encode("path", vpnSiteName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}", pathParameters), - autorest.WithJSON(vpnSiteParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client VpnSitesClient) UpdateTagsResponder(resp *http.Response) (result VpnSite, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnsitesconfiguration.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnsitesconfiguration.go deleted file mode 100644 index 91f1679b9c..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/vpnsitesconfiguration.go +++ /dev/null @@ -1,120 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// VpnSitesConfigurationClient is the network Client -type VpnSitesConfigurationClient struct { - BaseClient -} - -// NewVpnSitesConfigurationClient creates an instance of the VpnSitesConfigurationClient client. -func NewVpnSitesConfigurationClient(subscriptionID string) VpnSitesConfigurationClient { - return NewVpnSitesConfigurationClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewVpnSitesConfigurationClientWithBaseURI creates an instance of the VpnSitesConfigurationClient client using a -// custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, -// Azure stack). -func NewVpnSitesConfigurationClientWithBaseURI(baseURI string, subscriptionID string) VpnSitesConfigurationClient { - return VpnSitesConfigurationClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Download gives the sas-url to download the configurations for vpn-sites in a resource group. -// Parameters: -// resourceGroupName - the resource group name. -// virtualWANName - the name of the VirtualWAN for which configuration of all vpn-sites is needed. -// request - parameters supplied to download vpn-sites configuration. -func (client VpnSitesConfigurationClient) Download(ctx context.Context, resourceGroupName string, virtualWANName string, request GetVpnSitesConfigurationRequest) (result VpnSitesConfigurationDownloadFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesConfigurationClient.Download") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: request, - Constraints: []validation.Constraint{{Target: "request.OutputBlobSasURL", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.VpnSitesConfigurationClient", "Download", err.Error()) - } - - req, err := client.DownloadPreparer(ctx, resourceGroupName, virtualWANName, request) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesConfigurationClient", "Download", nil, "Failure preparing request") - return - } - - result, err = client.DownloadSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VpnSitesConfigurationClient", "Download", result.Response(), "Failure sending request") - return - } - - return -} - -// DownloadPreparer prepares the Download request. -func (client VpnSitesConfigurationClient) DownloadPreparer(ctx context.Context, resourceGroupName string, virtualWANName string, request GetVpnSitesConfigurationRequest) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "virtualWANName": autorest.Encode("path", virtualWANName), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/vpnConfiguration", pathParameters), - autorest.WithJSON(request), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DownloadSender sends the Download request. The method will close the -// http.Response Body if it receives an error. -func (client VpnSitesConfigurationClient) DownloadSender(req *http.Request) (future VpnSitesConfigurationDownloadFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DownloadResponder handles the response to the Download request. The method always -// closes the http.Response Body. -func (client VpnSitesConfigurationClient) DownloadResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result.Response = resp - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/watchers.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/watchers.go deleted file mode 100644 index b995d820c5..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/watchers.go +++ /dev/null @@ -1,1568 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// WatchersClient is the network Client -type WatchersClient struct { - BaseClient -} - -// 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 using a custom endpoint. Use this -// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewWatchersClientWithBaseURI(baseURI string, subscriptionID string) WatchersClient { - return WatchersClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CheckConnectivity verifies the possibility of establishing a direct TCP connection from a virtual machine to a given -// endpoint including another VM or an arbitrary remote server. -// Parameters: -// resourceGroupName - the name of the network watcher resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that determine how the connectivity check will be performed. -func (client WatchersClient) CheckConnectivity(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConnectivityParameters) (result WatchersCheckConnectivityFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.CheckConnectivity") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Source", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.Source.ResourceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.Source.Port", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.Source.Port", Name: validation.InclusiveMaximum, Rule: int64(65535), Chain: nil}, - {Target: "parameters.Source.Port", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}, - {Target: "parameters.Destination", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.Destination.Port", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.Destination.Port", Name: validation.InclusiveMaximum, Rule: int64(65535), Chain: nil}, - {Target: "parameters.Destination.Port", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, - }}, - }}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "CheckConnectivity", err.Error()) - } - - req, err := client.CheckConnectivityPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "CheckConnectivity", nil, "Failure preparing request") - return - } - - result, err = client.CheckConnectivitySender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "CheckConnectivity", result.Response(), "Failure sending request") - return - } - - return -} - -// CheckConnectivityPreparer prepares the CheckConnectivity request. -func (client WatchersClient) CheckConnectivityPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConnectivityParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectivityCheck", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CheckConnectivitySender sends the CheckConnectivity request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) CheckConnectivitySender(req *http.Request) (future WatchersCheckConnectivityFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// CheckConnectivityResponder handles the response to the CheckConnectivity request. The method always -// closes the http.Response Body. -func (client WatchersClient) CheckConnectivityResponder(resp *http.Response) (result ConnectivityInformation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateOrUpdate creates or updates a network watcher in the specified resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters that define the network watcher resource. -func (client WatchersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters Watcher) (result Watcher, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.CreateOrUpdatePreparer(ctx, 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 - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client WatchersClient) CreateOrUpdatePreparer(ctx context.Context, 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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - 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{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -func (client WatchersClient) Delete(ctx context.Context, resourceGroupName string, networkWatcherName string) (result WatchersDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeletePreparer(ctx, resourceGroupName, networkWatcherName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client WatchersClient) DeletePreparer(ctx context.Context, 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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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) (future WatchersDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets the specified network watcher by resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -func (client WatchersClient) Get(ctx context.Context, resourceGroupName string, networkWatcherName string) (result Watcher, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, 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 - } - - return -} - -// GetPreparer prepares the Get request. -func (client WatchersClient) GetPreparer(ctx context.Context, 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 = "2022-07-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{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetAzureReachabilityReport nOTE: This feature is currently in preview and still being tested for stability. Gets the -// relative latency score for internet service providers from a specified location to Azure regions. -// Parameters: -// resourceGroupName - the name of the network watcher resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that determine Azure reachability report configuration. -func (client WatchersClient) GetAzureReachabilityReport(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AzureReachabilityReportParameters) (result WatchersGetAzureReachabilityReportFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetAzureReachabilityReport") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.ProviderLocation", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.ProviderLocation.Country", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "parameters.StartTime", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.EndTime", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "GetAzureReachabilityReport", err.Error()) - } - - req, err := client.GetAzureReachabilityReportPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetAzureReachabilityReport", nil, "Failure preparing request") - return - } - - result, err = client.GetAzureReachabilityReportSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetAzureReachabilityReport", result.Response(), "Failure sending request") - return - } - - return -} - -// GetAzureReachabilityReportPreparer prepares the GetAzureReachabilityReport request. -func (client WatchersClient) GetAzureReachabilityReportPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AzureReachabilityReportParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/azureReachabilityReport", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetAzureReachabilityReportSender sends the GetAzureReachabilityReport request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) GetAzureReachabilityReportSender(req *http.Request) (future WatchersGetAzureReachabilityReportFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetAzureReachabilityReportResponder handles the response to the GetAzureReachabilityReport request. The method always -// closes the http.Response Body. -func (client WatchersClient) GetAzureReachabilityReportResponder(resp *http.Response) (result AzureReachabilityReport, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetFlowLogStatus queries status of flow log and traffic analytics (optional) on a specified resource. -// Parameters: -// resourceGroupName - the name of the network watcher resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that define a resource to query flow log and traffic analytics (optional) status. -func (client WatchersClient) GetFlowLogStatus(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogStatusParameters) (result WatchersGetFlowLogStatusFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetFlowLogStatus") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "GetFlowLogStatus", err.Error()) - } - - req, err := client.GetFlowLogStatusPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetFlowLogStatus", nil, "Failure preparing request") - return - } - - result, err = client.GetFlowLogStatusSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetFlowLogStatus", result.Response(), "Failure sending request") - return - } - - return -} - -// GetFlowLogStatusPreparer prepares the GetFlowLogStatus request. -func (client WatchersClient) GetFlowLogStatusPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogStatusParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/queryFlowLogStatus", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// 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) (future WatchersGetFlowLogStatusFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetNetworkConfigurationDiagnostic gets Network Configuration Diagnostic data to help customers understand and debug -// network behavior. It provides detailed information on what security rules were applied to a specified traffic flow -// and the result of evaluating these rules. Customers must provide details of a flow like source, destination, -// protocol, etc. The API returns whether traffic was allowed or denied, the rules evaluated for the specified flow and -// the evaluation results. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters to get network configuration diagnostic. -func (client WatchersClient) GetNetworkConfigurationDiagnostic(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConfigurationDiagnosticParameters) (result WatchersGetNetworkConfigurationDiagnosticFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetNetworkConfigurationDiagnostic") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.Profiles", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "GetNetworkConfigurationDiagnostic", err.Error()) - } - - req, err := client.GetNetworkConfigurationDiagnosticPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNetworkConfigurationDiagnostic", nil, "Failure preparing request") - return - } - - result, err = client.GetNetworkConfigurationDiagnosticSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNetworkConfigurationDiagnostic", result.Response(), "Failure sending request") - return - } - - return -} - -// GetNetworkConfigurationDiagnosticPreparer prepares the GetNetworkConfigurationDiagnostic request. -func (client WatchersClient) GetNetworkConfigurationDiagnosticPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters ConfigurationDiagnosticParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/networkConfigurationDiagnostic", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetNetworkConfigurationDiagnosticSender sends the GetNetworkConfigurationDiagnostic request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) GetNetworkConfigurationDiagnosticSender(req *http.Request) (future WatchersGetNetworkConfigurationDiagnosticFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// GetNetworkConfigurationDiagnosticResponder handles the response to the GetNetworkConfigurationDiagnostic request. The method always -// closes the http.Response Body. -func (client WatchersClient) GetNetworkConfigurationDiagnosticResponder(resp *http.Response) (result ConfigurationDiagnosticResponse, err error) { - err = autorest.Respond( - resp, - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters that define the source and destination endpoint. -func (client WatchersClient) GetNextHop(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters NextHopParameters) (result WatchersGetNextHopFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetNextHop") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 { - return result, validation.NewError("network.WatchersClient", "GetNextHop", err.Error()) - } - - req, err := client.GetNextHopPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNextHop", nil, "Failure preparing request") - return - } - - result, err = client.GetNextHopSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNextHop", result.Response(), "Failure sending request") - return - } - - return -} - -// GetNextHopPreparer prepares the GetNextHop request. -func (client WatchersClient) GetNextHopPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters NextHopParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/nextHop", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// 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) (future WatchersGetNextHopFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters that define the representation of topology. -func (client WatchersClient) GetTopology(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TopologyParameters) (result Topology, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetTopology") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetTopologyPreparer(ctx, 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 - } - - return -} - -// GetTopologyPreparer prepares the GetTopology request. -func (client WatchersClient) GetTopologyPreparer(ctx context.Context, 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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/topology", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetTroubleshooting initiate troubleshooting on a specified resource. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that define the resource to troubleshoot. -func (client WatchersClient) GetTroubleshooting(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TroubleshootingParameters) (result WatchersGetTroubleshootingFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetTroubleshooting") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 { - return result, validation.NewError("network.WatchersClient", "GetTroubleshooting", err.Error()) - } - - req, err := client.GetTroubleshootingPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshooting", nil, "Failure preparing request") - return - } - - result, err = client.GetTroubleshootingSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshooting", result.Response(), "Failure sending request") - return - } - - return -} - -// GetTroubleshootingPreparer prepares the GetTroubleshooting request. -func (client WatchersClient) GetTroubleshootingPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TroubleshootingParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/troubleshoot", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// 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) (future WatchersGetTroubleshootingFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that define the resource to query the troubleshooting result. -func (client WatchersClient) GetTroubleshootingResult(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters QueryTroubleshootingParameters) (result WatchersGetTroubleshootingResultFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetTroubleshootingResult") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "GetTroubleshootingResult", err.Error()) - } - - req, err := client.GetTroubleshootingResultPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshootingResult", nil, "Failure preparing request") - return - } - - result, err = client.GetTroubleshootingResultSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshootingResult", result.Response(), "Failure sending request") - return - } - - return -} - -// GetTroubleshootingResultPreparer prepares the GetTroubleshootingResult request. -func (client WatchersClient) GetTroubleshootingResultPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters QueryTroubleshootingParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/queryTroubleshootResult", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// 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) (future WatchersGetTroubleshootingResultFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters that define the VM to check security groups for. -func (client WatchersClient) GetVMSecurityRules(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters SecurityGroupViewParameters) (result WatchersGetVMSecurityRulesFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.GetVMSecurityRules") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WatchersClient", "GetVMSecurityRules", err.Error()) - } - - req, err := client.GetVMSecurityRulesPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetVMSecurityRules", nil, "Failure preparing request") - return - } - - result, err = client.GetVMSecurityRulesSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetVMSecurityRules", result.Response(), "Failure sending request") - return - } - - return -} - -// GetVMSecurityRulesPreparer prepares the GetVMSecurityRules request. -func (client WatchersClient) GetVMSecurityRulesPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters SecurityGroupViewParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/securityGroupView", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// 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) (future WatchersGetVMSecurityRulesFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client WatchersClient) List(ctx context.Context, resourceGroupName string) (result WatcherListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.List") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListPreparer(ctx, 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 - } - - return -} - -// ListPreparer prepares the List request. -func (client WatchersClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - 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(ctx context.Context) (result WatcherListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.ListAll") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAllPreparer(ctx) - 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 - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client WatchersClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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{}).WithContext(ctx)) -} - -// 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 client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListAvailableProviders nOTE: This feature is currently in preview and still being tested for stability. Lists all -// available internet service providers for a specified Azure region. -// Parameters: -// resourceGroupName - the name of the network watcher resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that scope the list of available providers. -func (client WatchersClient) ListAvailableProviders(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AvailableProvidersListParameters) (result WatchersListAvailableProvidersFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.ListAvailableProviders") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListAvailableProvidersPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAvailableProviders", nil, "Failure preparing request") - return - } - - result, err = client.ListAvailableProvidersSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAvailableProviders", result.Response(), "Failure sending request") - return - } - - return -} - -// ListAvailableProvidersPreparer prepares the ListAvailableProviders request. -func (client WatchersClient) ListAvailableProvidersPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters AvailableProvidersListParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/availableProvidersList", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAvailableProvidersSender sends the ListAvailableProviders request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) ListAvailableProvidersSender(req *http.Request) (future WatchersListAvailableProvidersFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// ListAvailableProvidersResponder handles the response to the ListAvailableProviders request. The method always -// closes the http.Response Body. -func (client WatchersClient) ListAvailableProvidersResponder(resp *http.Response) (result AvailableProvidersList, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SetFlowLogConfiguration configures flow log and traffic analytics (optional) on a specified resource. -// Parameters: -// resourceGroupName - the name of the network watcher resource group. -// networkWatcherName - the name of the network watcher resource. -// parameters - parameters that define the configuration of flow log. -func (client WatchersClient) SetFlowLogConfiguration(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogInformation) (result WatchersSetFlowLogConfigurationFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.SetFlowLogConfiguration") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 { - return result, validation.NewError("network.WatchersClient", "SetFlowLogConfiguration", err.Error()) - } - - req, err := client.SetFlowLogConfigurationPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "SetFlowLogConfiguration", nil, "Failure preparing request") - return - } - - result, err = client.SetFlowLogConfigurationSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "SetFlowLogConfiguration", result.Response(), "Failure sending request") - return - } - - return -} - -// SetFlowLogConfigurationPreparer prepares the SetFlowLogConfiguration request. -func (client WatchersClient) SetFlowLogConfigurationPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters FlowLogInformation) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/configureFlowLog", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// 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) (future WatchersSetFlowLogConfigurationFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateTags updates a network watcher tags. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters supplied to update network watcher tags. -func (client WatchersClient) UpdateTags(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TagsObject) (result Watcher, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.UpdateTags") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "UpdateTags", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateTagsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.WatchersClient", "UpdateTags", resp, "Failure sending request") - return - } - - result, err = client.UpdateTagsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "UpdateTags", resp, "Failure responding to request") - return - } - - return -} - -// UpdateTagsPreparer prepares the UpdateTags request. -func (client WatchersClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters TagsObject) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateTagsSender sends the UpdateTags request. The method will close the -// http.Response Body if it receives an error. -func (client WatchersClient) UpdateTagsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateTagsResponder handles the response to the UpdateTags request. The method always -// closes the http.Response Body. -func (client WatchersClient) UpdateTagsResponder(resp *http.Response) (result Watcher, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - 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. -// Parameters: -// resourceGroupName - the name of the resource group. -// networkWatcherName - the name of the network watcher. -// parameters - parameters that define the IP flow to be verified. -func (client WatchersClient) VerifyIPFlow(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters VerificationIPFlowParameters) (result WatchersVerifyIPFlowFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WatchersClient.VerifyIPFlow") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - 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 { - return result, validation.NewError("network.WatchersClient", "VerifyIPFlow", err.Error()) - } - - req, err := client.VerifyIPFlowPreparer(ctx, resourceGroupName, networkWatcherName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "VerifyIPFlow", nil, "Failure preparing request") - return - } - - result, err = client.VerifyIPFlowSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WatchersClient", "VerifyIPFlow", result.Response(), "Failure sending request") - return - } - - return -} - -// VerifyIPFlowPreparer prepares the VerifyIPFlow request. -func (client WatchersClient) VerifyIPFlowPreparer(ctx context.Context, resourceGroupName string, networkWatcherName string, parameters VerificationIPFlowParameters) (*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 = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/ipFlowVerify", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// 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) (future WatchersVerifyIPFlowFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// 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, - 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/services/network/mgmt/2022-07-01/network/webapplicationfirewallpolicies.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/webapplicationfirewallpolicies.go deleted file mode 100644 index db5c195a25..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/webapplicationfirewallpolicies.go +++ /dev/null @@ -1,531 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// WebApplicationFirewallPoliciesClient is the network Client -type WebApplicationFirewallPoliciesClient struct { - BaseClient -} - -// NewWebApplicationFirewallPoliciesClient creates an instance of the WebApplicationFirewallPoliciesClient client. -func NewWebApplicationFirewallPoliciesClient(subscriptionID string) WebApplicationFirewallPoliciesClient { - return NewWebApplicationFirewallPoliciesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewWebApplicationFirewallPoliciesClientWithBaseURI creates an instance of the WebApplicationFirewallPoliciesClient -// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI -// (sovereign clouds, Azure stack). -func NewWebApplicationFirewallPoliciesClientWithBaseURI(baseURI string, subscriptionID string) WebApplicationFirewallPoliciesClient { - return WebApplicationFirewallPoliciesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or update policy with specified rule set name within a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// policyName - the name of the policy. -// parameters - policy to be created. -func (client WebApplicationFirewallPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, policyName string, parameters WebApplicationFirewallPolicy) (result WebApplicationFirewallPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.CreateOrUpdate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: policyName, - Constraints: []validation.Constraint{{Target: "policyName", Name: validation.MaxLength, Rule: 128, Chain: nil}}}, - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.WebApplicationFirewallPolicyPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.WebApplicationFirewallPolicyPropertiesFormat.PolicySettings", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.WebApplicationFirewallPolicyPropertiesFormat.PolicySettings.MaxRequestBodySizeInKb", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.WebApplicationFirewallPolicyPropertiesFormat.PolicySettings.MaxRequestBodySizeInKb", Name: validation.InclusiveMinimum, Rule: int64(8), Chain: nil}}}, - {Target: "parameters.WebApplicationFirewallPolicyPropertiesFormat.PolicySettings.FileUploadLimitInMb", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.WebApplicationFirewallPolicyPropertiesFormat.PolicySettings.FileUploadLimitInMb", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}, - {Target: "parameters.WebApplicationFirewallPolicyPropertiesFormat.PolicySettings.CustomBlockResponseStatusCode", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.WebApplicationFirewallPolicyPropertiesFormat.PolicySettings.CustomBlockResponseStatusCode", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}, - {Target: "parameters.WebApplicationFirewallPolicyPropertiesFormat.PolicySettings.CustomBlockResponseBody", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.WebApplicationFirewallPolicyPropertiesFormat.PolicySettings.CustomBlockResponseBody", Name: validation.MaxLength, Rule: 32768, Chain: nil}, - {Target: "parameters.WebApplicationFirewallPolicyPropertiesFormat.PolicySettings.CustomBlockResponseBody", Name: validation.Pattern, Rule: `^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$`, Chain: nil}, - }}, - }}, - {Target: "parameters.WebApplicationFirewallPolicyPropertiesFormat.ManagedRules", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.WebApplicationFirewallPolicyPropertiesFormat.ManagedRules.ManagedRuleSets", Name: validation.Null, Rule: true, Chain: nil}}}, - }}}}}); err != nil { - return result, validation.NewError("network.WebApplicationFirewallPoliciesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, policyName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "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.WebApplicationFirewallPoliciesClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "CreateOrUpdate", resp, "Failure responding to request") - return - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client WebApplicationFirewallPoliciesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, policyName string, parameters WebApplicationFirewallPolicy) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyName": autorest.Encode("path", policyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - parameters.Etag = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client WebApplicationFirewallPoliciesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client WebApplicationFirewallPoliciesClient) CreateOrUpdateResponder(resp *http.Response) (result WebApplicationFirewallPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes Policy. -// Parameters: -// resourceGroupName - the name of the resource group. -// policyName - the name of the policy. -func (client WebApplicationFirewallPoliciesClient) Delete(ctx context.Context, resourceGroupName string, policyName string) (result WebApplicationFirewallPoliciesDeleteFuture, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.Delete") - defer func() { - sc := -1 - if result.FutureAPI != nil && result.FutureAPI.Response() != nil { - sc = result.FutureAPI.Response().StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: policyName, - Constraints: []validation.Constraint{{Target: "policyName", Name: validation.MaxLength, Rule: 128, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WebApplicationFirewallPoliciesClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, policyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client WebApplicationFirewallPoliciesClient) DeletePreparer(ctx context.Context, resourceGroupName string, policyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyName": autorest.Encode("path", policyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client WebApplicationFirewallPoliciesClient) DeleteSender(req *http.Request) (future WebApplicationFirewallPoliciesDeleteFuture, err error) { - var resp *http.Response - future.FutureAPI = &azure.Future{} - resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - var azf azure.Future - azf, err = azure.NewFutureFromResponse(resp) - future.FutureAPI = &azf - future.Result = future.result - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client WebApplicationFirewallPoliciesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get retrieve protection policy with specified name within a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -// policyName - the name of the policy. -func (client WebApplicationFirewallPoliciesClient) Get(ctx context.Context, resourceGroupName string, policyName string) (result WebApplicationFirewallPolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: policyName, - Constraints: []validation.Constraint{{Target: "policyName", Name: validation.MaxLength, Rule: 128, Chain: nil}}}}); err != nil { - return result, validation.NewError("network.WebApplicationFirewallPoliciesClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, policyName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "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.WebApplicationFirewallPoliciesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client WebApplicationFirewallPoliciesClient) GetPreparer(ctx context.Context, resourceGroupName string, policyName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "policyName": autorest.Encode("path", policyName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client WebApplicationFirewallPoliciesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client WebApplicationFirewallPoliciesClient) GetResponder(resp *http.Response) (result WebApplicationFirewallPolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists all of the protection policies within a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. -func (client WebApplicationFirewallPoliciesClient) List(ctx context.Context, resourceGroupName string) (result WebApplicationFirewallPolicyListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.List") - defer func() { - sc := -1 - if result.wafplr.Response.Response != nil { - sc = result.wafplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, resourceGroupName) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.wafplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "List", resp, "Failure sending request") - return - } - - result.wafplr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "List", resp, "Failure responding to request") - return - } - if result.wafplr.hasNextLink() && result.wafplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListPreparer prepares the List request. -func (client WebApplicationFirewallPoliciesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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/ApplicationGatewayWebApplicationFirewallPolicies", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client WebApplicationFirewallPoliciesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client WebApplicationFirewallPoliciesClient) ListResponder(resp *http.Response) (result WebApplicationFirewallPolicyListResult, err error) { - err = autorest.Respond( - resp, - 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 WebApplicationFirewallPoliciesClient) listNextResults(ctx context.Context, lastResults WebApplicationFirewallPolicyListResult) (result WebApplicationFirewallPolicyListResult, err error) { - req, err := lastResults.webApplicationFirewallPolicyListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client WebApplicationFirewallPoliciesClient) ListComplete(ctx context.Context, resourceGroupName string) (result WebApplicationFirewallPolicyListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.List") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.List(ctx, resourceGroupName) - return -} - -// ListAll gets all the WAF policies in a subscription. -func (client WebApplicationFirewallPoliciesClient) ListAll(ctx context.Context) (result WebApplicationFirewallPolicyListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.ListAll") - defer func() { - sc := -1 - if result.wafplr.Response.Response != nil { - sc = result.wafplr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listAllNextResults - req, err := client.ListAllPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "ListAll", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllSender(req) - if err != nil { - result.wafplr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "ListAll", resp, "Failure sending request") - return - } - - result.wafplr, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "ListAll", resp, "Failure responding to request") - return - } - if result.wafplr.hasNextLink() && result.wafplr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListAllPreparer prepares the ListAll request. -func (client WebApplicationFirewallPoliciesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllSender sends the ListAll request. The method will close the -// http.Response Body if it receives an error. -func (client WebApplicationFirewallPoliciesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllResponder handles the response to the ListAll request. The method always -// closes the http.Response Body. -func (client WebApplicationFirewallPoliciesClient) ListAllResponder(resp *http.Response) (result WebApplicationFirewallPolicyListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllNextResults retrieves the next set of results, if any. -func (client WebApplicationFirewallPoliciesClient) listAllNextResults(ctx context.Context, lastResults WebApplicationFirewallPolicyListResult) (result WebApplicationFirewallPolicyListResult, err error) { - req, err := lastResults.webApplicationFirewallPolicyListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "listAllNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "listAllNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebApplicationFirewallPoliciesClient", "listAllNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllComplete enumerates all values, automatically crossing page boundaries as required. -func (client WebApplicationFirewallPoliciesClient) ListAllComplete(ctx context.Context) (result WebApplicationFirewallPolicyListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPoliciesClient.ListAll") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListAll(ctx) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/webcategories.go b/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/webcategories.go deleted file mode 100644 index bc9fa35445..0000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network/webcategories.go +++ /dev/null @@ -1,222 +0,0 @@ -package network - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// WebCategoriesClient is the network Client -type WebCategoriesClient struct { - BaseClient -} - -// NewWebCategoriesClient creates an instance of the WebCategoriesClient client. -func NewWebCategoriesClient(subscriptionID string) WebCategoriesClient { - return NewWebCategoriesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewWebCategoriesClientWithBaseURI creates an instance of the WebCategoriesClient client using a custom endpoint. -// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewWebCategoriesClientWithBaseURI(baseURI string, subscriptionID string) WebCategoriesClient { - return WebCategoriesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get gets the specified Azure Web Category. -// Parameters: -// name - the name of the azureWebCategory. -// expand - expands resourceIds back referenced by the azureWebCategory resource. -func (client WebCategoriesClient) Get(ctx context.Context, name string, expand string) (result AzureWebCategory, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WebCategoriesClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, name, expand) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebCategoriesClient", "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.WebCategoriesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebCategoriesClient", "Get", resp, "Failure responding to request") - return - } - - return -} - -// GetPreparer prepares the Get request. -func (client WebCategoriesClient) GetPreparer(ctx context.Context, name string, expand string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "name": autorest.Encode("path", name), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-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}/providers/Microsoft.Network/azureWebCategories/{name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client WebCategoriesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client WebCategoriesClient) GetResponder(resp *http.Response) (result AzureWebCategory, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListBySubscription gets all the Azure Web Categories in a subscription. -func (client WebCategoriesClient) ListBySubscription(ctx context.Context) (result AzureWebCategoryListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WebCategoriesClient.ListBySubscription") - defer func() { - sc := -1 - if result.awclr.Response.Response != nil { - sc = result.awclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.fn = client.listBySubscriptionNextResults - req, err := client.ListBySubscriptionPreparer(ctx) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebCategoriesClient", "ListBySubscription", nil, "Failure preparing request") - return - } - - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.awclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "network.WebCategoriesClient", "ListBySubscription", resp, "Failure sending request") - return - } - - result.awclr, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebCategoriesClient", "ListBySubscription", resp, "Failure responding to request") - return - } - if result.awclr.hasNextLink() && result.awclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client WebCategoriesClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2022-07-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureWebCategories", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBySubscriptionSender sends the ListBySubscription request. The method will close the -// http.Response Body if it receives an error. -func (client WebCategoriesClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always -// closes the http.Response Body. -func (client WebCategoriesClient) ListBySubscriptionResponder(resp *http.Response) (result AzureWebCategoryListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listBySubscriptionNextResults retrieves the next set of results, if any. -func (client WebCategoriesClient) listBySubscriptionNextResults(ctx context.Context, lastResults AzureWebCategoryListResult) (result AzureWebCategoryListResult, err error) { - req, err := lastResults.azureWebCategoryListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.WebCategoriesClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListBySubscriptionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.WebCategoriesClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") - } - result, err = client.ListBySubscriptionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.WebCategoriesClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. -func (client WebCategoriesClient) ListBySubscriptionComplete(ctx context.Context) (result AzureWebCategoryListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/WebCategoriesClient.ListBySubscription") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.ListBySubscription(ctx) - return -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/mocks/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/mocks/LICENSE deleted file mode 100644 index b9d6a27ea9..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/mocks/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Microsoft Corporation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/Azure/go-autorest/autorest/mocks/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/mocks/go_mod_tidy_hack.go deleted file mode 100644 index 175a1c79f4..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/mocks/go_mod_tidy_hack.go +++ /dev/null @@ -1,25 +0,0 @@ -//go:build modhack -// +build modhack - -package mocks - -// Copyright 2017 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. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/mocks/helpers.go b/vendor/github.com/Azure/go-autorest/autorest/mocks/helpers.go deleted file mode 100644 index f8b2f8b1ab..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/mocks/helpers.go +++ /dev/null @@ -1,171 +0,0 @@ -package mocks - -// Copyright 2017 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. - -import ( - "fmt" - "io" - "net/http" - "time" -) - -const ( - // TestAuthorizationHeader is a faux HTTP Authorization header value - TestAuthorizationHeader = "BEARER SECRETTOKEN" - - // TestBadURL is a malformed URL - TestBadURL = " " - - // TestDelay is the Retry-After delay used in tests. - TestDelay = 0 * time.Second - - // TestHeader is the header used in tests. - TestHeader = "x-test-header" - - // TestURL is the URL used in tests. - TestURL = "https://microsoft.com/a/b/c/" - - // TestAzureAsyncURL is a URL used in Azure asynchronous tests - TestAzureAsyncURL = "https://microsoft.com/a/b/c/async" - - // TestLocationURL is a URL used in Azure asynchronous tests - TestLocationURL = "https://microsoft.com/a/b/c/location" -) - -const ( - headerLocation = "Location" - headerRetryAfter = "Retry-After" -) - -// NewRequest instantiates a new request. -func NewRequest() *http.Request { - return NewRequestWithContent("") -} - -// NewRequestWithContent instantiates a new request using the passed string for the body content. -func NewRequestWithContent(c string) *http.Request { - r, _ := http.NewRequest("GET", "https://microsoft.com/a/b/c/", NewBody(c)) - return r -} - -// NewRequestWithCloseBody instantiates a new request. -func NewRequestWithCloseBody() *http.Request { - return NewRequestWithCloseBodyContent("request body") -} - -// NewRequestWithCloseBodyContent instantiates a new request using the passed string for the body content. -func NewRequestWithCloseBodyContent(c string) *http.Request { - r, _ := http.NewRequest("GET", "https://microsoft.com/a/b/c/", NewBodyClose(c)) - return r -} - -// NewRequestForURL instantiates a new request using the passed URL. -func NewRequestForURL(u string) *http.Request { - return NewRequestWithParams("GET", u, NewBody("")) -} - -// NewRequestWithParams instantiates a new request using the provided parameters. -func NewRequestWithParams(method, u string, body io.Reader) *http.Request { - r, err := http.NewRequest(method, u, body) - if err != nil { - panic(fmt.Sprintf("mocks: ERROR (%v) parsing testing URL %s", err, u)) - } - return r -} - -// NewResponse instantiates a new response. -func NewResponse() *http.Response { - return NewResponseWithContent("") -} - -// NewResponseWithBytes instantiates a new response with the passed bytes as the body content. -func NewResponseWithBytes(input []byte) *http.Response { - return &http.Response{ - Status: "200 OK", - StatusCode: 200, - Proto: "HTTP/1.0", - ProtoMajor: 1, - ProtoMinor: 0, - Body: NewBodyWithBytes(input), - Request: NewRequest(), - } -} - -// NewResponseWithContent instantiates a new response with the passed string as the body content. -func NewResponseWithContent(c string) *http.Response { - return &http.Response{ - Status: "200 OK", - StatusCode: 200, - Proto: "HTTP/1.0", - ProtoMajor: 1, - ProtoMinor: 0, - Body: NewBody(c), - Request: NewRequest(), - } -} - -// NewResponseWithStatus instantiates a new response using the passed string and integer as the -// status and status code. -func NewResponseWithStatus(s string, c int) *http.Response { - resp := NewResponse() - resp.Status = s - resp.StatusCode = c - return resp -} - -// NewResponseWithBodyAndStatus instantiates a new response using the specified mock body, -// status and status code -func NewResponseWithBodyAndStatus(body *Body, c int, s string) *http.Response { - resp := NewResponse() - resp.Body = body - resp.ContentLength = body.Length() - resp.Status = s - resp.StatusCode = c - return resp -} - -// SetResponseHeader adds a header to the passed response. -func SetResponseHeader(resp *http.Response, h string, v string) { - if resp.Header == nil { - resp.Header = make(http.Header) - } - resp.Header.Set(h, v) -} - -// SetResponseHeaderValues adds a header containing all the passed string values. -func SetResponseHeaderValues(resp *http.Response, h string, values []string) { - if resp.Header == nil { - resp.Header = make(http.Header) - } - for _, v := range values { - resp.Header.Add(h, v) - } -} - -// SetAcceptedHeaders adds the headers usually associated with a 202 Accepted response. -func SetAcceptedHeaders(resp *http.Response) { - SetLocationHeader(resp, TestURL) - SetRetryHeader(resp, TestDelay) -} - -// SetLocationHeader adds the Location header. -func SetLocationHeader(resp *http.Response, location string) { - SetResponseHeader(resp, http.CanonicalHeaderKey(headerLocation), location) -} - -// SetRetryHeader adds the Retry-After header. -func SetRetryHeader(resp *http.Response, delay time.Duration) { - SetResponseHeader(resp, http.CanonicalHeaderKey(headerRetryAfter), fmt.Sprintf("%v", delay.Seconds())) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/mocks/mocks.go b/vendor/github.com/Azure/go-autorest/autorest/mocks/mocks.go deleted file mode 100644 index 0317825ee1..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/mocks/mocks.go +++ /dev/null @@ -1,238 +0,0 @@ -/* -Package mocks provides mocks and helpers used in testing. -*/ -package mocks - -// Copyright 2017 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. - -import ( - "fmt" - "io" - "net/http" - "time" -) - -// Body implements acceptable body over a string. -type Body struct { - src []byte - buf []byte - isOpen bool - closeAttempts int -} - -// NewBody creates a new instance of Body. -func NewBody(s string) *Body { - return (&Body{src: []byte(s)}).reset() -} - -// NewBodyWithBytes creates a new instance of Body. -func NewBodyWithBytes(b []byte) *Body { - return (&Body{src: b}).reset() -} - -// NewBodyClose creates a new instance of Body. -func NewBodyClose(s string) *Body { - return &Body{src: []byte(s)} -} - -// Read reads into the passed byte slice and returns the bytes read. -func (body *Body) Read(b []byte) (n int, err error) { - if !body.IsOpen() { - return 0, fmt.Errorf("ERROR: Body has been closed") - } - if len(body.buf) == 0 { - return 0, io.EOF - } - n = copy(b, body.buf) - body.buf = body.buf[n:] - return n, nil -} - -// Close closes the body. -func (body *Body) Close() error { - if body.isOpen { - body.isOpen = false - body.closeAttempts++ - } - return nil -} - -// CloseAttempts returns the number of times Close was called. -func (body *Body) CloseAttempts() int { - return body.closeAttempts -} - -// IsOpen returns true if the Body has not been closed, false otherwise. -func (body *Body) IsOpen() bool { - return body.isOpen -} - -func (body *Body) reset() *Body { - body.isOpen = true - body.buf = body.src - return body -} - -// Length returns the number of bytes in the body. -func (body *Body) Length() int64 { - if body == nil { - return 0 - } - return int64(len(body.src)) -} - -type response struct { - r *http.Response - e error - d time.Duration -} - -// Sender implements a simple null sender. -type Sender struct { - attempts int - responses []response - numResponses int - repeatResponse []int - err error - repeatError int - emitErrorAfter int -} - -// NewSender creates a new instance of Sender. -func NewSender() *Sender { - return &Sender{} -} - -// Do accepts the passed request and, based on settings, emits a response and possible error. -func (c *Sender) Do(r *http.Request) (resp *http.Response, err error) { - c.attempts++ - - if len(c.responses) > 0 { - resp = c.responses[0].r - if resp != nil { - if b, ok := resp.Body.(*Body); ok { - b.reset() - } - } else { - err = c.responses[0].e - } - select { - case <-time.After(c.responses[0].d): - // do nothing - case <-r.Context().Done(): - err = r.Context().Err() - return - } - c.repeatResponse[0]-- - if c.repeatResponse[0] == 0 { - c.responses = c.responses[1:] - c.repeatResponse = c.repeatResponse[1:] - } - } else { - resp = NewResponse() - } - if resp != nil { - resp.Request = r - } - - if c.emitErrorAfter > 0 { - c.emitErrorAfter-- - } else if c.err != nil { - err = c.err - c.repeatError-- - if c.repeatError == 0 { - c.err = nil - } - } - - return -} - -// AppendResponse adds the passed http.Response to the response stack. -func (c *Sender) AppendResponse(resp *http.Response) { - c.AppendAndRepeatResponse(resp, 1) -} - -// AppendResponseWithDelay adds the passed http.Response to the response stack with the specified delay. -func (c *Sender) AppendResponseWithDelay(resp *http.Response, delay time.Duration) { - c.AppendAndRepeatResponseWithDelay(resp, delay, 1) -} - -// AppendAndRepeatResponse adds the passed http.Response to the response stack along with a -// repeat count. A negative repeat count will return the response for all remaining calls to Do. -func (c *Sender) AppendAndRepeatResponse(resp *http.Response, repeat int) { - c.appendAndRepeat(response{r: resp}, repeat) -} - -// AppendAndRepeatResponseWithDelay adds the passed http.Response to the response stack with the specified -// delay along with a repeat count. A negative repeat count will return the response for all remaining calls to Do. -func (c *Sender) AppendAndRepeatResponseWithDelay(resp *http.Response, delay time.Duration, repeat int) { - c.appendAndRepeat(response{r: resp, d: delay}, repeat) -} - -// AppendError adds the passed error to the response stack. -func (c *Sender) AppendError(err error) { - c.AppendAndRepeatError(err, 1) -} - -// AppendAndRepeatError adds the passed error to the response stack along with a repeat -// count. A negative repeat count will return the response for all remaining calls to Do. -func (c *Sender) AppendAndRepeatError(err error, repeat int) { - c.appendAndRepeat(response{e: err}, repeat) -} - -func (c *Sender) appendAndRepeat(resp response, repeat int) { - if c.responses == nil { - c.responses = []response{resp} - c.repeatResponse = []int{repeat} - } else { - c.responses = append(c.responses, resp) - c.repeatResponse = append(c.repeatResponse, repeat) - } - c.numResponses++ -} - -// Attempts returns the number of times Do was called. -func (c *Sender) Attempts() int { - return c.attempts -} - -// SetError sets the error Do should return. -func (c *Sender) SetError(err error) { - c.SetAndRepeatError(err, 1) -} - -// SetAndRepeatError sets the error Do should return and how many calls to Do will return the error. -// A negative repeat value will return the error for all remaining calls to Do. -func (c *Sender) SetAndRepeatError(err error, repeat int) { - c.err = err - c.repeatError = repeat -} - -// SetEmitErrorAfter sets the number of attempts to be made before errors are emitted. -func (c *Sender) SetEmitErrorAfter(ea int) { - c.emitErrorAfter = ea -} - -// NumResponses returns the number of responses that have been added to the sender. -func (c *Sender) NumResponses() int { - return c.numResponses -} - -// T is a simple testing struct. -type T struct { - Name string `json:"name" xml:"Name"` - Age int `json:"age" xml:"Age"` -} diff --git a/vendor/github.com/samber/lo/CHANGELOG.md b/vendor/github.com/samber/lo/CHANGELOG.md index 25815f76aa..8b9e4e11f5 100644 --- a/vendor/github.com/samber/lo/CHANGELOG.md +++ b/vendor/github.com/samber/lo/CHANGELOG.md @@ -2,6 +2,11 @@ @samber: I sometimes forget to update this file. Ping me on [Twitter](https://twitter.com/samuelberthe) or open an issue in case of error. We need to keep a clear changelog for easier lib upgrade. +## 1.39.0 (2023-12-01) + +Improvement: +- Adding IsNil + ## 1.38.1 (2023-03-20) Improvement: @@ -15,7 +20,7 @@ Adding: - lo.EmptyableToPtr Improvement: -- Substring: add support for non-english chars +- Substring: add support for non-English chars Fix: - Async: Fix goroutine leak diff --git a/vendor/github.com/samber/lo/Dockerfile b/vendor/github.com/samber/lo/Dockerfile index bd01bbbb45..5eab431ac0 100644 --- a/vendor/github.com/samber/lo/Dockerfile +++ b/vendor/github.com/samber/lo/Dockerfile @@ -1,5 +1,5 @@ -FROM golang:1.18 +FROM golang:1.21.12 WORKDIR /go/src/github.com/samber/lo diff --git a/vendor/github.com/samber/lo/Makefile b/vendor/github.com/samber/lo/Makefile index 57bb49159f..f97ded85e7 100644 --- a/vendor/github.com/samber/lo/Makefile +++ b/vendor/github.com/samber/lo/Makefile @@ -1,8 +1,6 @@ -BIN=go - build: - ${BIN} build -v ./... + go build -v ./... test: go test -race -v ./... @@ -15,18 +13,18 @@ watch-bench: reflex -t 50ms -s -- sh -c 'go test -benchmem -count 3 -bench ./...' coverage: - ${BIN} test -v -coverprofile=cover.out -covermode=atomic . - ${BIN} tool cover -html=cover.out -o cover.html + go test -v -coverprofile=cover.out -covermode=atomic ./... + go tool cover -html=cover.out -o cover.html # tools tools: - ${BIN} install github.com/cespare/reflex@latest - ${BIN} install github.com/rakyll/gotest@latest - ${BIN} install github.com/psampaz/go-mod-outdated@latest - ${BIN} install github.com/jondot/goweight@latest - ${BIN} install github.com/golangci/golangci-lint/cmd/golangci-lint@latest - ${BIN} get -t -u golang.org/x/tools/cmd/cover - ${BIN} install github.com/sonatype-nexus-community/nancy@latest + go install github.com/cespare/reflex@latest + go install github.com/rakyll/gotest@latest + go install github.com/psampaz/go-mod-outdated@latest + go install github.com/jondot/goweight@latest + go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest + go get -t -u golang.org/x/tools/cmd/cover + go install github.com/sonatype-nexus-community/nancy@latest go mod tidy lint: @@ -35,10 +33,10 @@ lint-fix: golangci-lint run --timeout 60s --max-same-issues 50 --fix ./... audit: tools - ${BIN} list -json -m all | nancy sleuth + go list -json -m all | nancy sleuth outdated: tools - ${BIN} list -u -m -json all | go-mod-outdated -update -direct + go list -u -m -json all | go-mod-outdated -update -direct weight: tools goweight diff --git a/vendor/github.com/samber/lo/README.md b/vendor/github.com/samber/lo/README.md index 77ab2d007d..3f73cc8e6d 100644 --- a/vendor/github.com/samber/lo/README.md +++ b/vendor/github.com/samber/lo/README.md @@ -24,7 +24,7 @@ In the future, 5 to 10 helpers will overlap with those coming into the Go standa **Why this name?** -I wanted a **short name**, similar to "Lodash" and no Go package currently uses this name. +I wanted a **short name**, similar to "Lodash" and no Go package uses this name. ![lo](img/logo-full.png) @@ -54,7 +54,7 @@ import ( Then use one of the helpers below: ```go -names := lo.Uniq[string]([]string{"Samuel", "John", "Samuel"}) +names := lo.Uniq([]string{"Samuel", "John", "Samuel"}) // []string{"Samuel", "John"} ``` @@ -85,6 +85,7 @@ Supported helpers for slices: - [Reduce](#reduce) - [ReduceRight](#reduceright) - [ForEach](#foreach) +- [ForEachWhile](#foreachwhile) - [Times](#times) - [Uniq](#uniq) - [UniqBy](#uniqby) @@ -104,7 +105,10 @@ Supported helpers for slices: - [DropRight](#dropright) - [DropWhile](#dropwhile) - [DropRightWhile](#droprightwhile) +- [DropByIndex](#DropByIndex) - [Reject](#reject) +- [RejectMap](#rejectmap) +- [FilterReject](#filterreject) - [Count](#count) - [CountBy](#countby) - [CountValues](#countvalues) @@ -116,12 +120,16 @@ Supported helpers for slices: - [Compact](#compact) - [IsSorted](#issorted) - [IsSortedByKey](#issortedbykey) +- [Splice](#Splice) Supported helpers for maps: - [Keys](#keys) +- [UniqKeys](#uniqkeys) +- [HasKey](#haskey) - [ValueOr](#valueor) - [Values](#values) +- [UniqValues](#uniqvalues) - [PickBy](#pickby) - [PickByKeys](#pickbykeys) - [PickByValues](#pickbyvalues) @@ -143,6 +151,8 @@ Supported math helpers: - [Clamp](#clamp) - [Sum](#sum) - [SumBy](#sumby) +- [Mean](#mean) +- [MeanBy](#meanby) Supported helpers for strings: @@ -150,13 +160,27 @@ Supported helpers for strings: - [Substring](#substring) - [ChunkString](#chunkstring) - [RuneLength](#runelength) +- [PascalCase](#pascalcase) +- [CamelCase](#camelcase) +- [KebabCase](#kebabcase) +- [SnakeCase](#snakecase) +- [Words](#words) +- [Capitalize](#capitalize) +- [Elipse](#elipse) Supported helpers for tuples: - [T2 -> T9](#t2---t9) - [Unpack2 -> Unpack9](#unpack2---unpack9) - [Zip2 -> Zip9](#zip2---zip9) +- [ZipBy2 -> ZipBy9](#zipby2---zipby9) - [Unzip2 -> Unzip9](#unzip2---unzip9) +- [UnzipBy2 -> UnzipBy9](#unzipby2---unzipby9) + +Supported helpers for time and duration: + +- [Duration](#duration) +- [Duration0 -> Duration10](#duration0-duration10) Supported helpers for channels: @@ -200,9 +224,18 @@ Supported search helpers: - [FindDuplicatesBy](#findduplicatesby) - [Min](#min) - [MinBy](#minby) +- [Earliest](#earliest) +- [EarliestBy](#earliestby) - [Max](#max) - [MaxBy](#maxby) +- [Latest](#latest) +- [LatestBy](#latestby) +- [First](#first) +- [FirstOrEmpty](#FirstOrEmpty) +- [FirstOr](#FirstOr) - [Last](#last) +- [LastOrEmpty](#LastOrEmpty) +- [LastOr](#LastOr) - [Nth](#nth) - [Sample](#sample) - [Samples](#samples) @@ -216,17 +249,22 @@ Conditional helpers: Type manipulation helpers: +- [IsNil](#isnil) - [ToPtr](#toptr) +- [Nil](#nil) - [EmptyableToPtr](#emptyabletoptr) - [FromPtr](#fromptr) - [FromPtrOr](#fromptror) - [ToSlicePtr](#tosliceptr) +- [FromSlicePtr](#fromsliceptr) +- [FromSlicePtrOr](#fromsliceptror) - [ToAnySlice](#toanyslice) - [FromAnySlice](#fromanyslice) - [Empty](#empty) - [IsEmpty](#isempty) - [IsNotEmpty](#isnotempty) - [Coalesce](#coalesce) +- [CoalesceOrEmpty](#coalesceorempty) Function helpers: @@ -244,6 +282,8 @@ Concurrency helpers: - [Synchronize](#synchronize) - [Async](#async) - [Transaction](#transaction) +- [WaitFor](#waitfor) +- [WaitForWithContext](#waitforwithcontext) Error handling: @@ -324,11 +364,11 @@ matching := lo.FilterMap([]string{"cpu", "gpu", "mouse", "keyboard"}, func(x str Manipulates a slice and transforms and flattens it to a slice of another type. The transform function can either return a slice or a `nil`, and in the `nil` case no value is added to the final slice. ```go -lo.FlatMap([]int{0, 1, 2}, func(x int, _ int) []string { - return []string{ - strconv.FormatInt(x, 10), - strconv.FormatInt(x, 10), - } +lo.FlatMap([]int64{0, 1, 2}, func(x int64, _ int) []string { + return []string{ + strconv.FormatInt(x, 10), + strconv.FormatInt(x, 10), + } }) // []string{"0", "0", "1", "1", "2", "2"} ``` @@ -387,6 +427,26 @@ lop.ForEach([]string{"hello", "world"}, func(x string, _ int) { // prints "hello\nworld\n" or "world\nhello\n" ``` +### ForEachWhile + +Iterates over collection elements and invokes iteratee for each element collection return value decide to continue or break, like do while(). + +```go +list := []int64{1, 2, -42, 4} + +lo.ForEachWhile(list, func(x int64, _ int) bool { + if x < 0 { + return false + } + fmt.Println(x) + return true +}) +// 1 +// 2 +``` + +[[play](https://go.dev/play/p/QnLGt35tnow)] + ### Times Times invokes the iteratee n times, returning an array of the results of each invocation. The iteratee is invoked with index as argument. @@ -542,7 +602,7 @@ interleaved := lo.Interleave([]int{1}, []int{2, 5, 8}, []int{3, 6}, []int{4, 7, // []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} ``` -[[play](https://go.dev/play/p/DDhlwrShbwe)] +[[play](https://go.dev/play/p/-RJkTLQEDVt)] ### Shuffle @@ -716,6 +776,18 @@ l := lo.DropRightWhile([]string{"a", "aa", "aaa", "aa", "aa"}, func(val string) [[play](https://go.dev/play/p/3-n71oEC0Hz)] +### DropByIndex + +Drops elements from a slice or array by the index. A negative index will drop elements from the end of the slice. + +```go +l := lo.DropByIndex([]int{0, 1, 2, 3, 4, 5}, 2, 4, -1) +// []int{0, 1, 3} +``` + +[[play](https://go.dev/play/p/JswS7vXRJP2)] + + ### Reject The opposite of Filter, this method returns the elements of collection that predicate does not return truthy for. @@ -729,6 +801,33 @@ odd := lo.Reject([]int{1, 2, 3, 4}, func(x int, _ int) bool { [[play](https://go.dev/play/p/YkLMODy1WEL)] +### RejectMap + +The opposite of FilterMap, this method returns a slice which obtained after both filtering and mapping using the given callback function. + +The callback function should return two values: +- the result of the mapping operation and +- whether the result element should be included or not. + +```go +items := lo.RejectMap([]int{1, 2, 3, 4}, func(x int, _ int) (int, bool) { + return x*10, x%2 == 0 +}) +// []int{10, 30} +``` + +### FilterReject + +Mixes Filter and Reject, this method returns two slices, one for the elements of collection that predicate returns truthy for and one for the elements that predicate does not return truthy for. + +```go +kept, rejected := lo.FilterReject([]int{1, 2, 3, 4}, func(x int, _ int) bool { + return x%2 == 0 +}) +// []int{2, 4} +// []int{1, 3} +``` + ### Count Counts the number of elements in the collection that compare equal to value. @@ -893,7 +992,7 @@ Returns a slice of all non-zero elements. ```go in := []string{"", "foo", "", "bar", ""} -slice := lo.Compact[string](in) +slice := lo.Compact(in) // []string{"foo", "bar"} ``` @@ -923,37 +1022,117 @@ slice := lo.IsSortedByKey([]string{"a", "bb", "ccc"}, func(s string) int { [[play](https://go.dev/play/p/wiG6XyBBu49)] +### Splice + +Splice inserts multiple elements at index i. A negative index counts back from the end of the slice. The helper is protected against overflow errors. + +```go +result := lo.Splice([]string{"a", "b"}, 1, "1", "2") +// []string{"a", "1", "2", "b"} + +// negative +result = lo.Splice([]string{"a", "b"}, -1, "1", "2") +// []string{"a", "1", "2", "b"} + +// overflow +result = lo.Splice([]string{"a", "b"}, 42, "1", "2") +// []string{"a", "b", "1", "2"} +``` + +[[play](https://go.dev/play/p/G5_GhkeSUBA)] + ### Keys -Creates an array of the map keys. +Creates a slice of the map keys. + +Use the UniqKeys variant to deduplicate common keys. ```go -keys := lo.Keys[string, int](map[string]int{"foo": 1, "bar": 2}) +keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}) // []string{"foo", "bar"} + +keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3}) +// []string{"foo", "bar", "baz"} + +keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 3}) +// []string{"foo", "bar", "bar"} ``` [[play](https://go.dev/play/p/Uu11fHASqrU)] +### UniqKeys + +Creates an array of unique map keys. + +```go +keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3}) +// []string{"foo", "bar", "baz"} + +keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 3}) +// []string{"foo", "bar"} +``` + +[[play](https://go.dev/play/p/TPKAb6ILdHk)] + +### HasKey + +Returns whether the given key exists. + +```go +exists := lo.HasKey(map[string]int{"foo": 1, "bar": 2}, "foo") +// true + +exists := lo.HasKey(map[string]int{"foo": 1, "bar": 2}, "baz") +// false +``` + +[[play](https://go.dev/play/p/aVwubIvECqS)] + ### Values Creates an array of the map values. +Use the UniqValues variant to deduplicate common values. + ```go -values := lo.Values[string, int](map[string]int{"foo": 1, "bar": 2}) +values := lo.Values(map[string]int{"foo": 1, "bar": 2}) // []int{1, 2} + +values := lo.Values(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3}) +// []int{1, 2, 3} + +values := lo.Values(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 2}) +// []int{1, 2, 2} ``` [[play](https://go.dev/play/p/nnRTQkzQfF6)] +### UniqValues + +Creates an array of unique map values. + +```go +values := lo.UniqValues(map[string]int{"foo": 1, "bar": 2}) +// []int{1, 2} + +values := lo.UniqValues(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3}) +// []int{1, 2, 3} + +values := lo.UniqValues(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 2}) +// []int{1, 2} +``` + +[[play](https://go.dev/play/p/nf6bXMh7rM3)] + ### ValueOr -Creates an array of the map values. +Returns the value of the given key or the fallback value if the key is not present. ```go -value := lo.ValueOr[string, int](map[string]int{"foo": 1, "bar": 2}, "foo", 42) +value := lo.ValueOr(map[string]int{"foo": 1, "bar": 2}, "foo", 42) // 1 -value := lo.ValueOr[string, int](map[string]int{"foo": 1, "bar": 2}, "baz", 42) +value := lo.ValueOr(map[string]int{"foo": 1, "bar": 2}, "baz", 42) // 42 ``` @@ -1088,7 +1267,7 @@ m2 := lo.Invert(map[string]int{"a": 1, "b": 2, "c": 1}) Merges multiple maps from left to right. ```go -mergedMaps := lo.Assign[string, int]( +mergedMaps := lo.Assign( map[string]int{"a": 1, "b": 2}, map[string]int{"b": 3, "c": 4}, ) @@ -1234,6 +1413,42 @@ sum := lo.SumBy(strings, func(item string) int { [[play](https://go.dev/play/p/Dz_a_7jN_ca)] +### Mean + +Calculates the mean of a collection of numbers. + +If collection is empty 0 is returned. + +```go +mean := lo.Mean([]int{2, 3, 4, 5}) +// 3 + +mean := lo.Mean([]float64{2, 3, 4, 5}) +// 3.5 + +mean := lo.Mean([]float64{}) +// 0 +``` + +### MeanBy + +Calculates the mean of a collection of numbers using the given return value from the iteration function. + +If collection is empty 0 is returned. + +```go +list := []string{"aa", "bbb", "cccc", "ddddd"} +mapper := func(item string) float64 { + return float64(len(item)) +} + +mean := lo.MeanBy(list, mapper) +// 3.5 + +mean := lo.MeanBy([]float64{}, mapper) +// 0 +``` + ### RandomString Returns a random string of the specified length and made of the specified charset. @@ -1296,6 +1511,85 @@ sub := len("hellô") [[play](https://go.dev/play/p/tuhgW_lWY8l)] +### PascalCase + +Converts string to pascal case. + +```go +str := lo.PascalCase("hello_world") +// HelloWorld +``` + +[[play](https://go.dev/play/p/iZkdeLP9oiB)] + +### CamelCase + +Converts string to camel case. + +```go +str := lo.CamelCase("hello_world") +// helloWorld +``` + +[[play](https://go.dev/play/p/dtyFB58MBRp)] + +### KebabCase + +Converts string to kebab case. + +```go +str := lo.KebabCase("helloWorld") +// hello-world +``` + +[[play](https://go.dev/play/p/2YTuPafwECA)] + +### SnakeCase + +Converts string to snake case. + +```go +str := lo.SnakeCase("HelloWorld") +// hello_world +``` + +[[play](https://go.dev/play/p/QVKJG9nOnDg)] + +### Words + +Splits string into an array of its words. + +```go +str := lo.Words("helloWorld") +// []string{"hello", "world"} +``` + +[[play](https://go.dev/play/p/2P4zhqqq61g)] + +### Capitalize + +Converts the first character of string to upper case and the remaining to lower case. + +```go +str := lo.Capitalize("heLLO") +// Hello +``` + +### Elipse + +Truncates a string to a specified length and appends an ellipsis if truncated. + +```go +str := lo.Elipse("Lorem Ipsum", 5) +// Lo... + +str := lo.Elipse("Lorem Ipsum", 100) +// Lorem Ipsum + +str := lo.Elipse("Lorem Ipsum", 3) +// ... +``` + ### T2 -> T9 Creates a tuple from a list of values. @@ -1325,7 +1619,7 @@ Unpack is also available as a method of TupleX. ```go tuple2 := lo.T2("a", 1) a, b := tuple2.Unpack() -// "a" 1 +// "a", 1 ``` [[play](https://go.dev/play/p/xVP_k0kJ96W)] @@ -1343,6 +1637,19 @@ tuples := lo.Zip2([]string{"a", "b"}, []int{1, 2}) [[play](https://go.dev/play/p/jujaA6GaJTp)] +### ZipBy2 -> ZipBy9 + +ZipBy creates a slice of transformed elements, the first of which contains the first elements of the given arrays, the second of which contains the second elements of the given arrays, and so on. + +When collections have different size, the Tuple attributes are filled with zero value. + +```go +items := lo.ZipBy2([]string{"a", "b"}, []int{1, 2}, func(a string, b int) string { + return fmt.Sprintf("%s-%d", a, b) +}) +// []string{"a-1", "b-2"} +``` + ### Unzip2 -> Unzip9 Unzip accepts an array of grouped elements and creates an array regrouping the elements to their pre-zip configuration. @@ -1355,6 +1662,56 @@ a, b := lo.Unzip2([]Tuple2[string, int]{{A: "a", B: 1}, {A: "b", B: 2}}) [[play](https://go.dev/play/p/ciHugugvaAW)] +### UnzipBy2 -> UnzipBy9 + +UnzipBy2 iterates over a collection and creates an array regrouping the elements to their pre-zip configuration. + +```go +a, b := lo.UnzipBy2([]string{"hello", "john", "doe"}, func(str string) (string, int) { + return str, len(str) +}) +// []string{"hello", "john", "doe"} +// []int{5, 4, 3} +``` + +### Duration + +Returns the time taken to execute a function. + +```go +duration := lo.Duration(func() { + // very long job +}) +// 3s +``` + +### Duration0 -> Duration10 + +Returns the time taken to execute a function. + +```go +duration := lo.Duration0(func() { + // very long job +}) +// 3s + +err, duration := lo.Duration1(func() error { + // very long job + return fmt.Errorf("an error") +}) +// an error +// 3s + +str, nbr, err, duration := lo.Duration3(func() (string, int, error) { + // very long job + return "hello", 42, nil +}) +// hello +// 42 +// nil +// 3s +``` + ### ChannelDispatcher Distributes messages from input channels into N child channels. Close events are propagated to children. @@ -1823,7 +2180,7 @@ str, index, ok := lo.FindLastIndexOf([]string{"foobar"}, func(i string) bool { ### FindOrElse -Search an element in a slice based on a predicate. It returns element and true if element was found. +Search an element in a slice based on a predicate. It returns the element if found or a given fallback value otherwise. ```go str := lo.FindOrElse([]string{"a", "b", "c", "d"}, "x", func(i string) bool { @@ -1915,7 +2272,7 @@ duplicatedValues := lo.FindDuplicatesBy([]int{3, 4, 5, 6, 7}, func(i int) int { Search the minimum value of a collection. -Returns zero value when collection is empty. +Returns zero value when the collection is empty. ```go min := lo.Min([]int{1, 2, 3}) @@ -1923,6 +2280,9 @@ min := lo.Min([]int{1, 2, 3}) min := lo.Min([]int{}) // 0 + +min := lo.Min([]time.Duration{time.Second, time.Hour}) +// 1s ``` ### MinBy @@ -1931,7 +2291,7 @@ Search the minimum value of a collection using the given comparison function. If several values of the collection are equal to the smallest value, returns the first such value. -Returns zero value when collection is empty. +Returns zero value when the collection is empty. ```go min := lo.MinBy([]string{"s1", "string2", "s3"}, func(item string, min string) bool { @@ -1945,11 +2305,39 @@ min := lo.MinBy([]string{}, func(item string, min string) bool { // "" ``` +### Earliest + +Search the minimum time.Time of a collection. + +Returns zero value when the collection is empty. + +```go +earliest := lo.Earliest(time.Now(), time.Time{}) +// 0001-01-01 00:00:00 +0000 UTC +``` + +### EarliestBy + +Search the minimum time.Time of a collection using the given iteratee function. + +Returns zero value when the collection is empty. + +```go +type foo struct { + bar time.Time +} + +earliest := lo.EarliestBy([]foo{{time.Now()}, {}}, func(i foo) time.Time { + return i.bar +}) +// {bar:{2023-04-01 01:02:03 +0000 UTC}} +``` + ### Max Search the maximum value of a collection. -Returns zero value when collection is empty. +Returns zero value when the collection is empty. ```go max := lo.Max([]int{1, 2, 3}) @@ -1957,6 +2345,9 @@ max := lo.Max([]int{1, 2, 3}) max := lo.Max([]int{}) // 0 + +max := lo.Max([]time.Duration{time.Second, time.Hour}) +// 1h ``` ### MaxBy @@ -1965,7 +2356,7 @@ Search the maximum value of a collection using the given comparison function. If several values of the collection are equal to the greatest value, returns the first such value. -Returns zero value when collection is empty. +Returns zero value when the collection is empty. ```go max := lo.MaxBy([]string{"string1", "s2", "string3"}, func(item string, max string) bool { @@ -1979,13 +2370,104 @@ max := lo.MaxBy([]string{}, func(item string, max string) bool { // "" ``` +### Latest + +Search the maximum time.Time of a collection. + +Returns zero value when the collection is empty. + +```go +latest := lo.Latest([]time.Time{time.Now(), time.Time{}}) +// 2023-04-01 01:02:03 +0000 UTC +``` + +### LatestBy + +Search the maximum time.Time of a collection using the given iteratee function. + +Returns zero value when the collection is empty. + +```go +type foo struct { + bar time.Time +} + +latest := lo.LatestBy([]foo{{time.Now()}, {}}, func(i foo) time.Time { + return i.bar +}) +// {bar:{2023-04-01 01:02:03 +0000 UTC}} +``` + +### First + +Returns the first element of a collection and check for availability of the first element. + +```go +first, ok := lo.First([]int{1, 2, 3}) +// 1, true + +first, ok := lo.First([]int{}) +// 0, false +``` + +### FirstOrEmpty + +Returns the first element of a collection or zero value if empty. + +```go +first := lo.FirstOrEmpty([]int{1, 2, 3}) +// 1 + +first := lo.FirstOrEmpty([]int{}) +// 0 +``` +### FirstOr + +Returns the first element of a collection or the fallback value if empty. + +```go +first := lo.FirstOr([]int{1, 2, 3}, 245) +// 1 + +first := lo.FirstOr([]int{}, 31) +// 31 +``` + ### Last Returns the last element of a collection or error if empty. ```go -last, err := lo.Last([]int{1, 2, 3}) +last, ok := lo.Last([]int{1, 2, 3}) // 3 +// true + +last, ok := lo.Last([]int{}) +// 0 +// false +``` + +### LastOrEmpty + +Returns the first element of a collection or zero value if empty. + +```go +last := lo.LastOrEmpty([]int{1, 2, 3}) +// 3 + +last := lo.LastOrEmpty([]int{}) +// 0 +``` +### LastOr + +Returns the first element of a collection or the fallback value if empty. + +```go +last := lo.LastOr([]int{1, 2, 3}, 245) +// 3 + +last := lo.LastOr([]int{}, 31) +// 31 ``` ### Nth @@ -2047,7 +2529,7 @@ result := lo.TernaryF(false, func() string { return "a" }, func() string { retur // "b" ``` -Useful to avoid nil-pointer dereferencing in intializations, or avoid running unnecessary code +Useful to avoid nil-pointer dereferencing in initializations, or avoid running unnecessary code ```go var s *string @@ -2155,31 +2637,64 @@ result := lo.Switch(1). [[play](https://go.dev/play/p/TGbKUMAeRUd)] +### IsNil + +Checks if a value is nil or if it's a reference type with a nil underlying value. + +```go +var x int +IsNil(x)) +// false + +var k struct{} +IsNil(k) +// false + +var i *int +IsNil(i) +// true + +var ifaceWithNilValue any = (*string)(nil) +IsNil(ifaceWithNilValue) +// true +ifaceWithNilValue == nil +// false +``` + ### ToPtr -Returns a pointer copy of value. +Returns a pointer copy of the value. ```go ptr := lo.ToPtr("hello world") // *string{"hello world"} ``` +### Nil + +Returns a nil pointer of type. + +```go +ptr := lo.Nil[float64]() +// nil +``` + ### EmptyableToPtr Returns a pointer copy of value if it's nonzero. Otherwise, returns nil pointer. ```go -ptr := lo.EmptyableToPtr[[]int](nil) +ptr := lo.EmptyableToPtr(nil) // nil -ptr := lo.EmptyableToPtr[string]("") +ptr := lo.EmptyableToPtr("") // nil -ptr := lo.EmptyableToPtr[[]int]([]int{}) +ptr := lo.EmptyableToPtr([]int{}) // *[]int{} -ptr := lo.EmptyableToPtr[string]("hello world") +ptr := lo.EmptyableToPtr("hello world") // *string{"hello world"} ``` @@ -2192,7 +2707,7 @@ str := "hello world" value := lo.FromPtr(&str) // "hello world" -value := lo.FromPtr[string](nil) +value := lo.FromPtr(nil) // "" ``` @@ -2205,7 +2720,7 @@ str := "hello world" value := lo.FromPtrOr(&str, "empty") // "hello world" -value := lo.FromPtrOr[string](nil, "empty") +value := lo.FromPtrOr(nil, "empty") // "empty" ``` @@ -2218,6 +2733,36 @@ ptr := lo.ToSlicePtr([]string{"hello", "world"}) // []*string{"hello", "world"} ``` +### FromSlicePtr + +Returns a slice with the pointer values. +Returns a zero value in case of a nil pointer element. + +```go +str1 := "hello" +str2 := "world" + +ptr := lo.FromSlicePtr[string]([]*string{&str1, &str2, nil}) +// []string{"hello", "world", ""} + +ptr := lo.Compact( + lo.FromSlicePtr[string]([]*string{&str1, &str2, nil}), +) +// []string{"hello", "world"} +``` + +### FromSlicePtrOr + +Returns a slice with the pointer values or the fallback value. + +```go +str1 := "hello" +str2 := "world" + +ptr := lo.FromSlicePtrOr[string]([]*string{&str1, &str2, "fallback value"}) +// []string{"hello", "world", "fallback value"} +``` + ### ToAnySlice Returns a slice with all elements mapped to `any` type. @@ -2315,10 +2860,27 @@ result, ok := lo.Coalesce("") var nilStr *string str := "foobar" -result, ok := lo.Coalesce[*string](nil, nilStr, &str) +result, ok := lo.Coalesce(nil, nilStr, &str) // &"foobar" true ``` +### CoalesceOrEmpty + +Returns the first non-empty arguments. Arguments must be comparable. + +```go +result := lo.CoalesceOrEmpty(0, 1, 2, 3) +// 1 + +result := lo.CoalesceOrEmpty("") +// "" + +var nilStr *string +str := "foobar" +result := lo.CoalesceOrEmpty(nil, nilStr, &str) +// &"foobar" +``` + ### Partial Returns new function that, when called, has its first argument set to the provided value. @@ -2568,7 +3130,7 @@ ch := lo.Async2(func() (int, string) { Implements a Saga pattern. ```go -transaction := NewTransaction[int](). +transaction := NewTransaction(). Then( func(state int) (int, error) { fmt.Println("step 1") @@ -2615,6 +3177,81 @@ _, _ = transaction.Process(-5) // rollback 1 ``` +### WaitFor + +Runs periodically until a condition is validated. + +```go +alwaysTrue := func(i int) bool { return true } +alwaysFalse := func(i int) bool { return false } +laterTrue := func(i int) bool { + return i > 5 +} + +iterations, duration, ok := lo.WaitFor(alwaysTrue, 10*time.Millisecond, 2 * time.Millisecond) +// 1 +// 1ms +// true + +iterations, duration, ok := lo.WaitFor(alwaysFalse, 10*time.Millisecond, time.Millisecond) +// 10 +// 10ms +// false + +iterations, duration, ok := lo.WaitFor(laterTrue, 10*time.Millisecond, time.Millisecond) +// 7 +// 7ms +// true + +iterations, duration, ok := lo.WaitFor(laterTrue, 10*time.Millisecond, 5*time.Millisecond) +// 2 +// 10ms +// false +``` + + +### WaitForWithContext + +Runs periodically until a condition is validated or context is invalid. + +The condition receives also the context, so it can invalidate the process in the condition checker + +```go +ctx := context.Background() + +alwaysTrue := func(_ context.Context, i int) bool { return true } +alwaysFalse := func(_ context.Context, i int) bool { return false } +laterTrue := func(_ context.Context, i int) bool { + return i >= 5 +} + +iterations, duration, ok := lo.WaitForWithContext(ctx, alwaysTrue, 10*time.Millisecond, 2 * time.Millisecond) +// 1 +// 1ms +// true + +iterations, duration, ok := lo.WaitForWithContext(ctx, alwaysFalse, 10*time.Millisecond, time.Millisecond) +// 10 +// 10ms +// false + +iterations, duration, ok := lo.WaitForWithContext(ctx, laterTrue, 10*time.Millisecond, time.Millisecond) +// 5 +// 5ms +// true + +iterations, duration, ok := lo.WaitForWithContext(ctx, laterTrue, 10*time.Millisecond, 5*time.Millisecond) +// 2 +// 10ms +// false + +expiringCtx, cancel := context.WithTimeout(ctx, 5*time.Millisecond) +iterations, duration, ok := lo.WaitForWithContext(expiringCtx, alwaysFalse, 100*time.Millisecond, time.Millisecond) +// 5 +// 5.1ms +// false +``` + ### Validate Helper function that creates an error when a condition is not met. @@ -2687,7 +3324,7 @@ lo.Must0(ok, "'%s' must always contain '%s'", myString, requiredChar) list := []int{0, 1, 2} item := 5 -lo.Must0(lo.Contains[int](list, item), "'%s' must always contain '%s'", list, item) +lo.Must0(lo.Contains(list, item), "'%s' must always contain '%s'", list, item) ... ``` @@ -2695,7 +3332,7 @@ lo.Must0(lo.Contains[int](list, item), "'%s' must always contain '%s'", list, it ### Try -Calls the function and return false in case of error and on panic. +Calls the function and returns false in case of error and panic. ```go ok := lo.Try(func() error { @@ -2719,7 +3356,7 @@ ok := lo.Try(func() error { ### Try{0->6} -The same behavior than `Try`, but callback returns 2 variables. +The same behavior as `Try`, but the callback returns 2 variables. ```go ok := lo.Try2(func() (string, error) { @@ -2760,7 +3397,7 @@ str, ok := lo.TryOr(func() error { ### TryOr{0->6} -The same behavior than `TryOr`, but callback returns `X` variables. +The same behavior as `TryOr`, but the callback returns `X` variables. ```go str, nbr, ok := lo.TryOr2(func() (string, int, error) { @@ -2776,7 +3413,7 @@ str, nbr, ok := lo.TryOr2(func() (string, int, error) { ### TryWithErrorValue -The same behavior than `Try`, but also returns value passed to panic. +The same behavior as `Try`, but also returns the value passed to panic. ```go err, ok := lo.TryWithErrorValue(func() error { @@ -2790,7 +3427,7 @@ err, ok := lo.TryWithErrorValue(func() error { ### TryCatch -The same behavior than `Try`, but calls the catch function in case of error. +The same behavior as `Try`, but calls the catch function in case of error. ```go caught := false @@ -2809,7 +3446,7 @@ ok := lo.TryCatch(func() error { ### TryCatchWithErrorValue -The same behavior than `TryWithErrorValue`, but calls the catch function in case of error. +The same behavior as `TryWithErrorValue`, but calls the catch function in case of error. ```go caught := false @@ -2853,7 +3490,7 @@ if rateLimitErr, ok := lo.ErrorsAs[*RateLimitError](err); ok { ## 🛩 Benchmark -We executed a simple benchmark with the a dead-simple `lo.Map` loop: +We executed a simple benchmark with a dead-simple `lo.Map` loop: See the full implementation [here](./benchmark_test.go). @@ -2890,13 +3527,13 @@ ok github.com/samber/lo 6.657s ## 🤝 Contributing -- Ping me on twitter [@samuelberthe](https://twitter.com/samuelberthe) (DMs, mentions, whatever :)) +- Ping me on Twitter [@samuelberthe](https://twitter.com/samuelberthe) (DMs, mentions, whatever :)) - Fork the [project](https://github.com/samber/lo) - Fix [open issues](https://github.com/samber/lo/issues) or request new features Don't hesitate ;) -Helper naming: helpers must be self explanatory and respect standards (other languages, libraries...). Feel free to suggest many names in your contributions. +Helper naming: helpers must be self-explanatory and respect standards (other languages, libraries...). Feel free to suggest many names in your contributions. ### With Docker @@ -2924,10 +3561,10 @@ make watch-test Give a ⭐️ if this project helped you! -[![support us](https://c5.patreon.com/external/logo/become_a_patron_button.png)](https://www.patreon.com/samber) +[![GitHub Sponsors](https://img.shields.io/github/sponsors/samber?style=for-the-badge)](https://github.com/sponsors/samber) ## 📝 License Copyright © 2022 [Samuel Berthe](https://github.com/samber). -This project is [MIT](./LICENSE) licensed. +This project is under [MIT](./LICENSE) license. diff --git a/vendor/github.com/samber/lo/channel.go b/vendor/github.com/samber/lo/channel.go index 5dcac328a8..228705ae39 100644 --- a/vendor/github.com/samber/lo/channel.go +++ b/vendor/github.com/samber/lo/channel.go @@ -1,9 +1,10 @@ package lo import ( - "math/rand" "sync" "time" + + "github.com/samber/lo/internal/rand" ) type DispatchingStrategy[T any] func(msg T, index uint64, channels []<-chan T) int @@ -86,7 +87,7 @@ func DispatchingStrategyRoundRobin[T any](msg T, index uint64, channels []<-chan // If the channel capacity is exceeded, another random channel will be selected and so on. func DispatchingStrategyRandom[T any](msg T, index uint64, channels []<-chan T) int { for { - i := rand.Intn(len(channels)) + i := rand.IntN(len(channels)) if channelIsNotFull(channels[i]) { return i } @@ -108,7 +109,7 @@ func DispatchingStrategyWeightedRandom[T any](weights []int) DispatchingStrategy return func(msg T, index uint64, channels []<-chan T) int { for { - i := seq[rand.Intn(len(seq))] + i := seq[rand.IntN(len(seq))] if channelIsNotFull(channels[i]) { return i } @@ -156,8 +157,8 @@ func SliceToChannel[T any](bufferSize int, collection []T) <-chan T { ch := make(chan T, bufferSize) go func() { - for _, item := range collection { - ch <- item + for i := range collection { + ch <- collection[i] } close(ch) @@ -261,13 +262,13 @@ func FanIn[T any](channelBufferCap int, upstreams ...<-chan T) <-chan T { // Start an output goroutine for each input channel in upstreams. wg.Add(len(upstreams)) - for _, c := range upstreams { - go func(c <-chan T) { - for n := range c { + for i := range upstreams { + go func(index int) { + for n := range upstreams[index] { out <- n } wg.Done() - }(c) + }(i) } // Start a goroutine to close out once all the output goroutines are done. diff --git a/vendor/github.com/samber/lo/concurrency.go b/vendor/github.com/samber/lo/concurrency.go index d0aca2aa28..a2ebbce20a 100644 --- a/vendor/github.com/samber/lo/concurrency.go +++ b/vendor/github.com/samber/lo/concurrency.go @@ -1,6 +1,10 @@ package lo -import "sync" +import ( + "context" + "sync" + "time" +) type synchronize struct { locker sync.Locker @@ -50,7 +54,7 @@ func Async1[A any](f func() A) <-chan A { } // Async2 has the same behavior as Async, but returns the 2 results as a tuple inside the channel. -func Async2[A any, B any](f func() (A, B)) <-chan Tuple2[A, B] { +func Async2[A, B any](f func() (A, B)) <-chan Tuple2[A, B] { ch := make(chan Tuple2[A, B], 1) go func() { ch <- T2(f()) @@ -59,7 +63,7 @@ func Async2[A any, B any](f func() (A, B)) <-chan Tuple2[A, B] { } // Async3 has the same behavior as Async, but returns the 3 results as a tuple inside the channel. -func Async3[A any, B any, C any](f func() (A, B, C)) <-chan Tuple3[A, B, C] { +func Async3[A, B, C any](f func() (A, B, C)) <-chan Tuple3[A, B, C] { ch := make(chan Tuple3[A, B, C], 1) go func() { ch <- T3(f()) @@ -68,7 +72,7 @@ func Async3[A any, B any, C any](f func() (A, B, C)) <-chan Tuple3[A, B, C] { } // Async4 has the same behavior as Async, but returns the 4 results as a tuple inside the channel. -func Async4[A any, B any, C any, D any](f func() (A, B, C, D)) <-chan Tuple4[A, B, C, D] { +func Async4[A, B, C, D any](f func() (A, B, C, D)) <-chan Tuple4[A, B, C, D] { ch := make(chan Tuple4[A, B, C, D], 1) go func() { ch <- T4(f()) @@ -77,7 +81,7 @@ func Async4[A any, B any, C any, D any](f func() (A, B, C, D)) <-chan Tuple4[A, } // Async5 has the same behavior as Async, but returns the 5 results as a tuple inside the channel. -func Async5[A any, B any, C any, D any, E any](f func() (A, B, C, D, E)) <-chan Tuple5[A, B, C, D, E] { +func Async5[A, B, C, D, E any](f func() (A, B, C, D, E)) <-chan Tuple5[A, B, C, D, E] { ch := make(chan Tuple5[A, B, C, D, E], 1) go func() { ch <- T5(f()) @@ -86,10 +90,47 @@ func Async5[A any, B any, C any, D any, E any](f func() (A, B, C, D, E)) <-chan } // Async6 has the same behavior as Async, but returns the 6 results as a tuple inside the channel. -func Async6[A any, B any, C any, D any, E any, F any](f func() (A, B, C, D, E, F)) <-chan Tuple6[A, B, C, D, E, F] { +func Async6[A, B, C, D, E, F any](f func() (A, B, C, D, E, F)) <-chan Tuple6[A, B, C, D, E, F] { ch := make(chan Tuple6[A, B, C, D, E, F], 1) go func() { ch <- T6(f()) }() return ch } + +// WaitFor runs periodically until a condition is validated. +func WaitFor(condition func(i int) bool, timeout time.Duration, heartbeatDelay time.Duration) (totalIterations int, elapsed time.Duration, conditionFound bool) { + conditionWithContext := func(_ context.Context, currentIteration int) bool { + return condition(currentIteration) + } + return WaitForWithContext(context.Background(), conditionWithContext, timeout, heartbeatDelay) +} + +// WaitForWithContext runs periodically until a condition is validated or context is canceled. +func WaitForWithContext(ctx context.Context, condition func(ctx context.Context, currentIteration int) bool, timeout time.Duration, heartbeatDelay time.Duration) (totalIterations int, elapsed time.Duration, conditionFound bool) { + start := time.Now() + + if ctx.Err() != nil { + return totalIterations, time.Since(start), false + } + + ctx, cleanCtx := context.WithTimeout(ctx, timeout) + ticker := time.NewTicker(heartbeatDelay) + + defer func() { + cleanCtx() + ticker.Stop() + }() + + for { + select { + case <-ctx.Done(): + return totalIterations, time.Since(start), false + case <-ticker.C: + totalIterations++ + if condition(ctx, totalIterations-1) { + return totalIterations, time.Since(start), true + } + } + } +} diff --git a/vendor/github.com/samber/lo/errors.go b/vendor/github.com/samber/lo/errors.go index a99013d950..e63bf5d824 100644 --- a/vendor/github.com/samber/lo/errors.go +++ b/vendor/github.com/samber/lo/errors.go @@ -15,7 +15,7 @@ func Validate(ok bool, format string, args ...any) error { return nil } -func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { +func messageFromMsgAndArgs(msgAndArgs ...any) string { if len(msgAndArgs) == 1 { if msgAsStr, ok := msgAndArgs[0].(string); ok { return msgAsStr @@ -29,7 +29,7 @@ func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { } // must panics if err is error or false. -func must(err any, messageArgs ...interface{}) { +func must(err any, messageArgs ...any) { if err == nil { return } @@ -61,54 +61,54 @@ func must(err any, messageArgs ...interface{}) { // Must is a helper that wraps a call to a function returning a value and an error // and panics if err is error or false. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must[T any](val T, err any, messageArgs ...interface{}) T { +func Must[T any](val T, err any, messageArgs ...any) T { must(err, messageArgs...) return val } // Must0 has the same behavior as Must, but callback returns no variable. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must0(err any, messageArgs ...interface{}) { +func Must0(err any, messageArgs ...any) { must(err, messageArgs...) } // Must1 is an alias to Must // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must1[T any](val T, err any, messageArgs ...interface{}) T { +func Must1[T any](val T, err any, messageArgs ...any) T { return Must(val, err, messageArgs...) } // Must2 has the same behavior as Must, but callback returns 2 variables. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must2[T1 any, T2 any](val1 T1, val2 T2, err any, messageArgs ...interface{}) (T1, T2) { +func Must2[T1, T2 any](val1 T1, val2 T2, err any, messageArgs ...any) (T1, T2) { must(err, messageArgs...) return val1, val2 } // Must3 has the same behavior as Must, but callback returns 3 variables. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must3[T1 any, T2 any, T3 any](val1 T1, val2 T2, val3 T3, err any, messageArgs ...interface{}) (T1, T2, T3) { +func Must3[T1, T2, T3 any](val1 T1, val2 T2, val3 T3, err any, messageArgs ...any) (T1, T2, T3) { must(err, messageArgs...) return val1, val2, val3 } // Must4 has the same behavior as Must, but callback returns 4 variables. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must4[T1 any, T2 any, T3 any, T4 any](val1 T1, val2 T2, val3 T3, val4 T4, err any, messageArgs ...interface{}) (T1, T2, T3, T4) { +func Must4[T1, T2, T3, T4 any](val1 T1, val2 T2, val3 T3, val4 T4, err any, messageArgs ...any) (T1, T2, T3, T4) { must(err, messageArgs...) return val1, val2, val3, val4 } // Must5 has the same behavior as Must, but callback returns 5 variables. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must5[T1 any, T2 any, T3 any, T4 any, T5 any](val1 T1, val2 T2, val3 T3, val4 T4, val5 T5, err any, messageArgs ...interface{}) (T1, T2, T3, T4, T5) { +func Must5[T1, T2, T3, T4, T5 any](val1 T1, val2 T2, val3 T3, val4 T4, val5 T5, err any, messageArgs ...any) (T1, T2, T3, T4, T5) { must(err, messageArgs...) return val1, val2, val3, val4, val5 } // Must6 has the same behavior as Must, but callback returns 6 variables. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must6[T1 any, T2 any, T3 any, T4 any, T5 any, T6 any](val1 T1, val2 T2, val3 T3, val4 T4, val5 T5, val6 T6, err any, messageArgs ...interface{}) (T1, T2, T3, T4, T5, T6) { +func Must6[T1, T2, T3, T4, T5, T6 any](val1 T1, val2 T2, val3 T3, val4 T4, val5 T5, val6 T6, err any, messageArgs ...any) (T1, T2, T3, T4, T5, T6) { must(err, messageArgs...) return val1, val2, val3, val4, val5, val6 } @@ -215,7 +215,7 @@ func TryOr1[A any](callback func() (A, error), fallbackA A) (A, bool) { // TryOr2 has the same behavior as Must, but returns a default value in case of error. // Play: https://go.dev/play/p/B4F7Wg2Zh9X -func TryOr2[A any, B any](callback func() (A, B, error), fallbackA A, fallbackB B) (A, B, bool) { +func TryOr2[A, B any](callback func() (A, B, error), fallbackA A, fallbackB B) (A, B, bool) { ok := false Try0(func() { @@ -232,7 +232,7 @@ func TryOr2[A any, B any](callback func() (A, B, error), fallbackA A, fallbackB // TryOr3 has the same behavior as Must, but returns a default value in case of error. // Play: https://go.dev/play/p/B4F7Wg2Zh9X -func TryOr3[A any, B any, C any](callback func() (A, B, C, error), fallbackA A, fallbackB B, fallbackC C) (A, B, C, bool) { +func TryOr3[A, B, C any](callback func() (A, B, C, error), fallbackA A, fallbackB B, fallbackC C) (A, B, C, bool) { ok := false Try0(func() { @@ -250,7 +250,7 @@ func TryOr3[A any, B any, C any](callback func() (A, B, C, error), fallbackA A, // TryOr4 has the same behavior as Must, but returns a default value in case of error. // Play: https://go.dev/play/p/B4F7Wg2Zh9X -func TryOr4[A any, B any, C any, D any](callback func() (A, B, C, D, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D) (A, B, C, D, bool) { +func TryOr4[A, B, C, D any](callback func() (A, B, C, D, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D) (A, B, C, D, bool) { ok := false Try0(func() { @@ -269,7 +269,7 @@ func TryOr4[A any, B any, C any, D any](callback func() (A, B, C, D, error), fal // TryOr5 has the same behavior as Must, but returns a default value in case of error. // Play: https://go.dev/play/p/B4F7Wg2Zh9X -func TryOr5[A any, B any, C any, D any, E any](callback func() (A, B, C, D, E, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D, fallbackE E) (A, B, C, D, E, bool) { +func TryOr5[A, B, C, D, E any](callback func() (A, B, C, D, E, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D, fallbackE E) (A, B, C, D, E, bool) { ok := false Try0(func() { @@ -289,7 +289,7 @@ func TryOr5[A any, B any, C any, D any, E any](callback func() (A, B, C, D, E, e // TryOr6 has the same behavior as Must, but returns a default value in case of error. // Play: https://go.dev/play/p/B4F7Wg2Zh9X -func TryOr6[A any, B any, C any, D any, E any, F any](callback func() (A, B, C, D, E, F, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D, fallbackE E, fallbackF F) (A, B, C, D, E, F, bool) { +func TryOr6[A, B, C, D, E, F any](callback func() (A, B, C, D, E, F, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D, fallbackE E, fallbackF F) (A, B, C, D, E, F, bool) { ok := false Try0(func() { diff --git a/vendor/github.com/samber/lo/find.go b/vendor/github.com/samber/lo/find.go index f8caeb8959..ea577ae2a6 100644 --- a/vendor/github.com/samber/lo/find.go +++ b/vendor/github.com/samber/lo/find.go @@ -2,18 +2,17 @@ package lo import ( "fmt" - "math/rand" + "time" - "golang.org/x/exp/constraints" + "github.com/samber/lo/internal/constraints" + "github.com/samber/lo/internal/rand" ) -// import "golang.org/x/exp/constraints" - // IndexOf returns the index at which the first occurrence of a value is found in an array or return -1 // if the value cannot be found. func IndexOf[T comparable](collection []T, element T) int { - for i, item := range collection { - if item == element { + for i := range collection { + if collection[i] == element { return i } } @@ -37,9 +36,9 @@ func LastIndexOf[T comparable](collection []T, element T) int { // Find search an element in a slice based on a predicate. It returns element and true if element was found. func Find[T any](collection []T, predicate func(item T) bool) (T, bool) { - for _, item := range collection { - if predicate(item) { - return item, true + for i := range collection { + if predicate(collection[i]) { + return collection[i], true } } @@ -50,9 +49,9 @@ func Find[T any](collection []T, predicate func(item T) bool) (T, bool) { // FindIndexOf searches an element in a slice based on a predicate and returns the index and true. // It returns -1 and false if the element is not found. func FindIndexOf[T any](collection []T, predicate func(item T) bool) (T, int, bool) { - for i, item := range collection { - if predicate(item) { - return item, i, true + for i := range collection { + if predicate(collection[i]) { + return collection[i], i, true } } @@ -77,9 +76,9 @@ func FindLastIndexOf[T any](collection []T, predicate func(item T) bool) (T, int // FindOrElse search an element in a slice based on a predicate. It returns the element if found or a given fallback value otherwise. func FindOrElse[T any](collection []T, fallback T, predicate func(item T) bool) T { - for _, item := range collection { - if predicate(item) { - return item + for i := range collection { + if predicate(collection[i]) { + return collection[i] } } @@ -88,8 +87,8 @@ func FindOrElse[T any](collection []T, fallback T, predicate func(item T) bool) // FindKey returns the key of the first value matching. func FindKey[K comparable, V comparable](object map[K]V, value V) (K, bool) { - for k, v := range object { - if v == value { + for k := range object { + if object[k] == value { return k, true } } @@ -99,8 +98,8 @@ func FindKey[K comparable, V comparable](object map[K]V, value V) (K, bool) { // FindKeyBy returns the key of the first element predicate returns truthy for. func FindKeyBy[K comparable, V any](object map[K]V, predicate func(key K, value V) bool) (K, bool) { - for k, v := range object { - if predicate(k, v) { + for k := range object { + if predicate(k, object[k]) { return k, true } } @@ -110,23 +109,23 @@ func FindKeyBy[K comparable, V any](object map[K]V, predicate func(key K, value // FindUniques returns a slice with all the unique elements of the collection. // The order of result values is determined by the order they occur in the collection. -func FindUniques[T comparable](collection []T) []T { +func FindUniques[T comparable, Slice ~[]T](collection Slice) Slice { isDupl := make(map[T]bool, len(collection)) - for _, item := range collection { - duplicated, ok := isDupl[item] + for i := range collection { + duplicated, ok := isDupl[collection[i]] if !ok { - isDupl[item] = false + isDupl[collection[i]] = false } else if !duplicated { - isDupl[item] = true + isDupl[collection[i]] = true } } - result := make([]T, 0, len(collection)-len(isDupl)) + result := make(Slice, 0, len(collection)-len(isDupl)) - for _, item := range collection { - if duplicated := isDupl[item]; !duplicated { - result = append(result, item) + for i := range collection { + if duplicated := isDupl[collection[i]]; !duplicated { + result = append(result, collection[i]) } } @@ -136,11 +135,11 @@ func FindUniques[T comparable](collection []T) []T { // FindUniquesBy returns a slice with all the unique elements of the collection. // The order of result values is determined by the order they occur in the array. It accepts `iteratee` which is // invoked for each element in array to generate the criterion by which uniqueness is computed. -func FindUniquesBy[T any, U comparable](collection []T, iteratee func(item T) U) []T { +func FindUniquesBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) Slice { isDupl := make(map[U]bool, len(collection)) - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) duplicated, ok := isDupl[key] if !ok { @@ -150,13 +149,13 @@ func FindUniquesBy[T any, U comparable](collection []T, iteratee func(item T) U) } } - result := make([]T, 0, len(collection)-len(isDupl)) + result := make(Slice, 0, len(collection)-len(isDupl)) - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) if duplicated := isDupl[key]; !duplicated { - result = append(result, item) + result = append(result, collection[i]) } } @@ -165,24 +164,24 @@ func FindUniquesBy[T any, U comparable](collection []T, iteratee func(item T) U) // FindDuplicates returns a slice with the first occurrence of each duplicated elements of the collection. // The order of result values is determined by the order they occur in the collection. -func FindDuplicates[T comparable](collection []T) []T { +func FindDuplicates[T comparable, Slice ~[]T](collection Slice) Slice { isDupl := make(map[T]bool, len(collection)) - for _, item := range collection { - duplicated, ok := isDupl[item] + for i := range collection { + duplicated, ok := isDupl[collection[i]] if !ok { - isDupl[item] = false + isDupl[collection[i]] = false } else if !duplicated { - isDupl[item] = true + isDupl[collection[i]] = true } } - result := make([]T, 0, len(collection)-len(isDupl)) + result := make(Slice, 0, len(collection)-len(isDupl)) - for _, item := range collection { - if duplicated := isDupl[item]; duplicated { - result = append(result, item) - isDupl[item] = false + for i := range collection { + if duplicated := isDupl[collection[i]]; duplicated { + result = append(result, collection[i]) + isDupl[collection[i]] = false } } @@ -192,11 +191,11 @@ func FindDuplicates[T comparable](collection []T) []T { // FindDuplicatesBy returns a slice with the first occurrence of each duplicated elements of the collection. // The order of result values is determined by the order they occur in the array. It accepts `iteratee` which is // invoked for each element in array to generate the criterion by which uniqueness is computed. -func FindDuplicatesBy[T any, U comparable](collection []T, iteratee func(item T) U) []T { +func FindDuplicatesBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) Slice { isDupl := make(map[U]bool, len(collection)) - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) duplicated, ok := isDupl[key] if !ok { @@ -206,13 +205,13 @@ func FindDuplicatesBy[T any, U comparable](collection []T, iteratee func(item T) } } - result := make([]T, 0, len(collection)-len(isDupl)) + result := make(Slice, 0, len(collection)-len(isDupl)) - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) if duplicated := isDupl[key]; duplicated { - result = append(result, item) + result = append(result, collection[i]) isDupl[key] = false } } @@ -221,7 +220,7 @@ func FindDuplicatesBy[T any, U comparable](collection []T, iteratee func(item T) } // Min search the minimum value of a collection. -// Returns zero value when collection is empty. +// Returns zero value when the collection is empty. func Min[T constraints.Ordered](collection []T) T { var min T @@ -244,7 +243,7 @@ func Min[T constraints.Ordered](collection []T) T { // MinBy search the minimum value of a collection using the given comparison function. // If several values of the collection are equal to the smallest value, returns the first such value. -// Returns zero value when collection is empty. +// Returns zero value when the collection is empty. func MinBy[T any](collection []T, comparison func(a T, b T) bool) T { var min T @@ -265,8 +264,54 @@ func MinBy[T any](collection []T, comparison func(a T, b T) bool) T { return min } +// Earliest search the minimum time.Time of a collection. +// Returns zero value when the collection is empty. +func Earliest(times ...time.Time) time.Time { + var min time.Time + + if len(times) == 0 { + return min + } + + min = times[0] + + for i := 1; i < len(times); i++ { + item := times[i] + + if item.Before(min) { + min = item + } + } + + return min +} + +// EarliestBy search the minimum time.Time of a collection using the given iteratee function. +// Returns zero value when the collection is empty. +func EarliestBy[T any](collection []T, iteratee func(item T) time.Time) T { + var earliest T + + if len(collection) == 0 { + return earliest + } + + earliest = collection[0] + earliestTime := iteratee(collection[0]) + + for i := 1; i < len(collection); i++ { + itemTime := iteratee(collection[i]) + + if itemTime.Before(earliestTime) { + earliest = collection[i] + earliestTime = itemTime + } + } + + return earliest +} + // Max searches the maximum value of a collection. -// Returns zero value when collection is empty. +// Returns zero value when the collection is empty. func Max[T constraints.Ordered](collection []T) T { var max T @@ -289,7 +334,7 @@ func Max[T constraints.Ordered](collection []T) T { // MaxBy search the maximum value of a collection using the given comparison function. // If several values of the collection are equal to the greatest value, returns the first such value. -// Returns zero value when collection is empty. +// Returns zero value when the collection is empty. func MaxBy[T any](collection []T, comparison func(a T, b T) bool) T { var max T @@ -310,16 +355,106 @@ func MaxBy[T any](collection []T, comparison func(a T, b T) bool) T { return max } +// Latest search the maximum time.Time of a collection. +// Returns zero value when the collection is empty. +func Latest(times ...time.Time) time.Time { + var max time.Time + + if len(times) == 0 { + return max + } + + max = times[0] + + for i := 1; i < len(times); i++ { + item := times[i] + + if item.After(max) { + max = item + } + } + + return max +} + +// LatestBy search the maximum time.Time of a collection using the given iteratee function. +// Returns zero value when the collection is empty. +func LatestBy[T any](collection []T, iteratee func(item T) time.Time) T { + var latest T + + if len(collection) == 0 { + return latest + } + + latest = collection[0] + latestTime := iteratee(collection[0]) + + for i := 1; i < len(collection); i++ { + itemTime := iteratee(collection[i]) + + if itemTime.After(latestTime) { + latest = collection[i] + latestTime = itemTime + } + } + + return latest +} + +// First returns the first element of a collection and check for availability of the first element. +func First[T any](collection []T) (T, bool) { + length := len(collection) + + if length == 0 { + var t T + return t, false + } + + return collection[0], true +} + +// FirstOrEmpty returns the first element of a collection or zero value if empty. +func FirstOrEmpty[T any](collection []T) T { + i, _ := First(collection) + return i +} + +// FirstOr returns the first element of a collection or the fallback value if empty. +func FirstOr[T any](collection []T, fallback T) T { + i, ok := First(collection) + if !ok { + return fallback + } + + return i +} + // Last returns the last element of a collection or error if empty. -func Last[T any](collection []T) (T, error) { +func Last[T any](collection []T) (T, bool) { length := len(collection) if length == 0 { var t T - return t, fmt.Errorf("last: cannot extract the last element of an empty slice") + return t, false + } + + return collection[length-1], true +} + +// Returns the last element of a collection or zero value if empty. +func LastOrEmpty[T any](collection []T) T { + i, _ := Last(collection) + return i +} + +// LastOr returns the last element of a collection or the fallback value if empty. +func LastOr[T any](collection []T, fallback T) T { + i, ok := Last(collection) + if !ok { + return fallback } - return collection[length-1], nil + return i } // Nth returns the element at index `nth` of collection. If `nth` is negative, the nth element @@ -345,21 +480,21 @@ func Sample[T any](collection []T) T { return Empty[T]() } - return collection[rand.Intn(size)] + return collection[rand.IntN(size)] } // Samples returns N random unique items from collection. -func Samples[T any](collection []T, count int) []T { +func Samples[T any, Slice ~[]T](collection Slice, count int) Slice { size := len(collection) - copy := append([]T{}, collection...) + copy := append(Slice{}, collection...) - results := []T{} + results := Slice{} for i := 0; i < size && i < count; i++ { copyLength := size - i - index := rand.Intn(size - i) + index := rand.IntN(size - i) results = append(results, copy[index]) // Removes element. diff --git a/vendor/github.com/samber/lo/internal/constraints/constraints.go b/vendor/github.com/samber/lo/internal/constraints/constraints.go new file mode 100644 index 0000000000..3eb1cda55f --- /dev/null +++ b/vendor/github.com/samber/lo/internal/constraints/constraints.go @@ -0,0 +1,42 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package constraints defines a set of useful constraints to be used +// with type parameters. +package constraints + +// Signed is a constraint that permits any signed integer type. +// If future releases of Go add new predeclared signed integer types, +// this constraint will be modified to include them. +type Signed interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 +} + +// Unsigned is a constraint that permits any unsigned integer type. +// If future releases of Go add new predeclared unsigned integer types, +// this constraint will be modified to include them. +type Unsigned interface { + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr +} + +// Integer is a constraint that permits any integer type. +// If future releases of Go add new predeclared integer types, +// this constraint will be modified to include them. +type Integer interface { + Signed | Unsigned +} + +// Float is a constraint that permits any floating-point type. +// If future releases of Go add new predeclared floating-point types, +// this constraint will be modified to include them. +type Float interface { + ~float32 | ~float64 +} + +// Complex is a constraint that permits any complex numeric type. +// If future releases of Go add new predeclared complex numeric types, +// this constraint will be modified to include them. +type Complex interface { + ~complex64 | ~complex128 +} diff --git a/vendor/github.com/samber/lo/internal/constraints/ordered_go118.go b/vendor/github.com/samber/lo/internal/constraints/ordered_go118.go new file mode 100644 index 0000000000..a124366fd3 --- /dev/null +++ b/vendor/github.com/samber/lo/internal/constraints/ordered_go118.go @@ -0,0 +1,11 @@ +//go:build !go1.21 + +package constraints + +// Ordered is a constraint that permits any ordered type: any type +// that supports the operators < <= >= >. +// If future releases of Go add new ordered types, +// this constraint will be modified to include them. +type Ordered interface { + Integer | Float | ~string +} diff --git a/vendor/github.com/samber/lo/internal/constraints/ordered_go121.go b/vendor/github.com/samber/lo/internal/constraints/ordered_go121.go new file mode 100644 index 0000000000..c02de93548 --- /dev/null +++ b/vendor/github.com/samber/lo/internal/constraints/ordered_go121.go @@ -0,0 +1,9 @@ +//go:build go1.21 + +package constraints + +import ( + "cmp" +) + +type Ordered = cmp.Ordered diff --git a/vendor/github.com/samber/lo/internal/rand/ordered_go118.go b/vendor/github.com/samber/lo/internal/rand/ordered_go118.go new file mode 100644 index 0000000000..a31bb9f2ae --- /dev/null +++ b/vendor/github.com/samber/lo/internal/rand/ordered_go118.go @@ -0,0 +1,14 @@ +//go:build !go1.22 + +package rand + +import "math/rand" + +func Shuffle(n int, swap func(i, j int)) { + rand.Shuffle(n, swap) +} + +func IntN(n int) int { + // bearer:disable go_gosec_crypto_weak_random + return rand.Intn(n) +} diff --git a/vendor/github.com/samber/lo/internal/rand/ordered_go122.go b/vendor/github.com/samber/lo/internal/rand/ordered_go122.go new file mode 100644 index 0000000000..532ed33933 --- /dev/null +++ b/vendor/github.com/samber/lo/internal/rand/ordered_go122.go @@ -0,0 +1,13 @@ +//go:build go1.22 + +package rand + +import "math/rand/v2" + +func Shuffle(n int, swap func(i, j int)) { + rand.Shuffle(n, swap) +} + +func IntN(n int) int { + return rand.IntN(n) +} diff --git a/vendor/github.com/samber/lo/intersect.go b/vendor/github.com/samber/lo/intersect.go index cf6cab3d13..2df0e74157 100644 --- a/vendor/github.com/samber/lo/intersect.go +++ b/vendor/github.com/samber/lo/intersect.go @@ -2,8 +2,8 @@ package lo // Contains returns true if an element is present in a collection. func Contains[T comparable](collection []T, element T) bool { - for _, item := range collection { - if item == element { + for i := range collection { + if collection[i] == element { return true } } @@ -13,8 +13,8 @@ func Contains[T comparable](collection []T, element T) bool { // ContainsBy returns true if predicate function return true. func ContainsBy[T any](collection []T, predicate func(item T) bool) bool { - for _, item := range collection { - if predicate(item) { + for i := range collection { + if predicate(collection[i]) { return true } } @@ -24,8 +24,8 @@ func ContainsBy[T any](collection []T, predicate func(item T) bool) bool { // Every returns true if all elements of a subset are contained into a collection or if the subset is empty. func Every[T comparable](collection []T, subset []T) bool { - for _, elem := range subset { - if !Contains(collection, elem) { + for i := range subset { + if !Contains(collection, subset[i]) { return false } } @@ -35,8 +35,8 @@ func Every[T comparable](collection []T, subset []T) bool { // EveryBy returns true if the predicate returns true for all of the elements in the collection or if the collection is empty. func EveryBy[T any](collection []T, predicate func(item T) bool) bool { - for _, v := range collection { - if !predicate(v) { + for i := range collection { + if !predicate(collection[i]) { return false } } @@ -47,8 +47,8 @@ func EveryBy[T any](collection []T, predicate func(item T) bool) bool { // Some returns true if at least 1 element of a subset is contained into a collection. // If the subset is empty Some returns false. func Some[T comparable](collection []T, subset []T) bool { - for _, elem := range subset { - if Contains(collection, elem) { + for i := range subset { + if Contains(collection, subset[i]) { return true } } @@ -59,8 +59,8 @@ func Some[T comparable](collection []T, subset []T) bool { // SomeBy returns true if the predicate returns true for any of the elements in the collection. // If the collection is empty SomeBy returns false. func SomeBy[T any](collection []T, predicate func(item T) bool) bool { - for _, v := range collection { - if predicate(v) { + for i := range collection { + if predicate(collection[i]) { return true } } @@ -70,8 +70,8 @@ func SomeBy[T any](collection []T, predicate func(item T) bool) bool { // None returns true if no element of a subset are contained into a collection or if the subset is empty. func None[T comparable](collection []T, subset []T) bool { - for _, elem := range subset { - if Contains(collection, elem) { + for i := range subset { + if Contains(collection, subset[i]) { return false } } @@ -81,8 +81,8 @@ func None[T comparable](collection []T, subset []T) bool { // NoneBy returns true if the predicate returns true for none of the elements in the collection or if the collection is empty. func NoneBy[T any](collection []T, predicate func(item T) bool) bool { - for _, v := range collection { - if predicate(v) { + for i := range collection { + if predicate(collection[i]) { return false } } @@ -91,17 +91,17 @@ func NoneBy[T any](collection []T, predicate func(item T) bool) bool { } // Intersect returns the intersection between two collections. -func Intersect[T comparable](list1 []T, list2 []T) []T { - result := []T{} +func Intersect[T comparable, Slice ~[]T](list1 Slice, list2 Slice) Slice { + result := Slice{} seen := map[T]struct{}{} - for _, elem := range list1 { - seen[elem] = struct{}{} + for i := range list1 { + seen[list1[i]] = struct{}{} } - for _, elem := range list2 { - if _, ok := seen[elem]; ok { - result = append(result, elem) + for i := range list2 { + if _, ok := seen[list2[i]]; ok { + result = append(result, list2[i]) } } @@ -111,30 +111,30 @@ func Intersect[T comparable](list1 []T, list2 []T) []T { // Difference returns the difference between two collections. // The first value is the collection of element absent of list2. // The second value is the collection of element absent of list1. -func Difference[T comparable](list1 []T, list2 []T) ([]T, []T) { - left := []T{} - right := []T{} +func Difference[T comparable, Slice ~[]T](list1 Slice, list2 Slice) (Slice, Slice) { + left := Slice{} + right := Slice{} seenLeft := map[T]struct{}{} seenRight := map[T]struct{}{} - for _, elem := range list1 { - seenLeft[elem] = struct{}{} + for i := range list1 { + seenLeft[list1[i]] = struct{}{} } - for _, elem := range list2 { - seenRight[elem] = struct{}{} + for i := range list2 { + seenRight[list2[i]] = struct{}{} } - for _, elem := range list1 { - if _, ok := seenRight[elem]; !ok { - left = append(left, elem) + for i := range list1 { + if _, ok := seenRight[list1[i]]; !ok { + left = append(left, list1[i]) } } - for _, elem := range list2 { - if _, ok := seenLeft[elem]; !ok { - right = append(right, elem) + for i := range list2 { + if _, ok := seenLeft[list2[i]]; !ok { + right = append(right, list2[i]) } } @@ -143,15 +143,21 @@ func Difference[T comparable](list1 []T, list2 []T) ([]T, []T) { // Union returns all distinct elements from given collections. // result returns will not change the order of elements relatively. -func Union[T comparable](lists ...[]T) []T { - result := []T{} - seen := map[T]struct{}{} +func Union[T comparable, Slice ~[]T](lists ...Slice) Slice { + var capLen int for _, list := range lists { - for _, e := range list { - if _, ok := seen[e]; !ok { - seen[e] = struct{}{} - result = append(result, e) + capLen += len(list) + } + + result := make(Slice, 0, capLen) + seen := make(map[T]struct{}, capLen) + + for i := range lists { + for j := range lists[i] { + if _, ok := seen[lists[i][j]]; !ok { + seen[lists[i][j]] = struct{}{} + result = append(result, lists[i][j]) } } } @@ -160,26 +166,19 @@ func Union[T comparable](lists ...[]T) []T { } // Without returns slice excluding all given values. -func Without[T comparable](collection []T, exclude ...T) []T { - result := make([]T, 0, len(collection)) - for _, e := range collection { - if !Contains(exclude, e) { - result = append(result, e) +func Without[T comparable, Slice ~[]T](collection Slice, exclude ...T) Slice { + result := make(Slice, 0, len(collection)) + for i := range collection { + if !Contains(exclude, collection[i]) { + result = append(result, collection[i]) } } return result } // WithoutEmpty returns slice excluding empty values. -func WithoutEmpty[T comparable](collection []T) []T { - var empty T - - result := make([]T, 0, len(collection)) - for _, e := range collection { - if e != empty { - result = append(result, e) - } - } - - return result +// +// Deprecated: Use lo.Compact instead. +func WithoutEmpty[T comparable, Slice ~[]T](collection Slice) Slice { + return Compact(collection) } diff --git a/vendor/github.com/samber/lo/map.go b/vendor/github.com/samber/lo/map.go index 9c0ac4826b..d8feb434ec 100644 --- a/vendor/github.com/samber/lo/map.go +++ b/vendor/github.com/samber/lo/map.go @@ -2,23 +2,91 @@ package lo // Keys creates an array of the map keys. // Play: https://go.dev/play/p/Uu11fHASqrU -func Keys[K comparable, V any](in map[K]V) []K { - result := make([]K, 0, len(in)) +func Keys[K comparable, V any](in ...map[K]V) []K { + size := 0 + for i := range in { + size += len(in[i]) + } + result := make([]K, 0, size) - for k := range in { - result = append(result, k) + for i := range in { + for k := range in[i] { + result = append(result, k) + } } return result } +// UniqKeys creates an array of unique keys in the map. +// Play: https://go.dev/play/p/TPKAb6ILdHk +func UniqKeys[K comparable, V any](in ...map[K]V) []K { + size := 0 + for i := range in { + size += len(in[i]) + } + + seen := make(map[K]struct{}, size) + result := make([]K, 0) + + for i := range in { + for k := range in[i] { + if _, exists := seen[k]; exists { + continue + } + seen[k] = struct{}{} + result = append(result, k) + } + } + + return result +} + +// HasKey returns whether the given key exists. +// Play: https://go.dev/play/p/aVwubIvECqS +func HasKey[K comparable, V any](in map[K]V, key K) bool { + _, ok := in[key] + return ok +} + // Values creates an array of the map values. // Play: https://go.dev/play/p/nnRTQkzQfF6 -func Values[K comparable, V any](in map[K]V) []V { - result := make([]V, 0, len(in)) +func Values[K comparable, V any](in ...map[K]V) []V { + size := 0 + for i := range in { + size += len(in[i]) + } + result := make([]V, 0, size) - for _, v := range in { - result = append(result, v) + for i := range in { + for k := range in[i] { + result = append(result, in[i][k]) + } + } + + return result +} + +// UniqValues creates an array of unique values in the map. +// Play: https://go.dev/play/p/nf6bXMh7rM3 +func UniqValues[K comparable, V comparable](in ...map[K]V) []V { + size := 0 + for i := range in { + size += len(in[i]) + } + + seen := make(map[V]struct{}, size) + result := make([]V, 0) + + for i := range in { + for k := range in[i] { + val := in[i][k] + if _, exists := seen[val]; exists { + continue + } + seen[val] = struct{}{} + result = append(result, val) + } } return result @@ -35,11 +103,11 @@ func ValueOr[K comparable, V any](in map[K]V, key K, fallback V) V { // PickBy returns same map type filtered by given predicate. // Play: https://go.dev/play/p/kdg8GR_QMmf -func PickBy[K comparable, V any](in map[K]V, predicate func(key K, value V) bool) map[K]V { - r := map[K]V{} - for k, v := range in { - if predicate(k, v) { - r[k] = v +func PickBy[K comparable, V any, Map ~map[K]V](in Map, predicate func(key K, value V) bool) Map { + r := Map{} + for k := range in { + if predicate(k, in[k]) { + r[k] = in[k] } } return r @@ -47,11 +115,11 @@ func PickBy[K comparable, V any](in map[K]V, predicate func(key K, value V) bool // PickByKeys returns same map type filtered by given keys. // Play: https://go.dev/play/p/R1imbuci9qU -func PickByKeys[K comparable, V any](in map[K]V, keys []K) map[K]V { - r := map[K]V{} - for k, v := range in { - if Contains(keys, k) { - r[k] = v +func PickByKeys[K comparable, V any, Map ~map[K]V](in Map, keys []K) Map { + r := Map{} + for i := range keys { + if v, ok := in[keys[i]]; ok { + r[keys[i]] = v } } return r @@ -59,11 +127,11 @@ func PickByKeys[K comparable, V any](in map[K]V, keys []K) map[K]V { // PickByValues returns same map type filtered by given values. // Play: https://go.dev/play/p/1zdzSvbfsJc -func PickByValues[K comparable, V comparable](in map[K]V, values []V) map[K]V { - r := map[K]V{} - for k, v := range in { - if Contains(values, v) { - r[k] = v +func PickByValues[K comparable, V comparable, Map ~map[K]V](in Map, values []V) Map { + r := Map{} + for k := range in { + if Contains(values, in[k]) { + r[k] = in[k] } } return r @@ -71,11 +139,11 @@ func PickByValues[K comparable, V comparable](in map[K]V, values []V) map[K]V { // OmitBy returns same map type filtered by given predicate. // Play: https://go.dev/play/p/EtBsR43bdsd -func OmitBy[K comparable, V any](in map[K]V, predicate func(key K, value V) bool) map[K]V { - r := map[K]V{} - for k, v := range in { - if !predicate(k, v) { - r[k] = v +func OmitBy[K comparable, V any, Map ~map[K]V](in Map, predicate func(key K, value V) bool) Map { + r := Map{} + for k := range in { + if !predicate(k, in[k]) { + r[k] = in[k] } } return r @@ -83,23 +151,24 @@ func OmitBy[K comparable, V any](in map[K]V, predicate func(key K, value V) bool // OmitByKeys returns same map type filtered by given keys. // Play: https://go.dev/play/p/t1QjCrs-ysk -func OmitByKeys[K comparable, V any](in map[K]V, keys []K) map[K]V { - r := map[K]V{} - for k, v := range in { - if !Contains(keys, k) { - r[k] = v - } +func OmitByKeys[K comparable, V any, Map ~map[K]V](in Map, keys []K) Map { + r := Map{} + for k := range in { + r[k] = in[k] + } + for i := range keys { + delete(r, keys[i]) } return r } // OmitByValues returns same map type filtered by given values. // Play: https://go.dev/play/p/9UYZi-hrs8j -func OmitByValues[K comparable, V comparable](in map[K]V, values []V) map[K]V { - r := map[K]V{} - for k, v := range in { - if !Contains(values, v) { - r[k] = v +func OmitByValues[K comparable, V comparable, Map ~map[K]V](in Map, values []V) Map { + r := Map{} + for k := range in { + if !Contains(values, in[k]) { + r[k] = in[k] } } return r @@ -110,10 +179,10 @@ func OmitByValues[K comparable, V comparable](in map[K]V, values []V) map[K]V { func Entries[K comparable, V any](in map[K]V) []Entry[K, V] { entries := make([]Entry[K, V], 0, len(in)) - for k, v := range in { + for k := range in { entries = append(entries, Entry[K, V]{ Key: k, - Value: v, + Value: in[k], }) } @@ -132,8 +201,8 @@ func ToPairs[K comparable, V any](in map[K]V) []Entry[K, V] { func FromEntries[K comparable, V any](entries []Entry[K, V]) map[K]V { out := make(map[K]V, len(entries)) - for _, v := range entries { - out[v.Key] = v.Value + for i := range entries { + out[entries[i].Key] = entries[i].Value } return out @@ -153,8 +222,8 @@ func FromPairs[K comparable, V any](entries []Entry[K, V]) map[K]V { func Invert[K comparable, V comparable](in map[K]V) map[V]K { out := make(map[V]K, len(in)) - for k, v := range in { - out[v] = k + for k := range in { + out[in[k]] = k } return out @@ -162,12 +231,16 @@ func Invert[K comparable, V comparable](in map[K]V) map[V]K { // Assign merges multiple maps from left to right. // Play: https://go.dev/play/p/VhwfJOyxf5o -func Assign[K comparable, V any](maps ...map[K]V) map[K]V { - out := map[K]V{} +func Assign[K comparable, V any, Map ~map[K]V](maps ...Map) Map { + count := 0 + for i := range maps { + count += len(maps[i]) + } - for _, m := range maps { - for k, v := range m { - out[k] = v + out := make(Map, count) + for i := range maps { + for k := range maps[i] { + out[k] = maps[i][k] } } @@ -179,8 +252,8 @@ func Assign[K comparable, V any](maps ...map[K]V) map[K]V { func MapKeys[K comparable, V any, R comparable](in map[K]V, iteratee func(value V, key K) R) map[R]V { result := make(map[R]V, len(in)) - for k, v := range in { - result[iteratee(v, k)] = v + for k := range in { + result[iteratee(in[k], k)] = in[k] } return result @@ -191,8 +264,8 @@ func MapKeys[K comparable, V any, R comparable](in map[K]V, iteratee func(value func MapValues[K comparable, V any, R any](in map[K]V, iteratee func(value V, key K) R) map[K]R { result := make(map[K]R, len(in)) - for k, v := range in { - result[k] = iteratee(v, k) + for k := range in { + result[k] = iteratee(in[k], k) } return result @@ -203,8 +276,8 @@ func MapValues[K comparable, V any, R any](in map[K]V, iteratee func(value V, ke func MapEntries[K1 comparable, V1 any, K2 comparable, V2 any](in map[K1]V1, iteratee func(key K1, value V1) (K2, V2)) map[K2]V2 { result := make(map[K2]V2, len(in)) - for k1, v1 := range in { - k2, v2 := iteratee(k1, v1) + for k1 := range in { + k2, v2 := iteratee(k1, in[k1]) result[k2] = v2 } @@ -216,8 +289,8 @@ func MapEntries[K1 comparable, V1 any, K2 comparable, V2 any](in map[K1]V1, iter func MapToSlice[K comparable, V any, R any](in map[K]V, iteratee func(key K, value V) R) []R { result := make([]R, 0, len(in)) - for k, v := range in { - result = append(result, iteratee(k, v)) + for k := range in { + result = append(result, iteratee(k, in[k])) } return result diff --git a/vendor/github.com/samber/lo/math.go b/vendor/github.com/samber/lo/math.go index 9dce28cf83..e866f88e04 100644 --- a/vendor/github.com/samber/lo/math.go +++ b/vendor/github.com/samber/lo/math.go @@ -1,6 +1,8 @@ package lo -import "golang.org/x/exp/constraints" +import ( + "github.com/samber/lo/internal/constraints" +) // Range creates an array of numbers (positive and/or negative) with given length. // Play: https://go.dev/play/p/0r6VimXAi9H @@ -67,8 +69,8 @@ func Clamp[T constraints.Ordered](value T, min T, max T) T { // Play: https://go.dev/play/p/upfeJVqs4Bt func Sum[T constraints.Float | constraints.Integer | constraints.Complex](collection []T) T { var sum T = 0 - for _, val := range collection { - sum += val + for i := range collection { + sum += collection[i] } return sum } @@ -77,8 +79,28 @@ func Sum[T constraints.Float | constraints.Integer | constraints.Complex](collec // Play: https://go.dev/play/p/Dz_a_7jN_ca func SumBy[T any, R constraints.Float | constraints.Integer | constraints.Complex](collection []T, iteratee func(item T) R) R { var sum R = 0 - for _, item := range collection { - sum = sum + iteratee(item) + for i := range collection { + sum = sum + iteratee(collection[i]) } return sum } + +// Mean calculates the mean of a collection of numbers. +func Mean[T constraints.Float | constraints.Integer](collection []T) T { + var length T = T(len(collection)) + if length == 0 { + return 0 + } + var sum T = Sum(collection) + return sum / length +} + +// MeanBy calculates the mean of a collection of numbers using the given return value from the iteration function. +func MeanBy[T any, R constraints.Float | constraints.Integer](collection []T, iteratee func(item T) R) R { + var length R = R(len(collection)) + if length == 0 { + return 0 + } + var sum R = SumBy(collection, iteratee) + return sum / length +} diff --git a/vendor/github.com/samber/lo/retry.go b/vendor/github.com/samber/lo/retry.go index c3c264fff9..f026aa3319 100644 --- a/vendor/github.com/samber/lo/retry.go +++ b/vendor/github.com/samber/lo/retry.go @@ -26,8 +26,8 @@ func (d *debounce) reset() { } d.timer = time.AfterFunc(d.after, func() { - for _, f := range d.callbacks { - f() + for i := range d.callbacks { + d.callbacks[i]() } }) } @@ -101,8 +101,8 @@ func (d *debounceBy[T]) reset(key T) { item.count = 0 item.mu.Unlock() - for _, f := range d.callbacks { - f(key, count) + for i := range d.callbacks { + d.callbacks[i](key, count) } }) @@ -239,7 +239,7 @@ type transactionStep[T any] struct { onRollback func(T) T } -// NewTransaction instanciate a new transaction. +// NewTransaction instantiate a new transaction. func NewTransaction[T any]() *Transaction[T] { return &Transaction[T]{ steps: []transactionStep[T]{}, diff --git a/vendor/github.com/samber/lo/slice.go b/vendor/github.com/samber/lo/slice.go index 49c991f894..d2d3fd84ae 100644 --- a/vendor/github.com/samber/lo/slice.go +++ b/vendor/github.com/samber/lo/slice.go @@ -1,19 +1,20 @@ package lo import ( - "math/rand" + "sort" - "golang.org/x/exp/constraints" + "github.com/samber/lo/internal/constraints" + "github.com/samber/lo/internal/rand" ) // Filter iterates over elements of collection, returning an array of all elements predicate returns truthy for. // Play: https://go.dev/play/p/Apjg3WeSi7K -func Filter[V any](collection []V, predicate func(item V, index int) bool) []V { - result := make([]V, 0, len(collection)) +func Filter[T any, Slice ~[]T](collection Slice, predicate func(item T, index int) bool) Slice { + result := make(Slice, 0, len(collection)) - for i, item := range collection { - if predicate(item, i) { - result = append(result, item) + for i := range collection { + if predicate(collection[i], i) { + result = append(result, collection[i]) } } @@ -25,8 +26,8 @@ func Filter[V any](collection []V, predicate func(item V, index int) bool) []V { func Map[T any, R any](collection []T, iteratee func(item T, index int) R) []R { result := make([]R, len(collection)) - for i, item := range collection { - result[i] = iteratee(item, i) + for i := range collection { + result[i] = iteratee(collection[i], i) } return result @@ -41,8 +42,8 @@ func Map[T any, R any](collection []T, iteratee func(item T, index int) R) []R { func FilterMap[T any, R any](collection []T, callback func(item T, index int) (R, bool)) []R { result := []R{} - for i, item := range collection { - if r, ok := callback(item, i); ok { + for i := range collection { + if r, ok := callback(collection[i], i); ok { result = append(result, r) } } @@ -57,8 +58,8 @@ func FilterMap[T any, R any](collection []T, callback func(item T, index int) (R func FlatMap[T any, R any](collection []T, iteratee func(item T, index int) []R) []R { result := make([]R, 0, len(collection)) - for i, item := range collection { - result = append(result, iteratee(item, i)...) + for i := range collection { + result = append(result, iteratee(collection[i], i)...) } return result @@ -68,8 +69,8 @@ func FlatMap[T any, R any](collection []T, iteratee func(item T, index int) []R) // through accumulator, where each successive invocation is supplied the return value of the previous. // Play: https://go.dev/play/p/R4UHXZNaaUG func Reduce[T any, R any](collection []T, accumulator func(agg R, item T, index int) R, initial R) R { - for i, item := range collection { - initial = accumulator(initial, item, i) + for i := range collection { + initial = accumulator(initial, collection[i], i) } return initial @@ -88,8 +89,19 @@ func ReduceRight[T any, R any](collection []T, accumulator func(agg R, item T, i // ForEach iterates over elements of collection and invokes iteratee for each element. // Play: https://go.dev/play/p/oofyiUPRf8t func ForEach[T any](collection []T, iteratee func(item T, index int)) { - for i, item := range collection { - iteratee(item, i) + for i := range collection { + iteratee(collection[i], i) + } +} + +// ForEachWhile iterates over elements of collection and invokes iteratee for each element +// collection return value decide to continue or break, like do while(). +// Play: https://go.dev/play/p/QnLGt35tnow +func ForEachWhile[T any](collection []T, iteratee func(item T, index int) (goon bool)) { + for i := range collection { + if !iteratee(collection[i], i) { + break + } } } @@ -109,17 +121,17 @@ func Times[T any](count int, iteratee func(index int) T) []T { // Uniq returns a duplicate-free version of an array, in which only the first occurrence of each element is kept. // The order of result values is determined by the order they occur in the array. // Play: https://go.dev/play/p/DTzbeXZ6iEN -func Uniq[T comparable](collection []T) []T { - result := make([]T, 0, len(collection)) +func Uniq[T comparable, Slice ~[]T](collection Slice) Slice { + result := make(Slice, 0, len(collection)) seen := make(map[T]struct{}, len(collection)) - for _, item := range collection { - if _, ok := seen[item]; ok { + for i := range collection { + if _, ok := seen[collection[i]]; ok { continue } - seen[item] = struct{}{} - result = append(result, item) + seen[collection[i]] = struct{}{} + result = append(result, collection[i]) } return result @@ -129,19 +141,19 @@ func Uniq[T comparable](collection []T) []T { // The order of result values is determined by the order they occur in the array. It accepts `iteratee` which is // invoked for each element in array to generate the criterion by which uniqueness is computed. // Play: https://go.dev/play/p/g42Z3QSb53u -func UniqBy[T any, U comparable](collection []T, iteratee func(item T) U) []T { - result := make([]T, 0, len(collection)) +func UniqBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) Slice { + result := make(Slice, 0, len(collection)) seen := make(map[U]struct{}, len(collection)) - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) if _, ok := seen[key]; ok { continue } seen[key] = struct{}{} - result = append(result, item) + result = append(result, collection[i]) } return result @@ -149,13 +161,13 @@ func UniqBy[T any, U comparable](collection []T, iteratee func(item T) U) []T { // GroupBy returns an object composed of keys generated from the results of running each element of collection through iteratee. // Play: https://go.dev/play/p/XnQBd_v6brd -func GroupBy[T any, U comparable](collection []T, iteratee func(item T) U) map[U][]T { - result := map[U][]T{} +func GroupBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) map[U]Slice { + result := map[U]Slice{} - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) - result[key] = append(result[key], item) + result[key] = append(result[key], collection[i]) } return result @@ -164,7 +176,7 @@ func GroupBy[T any, U comparable](collection []T, iteratee func(item T) U) map[U // Chunk returns an array of elements split into groups the length of size. If array can't be split evenly, // the final chunk will be the remaining elements. // Play: https://go.dev/play/p/EeKl0AuTehH -func Chunk[T any](collection []T, size int) [][]T { +func Chunk[T any, Slice ~[]T](collection Slice, size int) []Slice { if size <= 0 { panic("Second parameter must be greater than 0") } @@ -174,14 +186,14 @@ func Chunk[T any](collection []T, size int) [][]T { chunksNum += 1 } - result := make([][]T, 0, chunksNum) + result := make([]Slice, 0, chunksNum) for i := 0; i < chunksNum; i++ { last := (i + 1) * size if last > len(collection) { last = len(collection) } - result = append(result, collection[i*size:last]) + result = append(result, collection[i*size:last:last]) } return result @@ -191,21 +203,21 @@ func Chunk[T any](collection []T, size int) [][]T { // determined by the order they occur in collection. The grouping is generated from the results // of running each element of collection through iteratee. // Play: https://go.dev/play/p/NfQ_nGjkgXW -func PartitionBy[T any, K comparable](collection []T, iteratee func(item T) K) [][]T { - result := [][]T{} +func PartitionBy[T any, K comparable, Slice ~[]T](collection Slice, iteratee func(item T) K) []Slice { + result := []Slice{} seen := map[K]int{} - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) resultIndex, ok := seen[key] if !ok { resultIndex = len(result) seen[key] = resultIndex - result = append(result, []T{}) + result = append(result, Slice{}) } - result[resultIndex] = append(result[resultIndex], item) + result[resultIndex] = append(result[resultIndex], collection[i]) } return result @@ -217,13 +229,13 @@ func PartitionBy[T any, K comparable](collection []T, iteratee func(item T) K) [ // Flatten returns an array a single level deep. // Play: https://go.dev/play/p/rbp9ORaMpjw -func Flatten[T any](collection [][]T) []T { +func Flatten[T any, Slice ~[]T](collection []Slice) Slice { totalLen := 0 for i := range collection { totalLen += len(collection[i]) } - result := make([]T, 0, totalLen) + result := make(Slice, 0, totalLen) for i := range collection { result = append(result, collection[i]...) } @@ -232,16 +244,16 @@ func Flatten[T any](collection [][]T) []T { } // Interleave round-robin alternating input slices and sequentially appending value at index into result -// Play: https://go.dev/play/p/DDhlwrShbwe -func Interleave[T any](collections ...[]T) []T { +// Play: https://go.dev/play/p/-RJkTLQEDVt +func Interleave[T any, Slice ~[]T](collections ...Slice) Slice { if len(collections) == 0 { - return []T{} + return Slice{} } maxSize := 0 totalSize := 0 - for _, c := range collections { - size := len(c) + for i := range collections { + size := len(collections[i]) totalSize += size if size > maxSize { maxSize = size @@ -249,10 +261,10 @@ func Interleave[T any](collections ...[]T) []T { } if maxSize == 0 { - return []T{} + return Slice{} } - result := make([]T, totalSize) + result := make(Slice, totalSize) resultIdx := 0 for i := 0; i < maxSize; i++ { @@ -271,7 +283,7 @@ func Interleave[T any](collections ...[]T) []T { // Shuffle returns an array of shuffled values. Uses the Fisher-Yates shuffle algorithm. // Play: https://go.dev/play/p/Qp73bnTDnc7 -func Shuffle[T any](collection []T) []T { +func Shuffle[T any, Slice ~[]T](collection Slice) Slice { rand.Shuffle(len(collection), func(i, j int) { collection[i], collection[j] = collection[j], collection[i] }) @@ -281,7 +293,7 @@ func Shuffle[T any](collection []T) []T { // Reverse reverses array so that the first element becomes the last, the second element becomes the second to last, and so on. // Play: https://go.dev/play/p/fhUMLvZ7vS6 -func Reverse[T any](collection []T) []T { +func Reverse[T any, Slice ~[]T](collection Slice) Slice { length := len(collection) half := length / 2 @@ -334,9 +346,9 @@ func RepeatBy[T any](count int, predicate func(index int) T) []T { func KeyBy[K comparable, V any](collection []V, iteratee func(item V) K) map[K]V { result := make(map[K]V, len(collection)) - for _, v := range collection { - k := iteratee(v) - result[k] = v + for i := range collection { + k := iteratee(collection[i]) + result[k] = collection[i] } return result @@ -349,8 +361,8 @@ func KeyBy[K comparable, V any](collection []V, iteratee func(item V) K) map[K]V func Associate[T any, K comparable, V any](collection []T, transform func(item T) (K, V)) map[K]V { result := make(map[K]V, len(collection)) - for _, t := range collection { - k, v := transform(t) + for i := range collection { + k, v := transform(collection[i]) result[k] = v } @@ -368,30 +380,30 @@ func SliceToMap[T any, K comparable, V any](collection []T, transform func(item // Drop drops n elements from the beginning of a slice or array. // Play: https://go.dev/play/p/JswS7vXRJP2 -func Drop[T any](collection []T, n int) []T { +func Drop[T any, Slice ~[]T](collection Slice, n int) Slice { if len(collection) <= n { - return make([]T, 0) + return make(Slice, 0) } - result := make([]T, 0, len(collection)-n) + result := make(Slice, 0, len(collection)-n) return append(result, collection[n:]...) } // DropRight drops n elements from the end of a slice or array. // Play: https://go.dev/play/p/GG0nXkSJJa3 -func DropRight[T any](collection []T, n int) []T { +func DropRight[T any, Slice ~[]T](collection Slice, n int) Slice { if len(collection) <= n { - return []T{} + return Slice{} } - result := make([]T, 0, len(collection)-n) + result := make(Slice, 0, len(collection)-n) return append(result, collection[:len(collection)-n]...) } // DropWhile drops elements from the beginning of a slice or array while the predicate returns true. // Play: https://go.dev/play/p/7gBPYw2IK16 -func DropWhile[T any](collection []T, predicate func(item T) bool) []T { +func DropWhile[T any, Slice ~[]T](collection Slice, predicate func(item T) bool) Slice { i := 0 for ; i < len(collection); i++ { if !predicate(collection[i]) { @@ -399,13 +411,13 @@ func DropWhile[T any](collection []T, predicate func(item T) bool) []T { } } - result := make([]T, 0, len(collection)-i) + result := make(Slice, 0, len(collection)-i) return append(result, collection[i:]...) } // DropRightWhile drops elements from the end of a slice or array while the predicate returns true. // Play: https://go.dev/play/p/3-n71oEC0Hz -func DropRightWhile[T any](collection []T, predicate func(item T) bool) []T { +func DropRightWhile[T any, Slice ~[]T](collection Slice, predicate func(item T) bool) Slice { i := len(collection) - 1 for ; i >= 0; i-- { if !predicate(collection[i]) { @@ -413,29 +425,94 @@ func DropRightWhile[T any](collection []T, predicate func(item T) bool) []T { } } - result := make([]T, 0, i+1) + result := make(Slice, 0, i+1) return append(result, collection[:i+1]...) } +// DropByIndex drops elements from a slice or array by the index. +// A negative index will drop elements from the end of the slice. +// Play: https://go.dev/play/p/bPIH4npZRxS +func DropByIndex[T any](collection []T, indexes ...int) []T { + initialSize := len(collection) + if initialSize == 0 { + return make([]T, 0) + } + + for i := range indexes { + if indexes[i] < 0 { + indexes[i] = initialSize + indexes[i] + } + } + + indexes = Uniq(indexes) + sort.Ints(indexes) + + result := make([]T, 0, initialSize) + result = append(result, collection...) + + for i := range indexes { + if indexes[i]-i < 0 || indexes[i]-i >= initialSize-i { + continue + } + + result = append(result[:indexes[i]-i], result[indexes[i]-i+1:]...) + } + + return result +} + // Reject is the opposite of Filter, this method returns the elements of collection that predicate does not return truthy for. // Play: https://go.dev/play/p/YkLMODy1WEL -func Reject[V any](collection []V, predicate func(item V, index int) bool) []V { - result := []V{} +func Reject[T any, Slice ~[]T](collection Slice, predicate func(item T, index int) bool) Slice { + result := Slice{} + + for i := range collection { + if !predicate(collection[i], i) { + result = append(result, collection[i]) + } + } + + return result +} + +// RejectMap is the opposite of FilterMap, this method returns a slice which obtained after both filtering and mapping using the given callback function. +// The callback function should return two values: +// - the result of the mapping operation and +// - whether the result element should be included or not. +func RejectMap[T any, R any](collection []T, callback func(item T, index int) (R, bool)) []R { + result := []R{} - for i, item := range collection { - if !predicate(item, i) { - result = append(result, item) + for i := range collection { + if r, ok := callback(collection[i], i); !ok { + result = append(result, r) } } return result } +// FilterReject mixes Filter and Reject, this method returns two slices, one for the elements of collection that +// predicate returns truthy for and one for the elements that predicate does not return truthy for. +func FilterReject[T any, Slice ~[]T](collection Slice, predicate func(T, int) bool) (kept Slice, rejected Slice) { + kept = make(Slice, 0, len(collection)) + rejected = make(Slice, 0, len(collection)) + + for i := range collection { + if predicate(collection[i], i) { + kept = append(kept, collection[i]) + } else { + rejected = append(rejected, collection[i]) + } + } + + return kept, rejected +} + // Count counts the number of elements in the collection that compare equal to value. // Play: https://go.dev/play/p/Y3FlK54yveC func Count[T comparable](collection []T, value T) (count int) { - for _, item := range collection { - if item == value { + for i := range collection { + if collection[i] == value { count++ } } @@ -446,8 +523,8 @@ func Count[T comparable](collection []T, value T) (count int) { // CountBy counts the number of elements in the collection for which predicate is true. // Play: https://go.dev/play/p/ByQbNYQQi4X func CountBy[T any](collection []T, predicate func(item T) bool) (count int) { - for _, item := range collection { - if predicate(item) { + for i := range collection { + if predicate(collection[i]) { count++ } } @@ -460,8 +537,8 @@ func CountBy[T any](collection []T, predicate func(item T) bool) (count int) { func CountValues[T comparable](collection []T) map[T]int { result := make(map[T]int) - for _, item := range collection { - result[item]++ + for i := range collection { + result[collection[i]]++ } return result @@ -473,8 +550,8 @@ func CountValues[T comparable](collection []T) map[T]int { func CountValuesBy[T any, U comparable](collection []T, mapper func(item T) U) map[U]int { result := make(map[U]int) - for _, item := range collection { - result[mapper(item)]++ + for i := range collection { + result[mapper(collection[i])]++ } return result @@ -482,7 +559,7 @@ func CountValuesBy[T any, U comparable](collection []T, mapper func(item T) U) m // Subset returns a copy of a slice from `offset` up to `length` elements. Like `slice[start:start+length]`, but does not panic on overflow. // Play: https://go.dev/play/p/tOQu1GhFcog -func Subset[T any](collection []T, offset int, length uint) []T { +func Subset[T any, Slice ~[]T](collection Slice, offset int, length uint) Slice { size := len(collection) if offset < 0 { @@ -493,7 +570,7 @@ func Subset[T any](collection []T, offset int, length uint) []T { } if offset > size { - return []T{} + return Slice{} } if length > uint(size)-uint(offset) { @@ -505,11 +582,11 @@ func Subset[T any](collection []T, offset int, length uint) []T { // Slice returns a copy of a slice from `start` up to, but not including `end`. Like `slice[start:end]`, but does not panic on overflow. // Play: https://go.dev/play/p/8XWYhfMMA1h -func Slice[T any](collection []T, start int, end int) []T { +func Slice[T any, Slice ~[]T](collection Slice, start int, end int) Slice { size := len(collection) if start >= end { - return []T{} + return Slice{} } if start > size { @@ -531,8 +608,8 @@ func Slice[T any](collection []T, start int, end int) []T { // Replace returns a copy of the slice with the first n non-overlapping instances of old replaced by new. // Play: https://go.dev/play/p/XfPzmf9gql6 -func Replace[T comparable](collection []T, old T, new T, n int) []T { - result := make([]T, len(collection)) +func Replace[T comparable, Slice ~[]T](collection Slice, old T, new T, n int) Slice { + result := make(Slice, len(collection)) copy(result, collection) for i := range result { @@ -547,20 +624,20 @@ func Replace[T comparable](collection []T, old T, new T, n int) []T { // ReplaceAll returns a copy of the slice with all non-overlapping instances of old replaced by new. // Play: https://go.dev/play/p/a9xZFUHfYcV -func ReplaceAll[T comparable](collection []T, old T, new T) []T { +func ReplaceAll[T comparable, Slice ~[]T](collection Slice, old T, new T) Slice { return Replace(collection, old, new, -1) } // Compact returns a slice of all non-zero elements. // Play: https://go.dev/play/p/tXiy-iK6PAc -func Compact[T comparable](collection []T) []T { +func Compact[T comparable, Slice ~[]T](collection Slice) Slice { var zero T - result := make([]T, 0, len(collection)) + result := make(Slice, 0, len(collection)) - for _, item := range collection { - if item != zero { - result = append(result, item) + for i := range collection { + if collection[i] != zero { + result = append(result, collection[i]) } } @@ -592,3 +669,27 @@ func IsSortedByKey[T any, K constraints.Ordered](collection []T, iteratee func(i return true } + +// Splice inserts multiple elements at index i. A negative index counts back +// from the end of the slice. The helper is protected against overflow errors. +// Play: https://go.dev/play/p/G5_GhkeSUBA +func Splice[T any, Slice ~[]T](collection Slice, i int, elements ...T) Slice { + sizeCollection := len(collection) + sizeElements := len(elements) + output := make(Slice, 0, sizeCollection+sizeElements) // preallocate memory for the output slice + + if sizeElements == 0 { + return append(output, collection...) // simple copy + } else if i > sizeCollection { + // positive overflow + return append(append(output, collection...), elements...) + } else if i < -sizeCollection { + // negative overflow + return append(append(output, elements...), collection...) + } else if i < 0 { + // backward + i = sizeCollection + i + } + + return append(append(append(output, collection[:i]...), elements...), collection[i:]...) +} diff --git a/vendor/github.com/samber/lo/string.go b/vendor/github.com/samber/lo/string.go index a7a959a395..1d808788cc 100644 --- a/vendor/github.com/samber/lo/string.go +++ b/vendor/github.com/samber/lo/string.go @@ -1,9 +1,15 @@ package lo import ( - "math/rand" + "regexp" "strings" + "unicode" "unicode/utf8" + + "github.com/samber/lo/internal/rand" + + "golang.org/x/text/cases" + "golang.org/x/text/language" ) var ( @@ -14,6 +20,11 @@ var ( AlphanumericCharset = append(LettersCharset, NumbersCharset...) SpecialCharset = []rune("!@#$%^&*()_+-=[]{}|;':\",./<>?") AllCharset = append(AlphanumericCharset, SpecialCharset...) + + // bearer:disable go_lang_permissive_regex_validation + splitWordReg = regexp.MustCompile(`([a-z])([A-Z0-9])|([a-zA-Z])([0-9])|([0-9])([a-zA-Z])|([A-Z])([A-Z])([a-z])`) + // bearer:disable go_lang_permissive_regex_validation + splitNumberLetterReg = regexp.MustCompile(`([0-9])([a-zA-Z])`) ) // RandomString return a random string. @@ -29,7 +40,7 @@ func RandomString(size int, charset []rune) string { b := make([]rune, size) possibleCharactersCount := len(charset) for i := range b { - b[i] = charset[rand.Intn(possibleCharactersCount)] + b[i] = charset[rand.IntN(possibleCharactersCount)] } return string(b) } @@ -47,7 +58,7 @@ func Substring[T ~string](str T, offset int, length uint) T { } } - if offset > size { + if offset >= size { return Empty[T]() } @@ -94,3 +105,76 @@ func ChunkString[T ~string](str T, size int) []T { func RuneLength(str string) int { return utf8.RuneCountInString(str) } + +// PascalCase converts string to pascal case. +func PascalCase(str string) string { + items := Words(str) + for i := range items { + items[i] = Capitalize(items[i]) + } + return strings.Join(items, "") +} + +// CamelCase converts string to camel case. +func CamelCase(str string) string { + items := Words(str) + for i, item := range items { + item = strings.ToLower(item) + if i > 0 { + item = Capitalize(item) + } + items[i] = item + } + return strings.Join(items, "") +} + +// KebabCase converts string to kebab case. +func KebabCase(str string) string { + items := Words(str) + for i := range items { + items[i] = strings.ToLower(items[i]) + } + return strings.Join(items, "-") +} + +// SnakeCase converts string to snake case. +func SnakeCase(str string) string { + items := Words(str) + for i := range items { + items[i] = strings.ToLower(items[i]) + } + return strings.Join(items, "_") +} + +// Words splits string into an array of its words. +func Words(str string) []string { + str = splitWordReg.ReplaceAllString(str, `$1$3$5$7 $2$4$6$8$9`) + // example: Int8Value => Int 8Value => Int 8 Value + str = splitNumberLetterReg.ReplaceAllString(str, "$1 $2") + var result strings.Builder + for _, r := range str { + if unicode.IsLetter(r) || unicode.IsDigit(r) { + result.WriteRune(r) + } else { + result.WriteRune(' ') + } + } + return strings.Fields(result.String()) +} + +// Capitalize converts the first character of string to upper case and the remaining to lower case. +func Capitalize(str string) string { + return cases.Title(language.English).String(str) +} + +// Elipse truncates a string to a specified length and appends an ellipsis if truncated. +func Elipse(str string, length int) string { + if len(str) > length { + if len(str) < 3 || length < 3 { + return "..." + } + return str[0:length-3] + "..." + } + + return str +} diff --git a/vendor/github.com/samber/lo/time.go b/vendor/github.com/samber/lo/time.go new file mode 100644 index 0000000000..e98e80f9e8 --- /dev/null +++ b/vendor/github.com/samber/lo/time.go @@ -0,0 +1,85 @@ +package lo + +import "time" + +// Duration returns the time taken to execute a function. +func Duration(cb func()) time.Duration { + return Duration0(cb) +} + +// Duration0 returns the time taken to execute a function. +func Duration0(cb func()) time.Duration { + start := time.Now() + cb() + return time.Since(start) +} + +// Duration1 returns the time taken to execute a function. +func Duration1[A any](cb func() A) (A, time.Duration) { + start := time.Now() + a := cb() + return a, time.Since(start) +} + +// Duration2 returns the time taken to execute a function. +func Duration2[A, B any](cb func() (A, B)) (A, B, time.Duration) { + start := time.Now() + a, b := cb() + return a, b, time.Since(start) +} + +// Duration3 returns the time taken to execute a function. +func Duration3[A, B, C any](cb func() (A, B, C)) (A, B, C, time.Duration) { + start := time.Now() + a, b, c := cb() + return a, b, c, time.Since(start) +} + +// Duration4 returns the time taken to execute a function. +func Duration4[A, B, C, D any](cb func() (A, B, C, D)) (A, B, C, D, time.Duration) { + start := time.Now() + a, b, c, d := cb() + return a, b, c, d, time.Since(start) +} + +// Duration5 returns the time taken to execute a function. +func Duration5[A, B, C, D, E any](cb func() (A, B, C, D, E)) (A, B, C, D, E, time.Duration) { + start := time.Now() + a, b, c, d, e := cb() + return a, b, c, d, e, time.Since(start) +} + +// Duration6 returns the time taken to execute a function. +func Duration6[A, B, C, D, E, F any](cb func() (A, B, C, D, E, F)) (A, B, C, D, E, F, time.Duration) { + start := time.Now() + a, b, c, d, e, f := cb() + return a, b, c, d, e, f, time.Since(start) +} + +// Duration7 returns the time taken to execute a function. +func Duration7[A, B, C, D, E, F, G any](cb func() (A, B, C, D, E, F, G)) (A, B, C, D, E, F, G, time.Duration) { + start := time.Now() + a, b, c, d, e, f, g := cb() + return a, b, c, d, e, f, g, time.Since(start) +} + +// Duration8 returns the time taken to execute a function. +func Duration8[A, B, C, D, E, F, G, H any](cb func() (A, B, C, D, E, F, G, H)) (A, B, C, D, E, F, G, H, time.Duration) { + start := time.Now() + a, b, c, d, e, f, g, h := cb() + return a, b, c, d, e, f, g, h, time.Since(start) +} + +// Duration9 returns the time taken to execute a function. +func Duration9[A, B, C, D, E, F, G, H, I any](cb func() (A, B, C, D, E, F, G, H, I)) (A, B, C, D, E, F, G, H, I, time.Duration) { + start := time.Now() + a, b, c, d, e, f, g, h, i := cb() + return a, b, c, d, e, f, g, h, i, time.Since(start) +} + +// Duration10 returns the time taken to execute a function. +func Duration10[A, B, C, D, E, F, G, H, I, J any](cb func() (A, B, C, D, E, F, G, H, I, J)) (A, B, C, D, E, F, G, H, I, J, time.Duration) { + start := time.Now() + a, b, c, d, e, f, g, h, i, j := cb() + return a, b, c, d, e, f, g, h, i, j, time.Since(start) +} diff --git a/vendor/github.com/samber/lo/tuples.go b/vendor/github.com/samber/lo/tuples.go index cdddf6afc1..18a03009dc 100644 --- a/vendor/github.com/samber/lo/tuples.go +++ b/vendor/github.com/samber/lo/tuples.go @@ -2,97 +2,97 @@ package lo // T2 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T2[A any, B any](a A, b B) Tuple2[A, B] { +func T2[A, B any](a A, b B) Tuple2[A, B] { return Tuple2[A, B]{A: a, B: b} } // T3 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T3[A any, B any, C any](a A, b B, c C) Tuple3[A, B, C] { +func T3[A, B, C any](a A, b B, c C) Tuple3[A, B, C] { return Tuple3[A, B, C]{A: a, B: b, C: c} } // T4 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T4[A any, B any, C any, D any](a A, b B, c C, d D) Tuple4[A, B, C, D] { +func T4[A, B, C, D any](a A, b B, c C, d D) Tuple4[A, B, C, D] { return Tuple4[A, B, C, D]{A: a, B: b, C: c, D: d} } // T5 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T5[A any, B any, C any, D any, E any](a A, b B, c C, d D, e E) Tuple5[A, B, C, D, E] { +func T5[A, B, C, D, E any](a A, b B, c C, d D, e E) Tuple5[A, B, C, D, E] { return Tuple5[A, B, C, D, E]{A: a, B: b, C: c, D: d, E: e} } // T6 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T6[A any, B any, C any, D any, E any, F any](a A, b B, c C, d D, e E, f F) Tuple6[A, B, C, D, E, F] { +func T6[A, B, C, D, E, F any](a A, b B, c C, d D, e E, f F) Tuple6[A, B, C, D, E, F] { return Tuple6[A, B, C, D, E, F]{A: a, B: b, C: c, D: d, E: e, F: f} } // T7 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T7[A any, B any, C any, D any, E any, F any, G any](a A, b B, c C, d D, e E, f F, g G) Tuple7[A, B, C, D, E, F, G] { +func T7[A, B, C, D, E, F, G any](a A, b B, c C, d D, e E, f F, g G) Tuple7[A, B, C, D, E, F, G] { return Tuple7[A, B, C, D, E, F, G]{A: a, B: b, C: c, D: d, E: e, F: f, G: g} } // T8 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T8[A any, B any, C any, D any, E any, F any, G any, H any](a A, b B, c C, d D, e E, f F, g G, h H) Tuple8[A, B, C, D, E, F, G, H] { +func T8[A, B, C, D, E, F, G, H any](a A, b B, c C, d D, e E, f F, g G, h H) Tuple8[A, B, C, D, E, F, G, H] { return Tuple8[A, B, C, D, E, F, G, H]{A: a, B: b, C: c, D: d, E: e, F: f, G: g, H: h} } // T9 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T9[A any, B any, C any, D any, E any, F any, G any, H any, I any](a A, b B, c C, d D, e E, f F, g G, h H, i I) Tuple9[A, B, C, D, E, F, G, H, I] { +func T9[A, B, C, D, E, F, G, H, I any](a A, b B, c C, d D, e E, f F, g G, h H, i I) Tuple9[A, B, C, D, E, F, G, H, I] { return Tuple9[A, B, C, D, E, F, G, H, I]{A: a, B: b, C: c, D: d, E: e, F: f, G: g, H: h, I: i} } // Unpack2 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack2[A any, B any](tuple Tuple2[A, B]) (A, B) { +func Unpack2[A, B any](tuple Tuple2[A, B]) (A, B) { return tuple.A, tuple.B } // Unpack3 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack3[A any, B any, C any](tuple Tuple3[A, B, C]) (A, B, C) { +func Unpack3[A, B, C any](tuple Tuple3[A, B, C]) (A, B, C) { return tuple.A, tuple.B, tuple.C } // Unpack4 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack4[A any, B any, C any, D any](tuple Tuple4[A, B, C, D]) (A, B, C, D) { +func Unpack4[A, B, C, D any](tuple Tuple4[A, B, C, D]) (A, B, C, D) { return tuple.A, tuple.B, tuple.C, tuple.D } // Unpack5 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack5[A any, B any, C any, D any, E any](tuple Tuple5[A, B, C, D, E]) (A, B, C, D, E) { +func Unpack5[A, B, C, D, E any](tuple Tuple5[A, B, C, D, E]) (A, B, C, D, E) { return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E } // Unpack6 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack6[A any, B any, C any, D any, E any, F any](tuple Tuple6[A, B, C, D, E, F]) (A, B, C, D, E, F) { +func Unpack6[A, B, C, D, E, F any](tuple Tuple6[A, B, C, D, E, F]) (A, B, C, D, E, F) { return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E, tuple.F } // Unpack7 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack7[A any, B any, C any, D any, E any, F any, G any](tuple Tuple7[A, B, C, D, E, F, G]) (A, B, C, D, E, F, G) { +func Unpack7[A, B, C, D, E, F, G any](tuple Tuple7[A, B, C, D, E, F, G]) (A, B, C, D, E, F, G) { return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E, tuple.F, tuple.G } // Unpack8 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack8[A any, B any, C any, D any, E any, F any, G any, H any](tuple Tuple8[A, B, C, D, E, F, G, H]) (A, B, C, D, E, F, G, H) { +func Unpack8[A, B, C, D, E, F, G, H any](tuple Tuple8[A, B, C, D, E, F, G, H]) (A, B, C, D, E, F, G, H) { return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E, tuple.F, tuple.G, tuple.H } // Unpack9 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack9[A any, B any, C any, D any, E any, F any, G any, H any, I any](tuple Tuple9[A, B, C, D, E, F, G, H, I]) (A, B, C, D, E, F, G, H, I) { +func Unpack9[A, B, C, D, E, F, G, H, I any](tuple Tuple9[A, B, C, D, E, F, G, H, I]) (A, B, C, D, E, F, G, H, I) { return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E, tuple.F, tuple.G, tuple.H, tuple.I } @@ -100,7 +100,7 @@ func Unpack9[A any, B any, C any, D any, E any, F any, G any, H any, I any](tupl // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip2[A any, B any](a []A, b []B) []Tuple2[A, B] { +func Zip2[A, B any](a []A, b []B) []Tuple2[A, B] { size := Max([]int{len(a), len(b)}) result := make([]Tuple2[A, B], 0, size) @@ -122,7 +122,7 @@ func Zip2[A any, B any](a []A, b []B) []Tuple2[A, B] { // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip3[A any, B any, C any](a []A, b []B, c []C) []Tuple3[A, B, C] { +func Zip3[A, B, C any](a []A, b []B, c []C) []Tuple3[A, B, C] { size := Max([]int{len(a), len(b), len(c)}) result := make([]Tuple3[A, B, C], 0, size) @@ -146,7 +146,7 @@ func Zip3[A any, B any, C any](a []A, b []B, c []C) []Tuple3[A, B, C] { // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip4[A any, B any, C any, D any](a []A, b []B, c []C, d []D) []Tuple4[A, B, C, D] { +func Zip4[A, B, C, D any](a []A, b []B, c []C, d []D) []Tuple4[A, B, C, D] { size := Max([]int{len(a), len(b), len(c), len(d)}) result := make([]Tuple4[A, B, C, D], 0, size) @@ -172,7 +172,7 @@ func Zip4[A any, B any, C any, D any](a []A, b []B, c []C, d []D) []Tuple4[A, B, // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip5[A any, B any, C any, D any, E any](a []A, b []B, c []C, d []D, e []E) []Tuple5[A, B, C, D, E] { +func Zip5[A, B, C, D, E any](a []A, b []B, c []C, d []D, e []E) []Tuple5[A, B, C, D, E] { size := Max([]int{len(a), len(b), len(c), len(d), len(e)}) result := make([]Tuple5[A, B, C, D, E], 0, size) @@ -200,7 +200,7 @@ func Zip5[A any, B any, C any, D any, E any](a []A, b []B, c []C, d []D, e []E) // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip6[A any, B any, C any, D any, E any, F any](a []A, b []B, c []C, d []D, e []E, f []F) []Tuple6[A, B, C, D, E, F] { +func Zip6[A, B, C, D, E, F any](a []A, b []B, c []C, d []D, e []E, f []F) []Tuple6[A, B, C, D, E, F] { size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f)}) result := make([]Tuple6[A, B, C, D, E, F], 0, size) @@ -230,7 +230,7 @@ func Zip6[A any, B any, C any, D any, E any, F any](a []A, b []B, c []C, d []D, // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip7[A any, B any, C any, D any, E any, F any, G any](a []A, b []B, c []C, d []D, e []E, f []F, g []G) []Tuple7[A, B, C, D, E, F, G] { +func Zip7[A, B, C, D, E, F, G any](a []A, b []B, c []C, d []D, e []E, f []F, g []G) []Tuple7[A, B, C, D, E, F, G] { size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g)}) result := make([]Tuple7[A, B, C, D, E, F, G], 0, size) @@ -262,7 +262,7 @@ func Zip7[A any, B any, C any, D any, E any, F any, G any](a []A, b []B, c []C, // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip8[A any, B any, C any, D any, E any, F any, G any, H any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H) []Tuple8[A, B, C, D, E, F, G, H] { +func Zip8[A, B, C, D, E, F, G, H any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H) []Tuple8[A, B, C, D, E, F, G, H] { size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g), len(h)}) result := make([]Tuple8[A, B, C, D, E, F, G, H], 0, size) @@ -296,7 +296,7 @@ func Zip8[A any, B any, C any, D any, E any, F any, G any, H any](a []A, b []B, // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip9[A any, B any, C any, D any, E any, F any, G any, H any, I any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H, i []I) []Tuple9[A, B, C, D, E, F, G, H, I] { +func Zip9[A, B, C, D, E, F, G, H, I any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H, i []I) []Tuple9[A, B, C, D, E, F, G, H, I] { size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g), len(h), len(i)}) result := make([]Tuple9[A, B, C, D, E, F, G, H, I], 0, size) @@ -328,17 +328,189 @@ func Zip9[A any, B any, C any, D any, E any, F any, G any, H any, I any](a []A, return result } +// ZipBy2 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy2[A any, B any, Out any](a []A, b []B, iteratee func(a A, b B) Out) []Out { + size := Max([]int{len(a), len(b)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + + result = append(result, iteratee(_a, _b)) + } + + return result +} + +// ZipBy3 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy3[A any, B any, C any, Out any](a []A, b []B, c []C, iteratee func(a A, b B, c C) Out) []Out { + size := Max([]int{len(a), len(b), len(c)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + + result = append(result, iteratee(_a, _b, _c)) + } + + return result +} + +// ZipBy4 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy4[A any, B any, C any, D any, Out any](a []A, b []B, c []C, d []D, iteratee func(a A, b B, c C, d D) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + + result = append(result, iteratee(_a, _b, _c, _d)) + } + + return result +} + +// ZipBy5 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy5[A any, B any, C any, D any, E any, Out any](a []A, b []B, c []C, d []D, e []E, iteratee func(a A, b B, c C, d D, e E) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e)) + } + + return result +} + +// ZipBy6 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy6[A any, B any, C any, D any, E any, F any, Out any](a []A, b []B, c []C, d []D, e []E, f []F, iteratee func(a A, b B, c C, d D, e E, f F) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e, _f)) + } + + return result +} + +// ZipBy7 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy7[A any, B any, C any, D any, E any, F any, G any, Out any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, iteratee func(a A, b B, c C, d D, e E, f F, g G) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + _g, _ := Nth(g, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e, _f, _g)) + } + + return result +} + +// ZipBy8 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy8[A any, B any, C any, D any, E any, F any, G any, H any, Out any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H, iteratee func(a A, b B, c C, d D, e E, f F, g G, h H) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + _g, _ := Nth(g, index) + _h, _ := Nth(h, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e, _f, _g, _h)) + } + + return result +} + +// ZipBy9 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy9[A any, B any, C any, D any, E any, F any, G any, H any, I any, Out any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H, i []I, iteratee func(a A, b B, c C, d D, e E, f F, g G, h H, i I) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g), len(h), len(i)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + _g, _ := Nth(g, index) + _h, _ := Nth(h, index) + _i, _ := Nth(i, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e, _f, _g, _h, _i)) + } + + return result +} + // Unzip2 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip2[A any, B any](tuples []Tuple2[A, B]) ([]A, []B) { +func Unzip2[A, B any](tuples []Tuple2[A, B]) ([]A, []B) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) } return r1, r2 @@ -347,16 +519,16 @@ func Unzip2[A any, B any](tuples []Tuple2[A, B]) ([]A, []B) { // Unzip3 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip3[A any, B any, C any](tuples []Tuple3[A, B, C]) ([]A, []B, []C) { +func Unzip3[A, B, C any](tuples []Tuple3[A, B, C]) ([]A, []B, []C) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) r3 := make([]C, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) } return r1, r2, r3 @@ -365,18 +537,18 @@ func Unzip3[A any, B any, C any](tuples []Tuple3[A, B, C]) ([]A, []B, []C) { // Unzip4 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip4[A any, B any, C any, D any](tuples []Tuple4[A, B, C, D]) ([]A, []B, []C, []D) { +func Unzip4[A, B, C, D any](tuples []Tuple4[A, B, C, D]) ([]A, []B, []C, []D) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) r3 := make([]C, 0, size) r4 := make([]D, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) - r4 = append(r4, tuple.D) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) } return r1, r2, r3, r4 @@ -385,7 +557,7 @@ func Unzip4[A any, B any, C any, D any](tuples []Tuple4[A, B, C, D]) ([]A, []B, // Unzip5 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip5[A any, B any, C any, D any, E any](tuples []Tuple5[A, B, C, D, E]) ([]A, []B, []C, []D, []E) { +func Unzip5[A, B, C, D, E any](tuples []Tuple5[A, B, C, D, E]) ([]A, []B, []C, []D, []E) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) @@ -393,12 +565,12 @@ func Unzip5[A any, B any, C any, D any, E any](tuples []Tuple5[A, B, C, D, E]) ( r4 := make([]D, 0, size) r5 := make([]E, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) - r4 = append(r4, tuple.D) - r5 = append(r5, tuple.E) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) } return r1, r2, r3, r4, r5 @@ -407,7 +579,7 @@ func Unzip5[A any, B any, C any, D any, E any](tuples []Tuple5[A, B, C, D, E]) ( // Unzip6 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip6[A any, B any, C any, D any, E any, F any](tuples []Tuple6[A, B, C, D, E, F]) ([]A, []B, []C, []D, []E, []F) { +func Unzip6[A, B, C, D, E, F any](tuples []Tuple6[A, B, C, D, E, F]) ([]A, []B, []C, []D, []E, []F) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) @@ -416,13 +588,13 @@ func Unzip6[A any, B any, C any, D any, E any, F any](tuples []Tuple6[A, B, C, D r5 := make([]E, 0, size) r6 := make([]F, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) - r4 = append(r4, tuple.D) - r5 = append(r5, tuple.E) - r6 = append(r6, tuple.F) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) + r6 = append(r6, tuples[i].F) } return r1, r2, r3, r4, r5, r6 @@ -431,7 +603,7 @@ func Unzip6[A any, B any, C any, D any, E any, F any](tuples []Tuple6[A, B, C, D // Unzip7 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip7[A any, B any, C any, D any, E any, F any, G any](tuples []Tuple7[A, B, C, D, E, F, G]) ([]A, []B, []C, []D, []E, []F, []G) { +func Unzip7[A, B, C, D, E, F, G any](tuples []Tuple7[A, B, C, D, E, F, G]) ([]A, []B, []C, []D, []E, []F, []G) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) @@ -441,14 +613,14 @@ func Unzip7[A any, B any, C any, D any, E any, F any, G any](tuples []Tuple7[A, r6 := make([]F, 0, size) r7 := make([]G, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) - r4 = append(r4, tuple.D) - r5 = append(r5, tuple.E) - r6 = append(r6, tuple.F) - r7 = append(r7, tuple.G) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) + r6 = append(r6, tuples[i].F) + r7 = append(r7, tuples[i].G) } return r1, r2, r3, r4, r5, r6, r7 @@ -457,7 +629,7 @@ func Unzip7[A any, B any, C any, D any, E any, F any, G any](tuples []Tuple7[A, // Unzip8 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip8[A any, B any, C any, D any, E any, F any, G any, H any](tuples []Tuple8[A, B, C, D, E, F, G, H]) ([]A, []B, []C, []D, []E, []F, []G, []H) { +func Unzip8[A, B, C, D, E, F, G, H any](tuples []Tuple8[A, B, C, D, E, F, G, H]) ([]A, []B, []C, []D, []E, []F, []G, []H) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) @@ -468,15 +640,15 @@ func Unzip8[A any, B any, C any, D any, E any, F any, G any, H any](tuples []Tup r7 := make([]G, 0, size) r8 := make([]H, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) - r4 = append(r4, tuple.D) - r5 = append(r5, tuple.E) - r6 = append(r6, tuple.F) - r7 = append(r7, tuple.G) - r8 = append(r8, tuple.H) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) + r6 = append(r6, tuples[i].F) + r7 = append(r7, tuples[i].G) + r8 = append(r8, tuples[i].H) } return r1, r2, r3, r4, r5, r6, r7, r8 @@ -485,7 +657,7 @@ func Unzip8[A any, B any, C any, D any, E any, F any, G any, H any](tuples []Tup // Unzip9 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip9[A any, B any, C any, D any, E any, F any, G any, H any, I any](tuples []Tuple9[A, B, C, D, E, F, G, H, I]) ([]A, []B, []C, []D, []E, []F, []G, []H, []I) { +func Unzip9[A, B, C, D, E, F, G, H, I any](tuples []Tuple9[A, B, C, D, E, F, G, H, I]) ([]A, []B, []C, []D, []E, []F, []G, []H, []I) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) @@ -497,16 +669,200 @@ func Unzip9[A any, B any, C any, D any, E any, F any, G any, H any, I any](tuple r8 := make([]H, 0, size) r9 := make([]I, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) - r4 = append(r4, tuple.D) - r5 = append(r5, tuple.E) - r6 = append(r6, tuple.F) - r7 = append(r7, tuple.G) - r8 = append(r8, tuple.H) - r9 = append(r9, tuple.I) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) + r6 = append(r6, tuples[i].F) + r7 = append(r7, tuples[i].G) + r8 = append(r8, tuples[i].H) + r9 = append(r9, tuples[i].I) + } + + return r1, r2, r3, r4, r5, r6, r7, r8, r9 +} + +// UnzipBy2 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy2[In any, A any, B any](items []In, iteratee func(In) (a A, b B)) ([]A, []B) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + + for i := range items { + a, b := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + } + + return r1, r2 +} + +// UnzipBy3 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy3[In any, A any, B any, C any](items []In, iteratee func(In) (a A, b B, c C)) ([]A, []B, []C) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + + for i := range items { + a, b, c := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + } + + return r1, r2, r3 +} + +// UnzipBy4 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy4[In any, A any, B any, C any, D any](items []In, iteratee func(In) (a A, b B, c C, d D)) ([]A, []B, []C, []D) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + + for i := range items { + a, b, c, d := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + } + + return r1, r2, r3, r4 +} + +// UnzipBy5 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy5[In any, A any, B any, C any, D any, E any](items []In, iteratee func(In) (a A, b B, c C, d D, e E)) ([]A, []B, []C, []D, []E) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + + for i := range items { + a, b, c, d, e := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + } + + return r1, r2, r3, r4, r5 +} + +// UnzipBy6 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy6[In any, A any, B any, C any, D any, E any, F any](items []In, iteratee func(In) (a A, b B, c C, d D, e E, f F)) ([]A, []B, []C, []D, []E, []F) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + + for i := range items { + a, b, c, d, e, f := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + r6 = append(r6, f) + } + + return r1, r2, r3, r4, r5, r6 +} + +// UnzipBy7 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy7[In any, A any, B any, C any, D any, E any, F any, G any](items []In, iteratee func(In) (a A, b B, c C, d D, e E, f F, g G)) ([]A, []B, []C, []D, []E, []F, []G) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + r7 := make([]G, 0, size) + + for i := range items { + a, b, c, d, e, f, g := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + r6 = append(r6, f) + r7 = append(r7, g) + } + + return r1, r2, r3, r4, r5, r6, r7 +} + +// UnzipBy8 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy8[In any, A any, B any, C any, D any, E any, F any, G any, H any](items []In, iteratee func(In) (a A, b B, c C, d D, e E, f F, g G, h H)) ([]A, []B, []C, []D, []E, []F, []G, []H) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + r7 := make([]G, 0, size) + r8 := make([]H, 0, size) + + for i := range items { + a, b, c, d, e, f, g, h := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + r6 = append(r6, f) + r7 = append(r7, g) + r8 = append(r8, h) + } + + return r1, r2, r3, r4, r5, r6, r7, r8 +} + +// UnzipBy9 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy9[In any, A any, B any, C any, D any, E any, F any, G any, H any, I any](items []In, iteratee func(In) (a A, b B, c C, d D, e E, f F, g G, h H, i I)) ([]A, []B, []C, []D, []E, []F, []G, []H, []I) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + r7 := make([]G, 0, size) + r8 := make([]H, 0, size) + r9 := make([]I, 0, size) + + for i := range items { + a, b, c, d, e, f, g, h, i := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + r6 = append(r6, f) + r7 = append(r7, g) + r8 = append(r8, h) + r9 = append(r9, i) } return r1, r2, r3, r4, r5, r6, r7, r8, r9 diff --git a/vendor/github.com/samber/lo/type_manipulation.go b/vendor/github.com/samber/lo/type_manipulation.go index 45d8fe2037..ef070281aa 100644 --- a/vendor/github.com/samber/lo/type_manipulation.go +++ b/vendor/github.com/samber/lo/type_manipulation.go @@ -2,11 +2,22 @@ package lo import "reflect" +// IsNil checks if a value is nil or if it's a reference type with a nil underlying value. +func IsNil(x any) bool { + defer func() { recover() }() // nolint:errcheck + return x == nil || reflect.ValueOf(x).IsNil() +} + // ToPtr returns a pointer copy of value. func ToPtr[T any](x T) *T { return &x } +// Nil returns a nil pointer of type. +func Nil[T any]() *T { + return nil +} + // EmptyableToPtr returns a pointer copy of value if it's nonzero. // Otherwise, returns nil pointer. func EmptyableToPtr[T any](x T) *T { @@ -39,16 +50,40 @@ func FromPtrOr[T any](x *T, fallback T) T { // ToSlicePtr returns a slice of pointer copy of value. func ToSlicePtr[T any](collection []T) []*T { - return Map(collection, func(x T, _ int) *T { - return &x + result := make([]*T, len(collection)) + + for i := range collection { + result[i] = &collection[i] + } + return result +} + +// FromSlicePtr returns a slice with the pointer values. +// Returns a zero value in case of a nil pointer element. +func FromSlicePtr[T any](collection []*T) []T { + return Map(collection, func(x *T, _ int) T { + if x == nil { + return Empty[T]() + } + return *x + }) +} + +// FromSlicePtr returns a slice with the pointer values or the fallback value. +func FromSlicePtrOr[T any](collection []*T, fallback T) []T { + return Map(collection, func(x *T, _ int) T { + if x == nil { + return fallback + } + return *x }) } // ToAnySlice returns a slice with all elements mapped to `any` type func ToAnySlice[T any](collection []T) []any { result := make([]any, len(collection)) - for i, item := range collection { - result[i] = item + for i := range collection { + result[i] = collection[i] } return result } @@ -64,8 +99,8 @@ func FromAnySlice[T any](in []any) (out []T, ok bool) { }() result := make([]T, len(in)) - for i, item := range in { - result[i] = item.(T) + for i := range in { + result[i] = in[i].(T) } return result, true } @@ -89,10 +124,10 @@ func IsNotEmpty[T comparable](v T) bool { } // Coalesce returns the first non-empty arguments. Arguments must be comparable. -func Coalesce[T comparable](v ...T) (result T, ok bool) { - for _, e := range v { - if e != result { - result = e +func Coalesce[T comparable](values ...T) (result T, ok bool) { + for i := range values { + if values[i] != result { + result = values[i] ok = true return } @@ -100,3 +135,9 @@ func Coalesce[T comparable](v ...T) (result T, ok bool) { return } + +// CoalesceOrEmpty returns the first non-empty arguments. Arguments must be comparable. +func CoalesceOrEmpty[T comparable](v ...T) T { + result, _ := Coalesce(v...) + return result +} diff --git a/vendor/github.com/samber/lo/types.go b/vendor/github.com/samber/lo/types.go index 271c5b4fdf..1c6f0d0057 100644 --- a/vendor/github.com/samber/lo/types.go +++ b/vendor/github.com/samber/lo/types.go @@ -7,7 +7,7 @@ type Entry[K comparable, V any] struct { } // Tuple2 is a group of 2 elements (pair). -type Tuple2[A any, B any] struct { +type Tuple2[A, B any] struct { A A B B } @@ -18,7 +18,7 @@ func (t Tuple2[A, B]) Unpack() (A, B) { } // Tuple3 is a group of 3 elements. -type Tuple3[A any, B any, C any] struct { +type Tuple3[A, B, C any] struct { A A B B C C @@ -30,7 +30,7 @@ func (t Tuple3[A, B, C]) Unpack() (A, B, C) { } // Tuple4 is a group of 4 elements. -type Tuple4[A any, B any, C any, D any] struct { +type Tuple4[A, B, C, D any] struct { A A B B C C @@ -43,7 +43,7 @@ func (t Tuple4[A, B, C, D]) Unpack() (A, B, C, D) { } // Tuple5 is a group of 5 elements. -type Tuple5[A any, B any, C any, D any, E any] struct { +type Tuple5[A, B, C, D, E any] struct { A A B B C C @@ -57,7 +57,7 @@ func (t Tuple5[A, B, C, D, E]) Unpack() (A, B, C, D, E) { } // Tuple6 is a group of 6 elements. -type Tuple6[A any, B any, C any, D any, E any, F any] struct { +type Tuple6[A, B, C, D, E, F any] struct { A A B B C C @@ -72,7 +72,7 @@ func (t Tuple6[A, B, C, D, E, F]) Unpack() (A, B, C, D, E, F) { } // Tuple7 is a group of 7 elements. -type Tuple7[A any, B any, C any, D any, E any, F any, G any] struct { +type Tuple7[A, B, C, D, E, F, G any] struct { A A B B C C @@ -88,7 +88,7 @@ func (t Tuple7[A, B, C, D, E, F, G]) Unpack() (A, B, C, D, E, F, G) { } // Tuple8 is a group of 8 elements. -type Tuple8[A any, B any, C any, D any, E any, F any, G any, H any] struct { +type Tuple8[A, B, C, D, E, F, G, H any] struct { A A B B C C @@ -105,7 +105,7 @@ func (t Tuple8[A, B, C, D, E, F, G, H]) Unpack() (A, B, C, D, E, F, G, H) { } // Tuple9 is a group of 9 elements. -type Tuple9[A any, B any, C any, D any, E any, F any, G any, H any, I any] struct { +type Tuple9[A, B, C, D, E, F, G, H, I any] struct { A A B B C C diff --git a/vendor/modules.txt b/vendor/modules.txt index 5556e5cbbb..844504bef3 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -34,7 +34,6 @@ github.com/Azure/azure-pipeline-go/pipeline # github.com/Azure/azure-sdk-for-go v68.0.0+incompatible ## explicit github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute -github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network github.com/Azure/azure-sdk-for-go/storage github.com/Azure/azure-sdk-for-go/version # github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0 @@ -147,9 +146,6 @@ github.com/Azure/go-autorest/autorest/adal # github.com/Azure/go-autorest/autorest/date v0.3.0 ## explicit; go 1.12 github.com/Azure/go-autorest/autorest/date -# github.com/Azure/go-autorest/autorest/mocks v0.4.2 -## explicit; go 1.15 -github.com/Azure/go-autorest/autorest/mocks # github.com/Azure/go-autorest/autorest/to v0.4.0 ## explicit; go 1.12 github.com/Azure/go-autorest/autorest/to @@ -444,9 +440,11 @@ github.com/prometheus/common/model github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util -# github.com/samber/lo v1.38.1 +# github.com/samber/lo v1.47.0 ## explicit; go 1.18 github.com/samber/lo +github.com/samber/lo/internal/constraints +github.com/samber/lo/internal/rand # github.com/shopspring/decimal v1.3.1 ## explicit; go 1.13 github.com/shopspring/decimal